diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 247d6efb3..fbbd40d11 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,6 +27,14 @@ jobs: run: | cd ${{ github.workspace }}/build ninja + - name: Package Amnesia + working-directory: ./build + run: tar -czvf ../amnesia-linux-x86-64-release.tar.gz * + - name: Upload Amnesia artifact + uses: actions/upload-artifact@v3 + with: + name: amnesia-linux-x86-64-release + path: amnesia-linux-x86-64-release.tar.gz windows: runs-on: windows-latest steps: @@ -50,4 +58,12 @@ jobs: - name: Build run: | cd ${{ github.workspace }}\build - msbuild ALL_BUILD.vcxproj /property:Configuration=Release \ No newline at end of file + msbuild ALL_BUILD.vcxproj /property:Configuration=Release + - name: Package Amnesia + working-directory: .\build + run: 7z a ..\amnesia-win-x86-64-release.zip * + - name: Upload Amnesia artifact + uses: actions/upload-artifact@v3 + with: + name: amnesia-win-x86-64-release + path: amnesia-win-x86-64-release.zip \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8bf78173d..01b7133dd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -36,7 +36,7 @@ jobs: - name: Zipping (Windows) run: | cd ${{ github.workspace }}/build - 7z a Amnesia_windows_x68_64_${{ github.event.inputs.tag }}.zip amnesia/Release + 7z a Amnesia_windows_x68_64_${{ github.event.inputs.tag }}.zip * - uses: actions/upload-artifact@master with: name: windows-build-artifacts diff --git a/.gitignore b/.gitignore index b8bfcf403..c20d9d75a 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ mono_crash.* # Build results +build/ [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ @@ -30,10 +31,6 @@ bld/ [Oo]bj/ [Ll]og/ [Ll]ogs/ -.[Bb]uild/ -[Bb]uild/ -vcpkg_installed/ -/out/ # Visual Studio 2015/2017 cache/options directory .vs/ @@ -353,8 +350,16 @@ MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder .ionide/ -lib/ - +# HPL2 Specific BuildID_*.cpp BuildID_*.h -cmake-build-debug/ \ No newline at end of file +CMakeCache.txt +vcpkg_installed/ +CMakeFiles/ + +Makefile +cmake_install.cmake +*.a + +/HPL2/Shaders +/HPL2/CompiledShaders \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index f103a19fa..3fa643194 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,8 @@ cmake_minimum_required(VERSION 3.21) set(CMAKE_CXX_STANDARD 20) set(INSTALL_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR}/bin) set(CMAKE_INSTALL_PREFIX ${INSTALL_OUTPUT_PATH} CACHE PATH "Install path prefix, prepended onto install directories." FORCE) +set(CMAKE_MODULE_PATH ${CMAKE_HOME_DIRECTORY}/cmake) +include(HPLUtils) enable_language(ASM) @@ -14,12 +16,6 @@ if(UNIX) endif() include("${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake") -add_definitions( - -DUSE_THE_FORGE_LEGACY - # -DUSE_FORWARD_PLUS_BACKEND # prototype forward renderer -) - - # hack to get to build on windwos # HACK to correctly set Linux property for newer cmake if(NOT APPLE AND UNIX) diff --git a/HPL2/CMakeLists.txt b/HPL2/CMakeLists.txt index 471503733..2d85addd9 100644 --- a/HPL2/CMakeLists.txt +++ b/HPL2/CMakeLists.txt @@ -185,7 +185,7 @@ source_group("Platform" REGULAR_EXPRESSION "\\/impl\\/Platform.+") # setup libs -set(OpenGL_GL_PREFERENCE LEGACY) +# set(OpenGL_GL_PREFERENCE LEGACY) find_package(DevIL REQUIRED) find_package(OpenGL REQUIRED) find_package(ZLIB REQUIRED) diff --git a/HPL2/include/graphics/DebugDraw.h b/HPL2/include/graphics/DebugDraw.h index e116b15e6..04a31282a 100644 --- a/HPL2/include/graphics/DebugDraw.h +++ b/HPL2/include/graphics/DebugDraw.h @@ -33,8 +33,8 @@ class DebugDraw final { Count }; - static constexpr uint32_t ImmediateVertexBufferSize = 1 << 25; - static constexpr uint32_t ImmediateIndexBufferSize = 1 << 23; + static constexpr uint32_t ImmediateVertexBufferSize = 1 << 10; + static constexpr uint32_t ImmediateIndexBufferSize = 1 << 10; static constexpr uint32_t NumberOfPerFrameUniforms = 32; static constexpr uint32_t NumberOfTextureUnits = 512; @@ -131,8 +131,6 @@ class DebugDraw final { mat4 m_viewProj2DMat; }; - GPURingBuffer* m_vertexBuffer = nullptr; - GPURingBuffer* m_indexBuffer = nullptr; std::array m_viewBufferUniform; uint32_t m_frameIndex = 0; uint32_t m_activeFrame = 0; diff --git a/HPL2/include/graphics/DrawPacket.h b/HPL2/include/graphics/DrawPacket.h index b89407ad6..9dc3a891b 100644 --- a/HPL2/include/graphics/DrawPacket.h +++ b/HPL2/include/graphics/DrawPacket.h @@ -23,6 +23,7 @@ namespace hpl { uint32_t m_numStreams; struct { SharedBuffer* m_buffer; + eVertexBufferElement m_element; uint64_t m_offset; uint32_t m_stride; } m_vertexStream[MaxVertexBindings]; @@ -33,8 +34,6 @@ namespace hpl { }; struct GeometrySetBinding { - uint32_t m_numStreams; - eVertexBufferElement m_elements[MaxVertexBindings]; GraphicsAllocator::AllocationSet m_set; GeometrySet::GeometrySetSubAllocation* m_subAllocation; uint32_t m_numIndices; @@ -51,7 +50,7 @@ namespace hpl { return 0; } - static void cmdBindBuffers(Cmd* cmd, ForgeRenderer::CommandResourcePool* resourcePool, DrawPacket* packet); + static void cmdBindBuffers(Cmd* cmd, ForgeRenderer::CommandResourcePool* resourcePool, DrawPacket* packet, std::span elements); DrawPacket() : m_type(DrawPacketType::Unknown) { diff --git a/HPL2/include/graphics/ForgeRenderer.h b/HPL2/include/graphics/ForgeRenderer.h index 717959758..300cc298a 100644 --- a/HPL2/include/graphics/ForgeRenderer.h +++ b/HPL2/include/graphics/ForgeRenderer.h @@ -11,6 +11,7 @@ #include +#include "Common_3/Utilities/RingBuffer.h" #include "graphics/ForgeHandles.h" #include "windowing/NativeWindow.h" #include "engine/QueuedEventLoopHandler.h" @@ -54,13 +55,12 @@ namespace hpl { CopyPipelineCount = 2 }; + static constexpr uint32_t MaxCopyFrames = 32; static constexpr uint32_t SwapChainLength = 2; // double buffered static constexpr uint32_t ResourcePoolSize = 4; // double buffered void InitializeRenderer(window::NativeWindowWrapper* window); - void InitializeResource(); - RendererApi GetApi(); struct SamplerPoolKey { union { @@ -103,36 +103,58 @@ namespace hpl { /** * tracks the resources used by a single command buffer */ + //TODO: transiation this to Frame.h struct Frame { + public: uint32_t m_currentFrame = 0; uint32_t m_frameIndex = 0; uint32_t m_swapChainIndex = 0; + GpuCmdRingElement m_cmdRingElement; + bool m_isFinished = true; + + Frame() = default; + Frame(Frame& frame) = delete; + void operator=(Frame&) = delete; + ForgeRenderer* m_renderer = nullptr; - SwapChain* m_swapChain = nullptr; Cmd* m_cmd = nullptr; CmdPool* m_cmdPool = nullptr; Fence* m_renderCompleteFence = nullptr; Semaphore* m_renderCompleteSemaphore = nullptr; CommandResourcePool* m_resourcePool = nullptr; RenderTarget* m_finalRenderTarget = nullptr; - }; + std::vector m_waitSemaphores = {}; + + template + inline void pushResource(const T& ele) { + m_resourcePool->Push(ele); + } + + inline uint32_t FrameCount() { + return m_currentFrame; + } + + inline uint32_t index() { + return m_frameIndex; + } + + inline Cmd*& cmd() { + return m_cmdRingElement.pCmds[0]; + } + + inline RenderTarget* finalTarget() { + return m_finalRenderTarget; + } + inline GpuCmdRingElement& RingElement() { + return m_cmdRingElement; + } + + friend class ForgeRenderer; + }; - const inline Frame GetFrame() { - Frame frame; - frame.m_currentFrame = FrameCount(); - frame.m_frameIndex = CurrentFrameIndex(); - frame.m_swapChainIndex = SwapChainIndex(); - frame.m_renderer = this; - frame.m_swapChain = m_swapChain.m_handle; - - frame.m_cmd = m_cmds[CurrentFrameIndex()]; - frame.m_cmdPool = m_cmdPools[CurrentFrameIndex()]; - frame.m_renderCompleteFence = m_renderCompleteFences[CurrentFrameIndex()]; - frame.m_renderCompleteSemaphore = m_renderCompleteSemaphores[CurrentFrameIndex()]; - frame.m_resourcePool = &m_resourcePool[CurrentFrameIndex()]; - frame.m_finalRenderTarget = m_finalRenderTarget[CurrentFrameIndex()].m_handle; - return frame; + inline Frame& GetFrame() { + return m_frame; } // void BeginFrame() {} @@ -145,10 +167,6 @@ namespace hpl { } RootSignature* PipelineSignature() { return m_pipelineSignature; } - size_t SwapChainIndex() { return m_swapChainIndex; } - size_t CurrentFrameIndex() { return m_currentFrameCount % SwapChainLength; } - size_t FrameCount() { return m_currentFrameCount; } - inline SwapChain* GetSwapChain() { return m_swapChain.m_handle; } inline Queue* GetGraphicsQueue() { return m_graphicsQueue; } void cmdCopyTexture(Cmd* cmd, Texture* srcTexture, RenderTarget* dstTexture); @@ -158,17 +176,15 @@ namespace hpl { private: std::array m_samplerPool; std::array m_resourcePool; - std::array m_renderCompleteFences; - std::array m_renderCompleteSemaphores; std::array m_cmdPools; std::array m_cmds; std::array m_finalRenderTarget; - float m_gamma = 1.0f; - window::WindowEvent::QueuedEventHandler m_windowEventHandler; window::NativeWindowWrapper* m_window = nullptr; + GpuCmdRing m_graphicsCmdRing; + Renderer* m_renderer = nullptr; RootSignature* m_pipelineSignature = nullptr; SharedSwapChain m_swapChain; @@ -187,11 +203,14 @@ namespace hpl { SharedSampler m_pointSampler ; RootSignature* m_copyPostProcessingRootSignature = nullptr; - DescriptorSet* m_copyPostProcessingDescriptorSet = nullptr; + std::array m_copyPostProcessingDescriptorSet ; uint32_t m_copyRegionDescriptorIndex = 0; + float m_gamma = 1.0f; + uint32_t m_swapChainCount; + + + Frame m_frame; - uint32_t m_currentFrameCount = 0; - uint32_t m_swapChainIndex = 0; }; } // namespace hpl diff --git a/HPL2/include/graphics/ForwardResources.h b/HPL2/include/graphics/ForwardResources.h deleted file mode 100644 index bb9d225cc..000000000 --- a/HPL2/include/graphics/ForwardResources.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include "graphics/GraphicsTypes.h" -#include "graphics/TextureDescriptorPool.h" -#include "scene/LightPoint.h" -#include -#include -#include -#include - -namespace hpl::resource { - class iLight; - struct PointLightResource { - mat4 m_mvp; - float3 m_lightPos; - uint m_config; - float4 m_lightColor; - float m_radius; - }; - using LightResourceVariants = std::variant; - static LightResourceVariants CreateFromLight(iLight& light); - - struct DiffuseMaterial { - union { - uint m_texture[4]; - struct { - uint16_t m_diffues; - uint16_t m_normal; - - uint16_t m_alpha; - uint16_t m_specular; - - uint16_t m_height; - uint16_t m_illuminiation; - - uint16_t m_dissolveAlpha; - uint16_t m_cubeMapAlpha; - } m_tex; - }; - uint m_materialConfig; - float m_heightMapScale; - float m_heigtMapBias; - float m_frenselBias; - float m_frenselPow; - }; - using MaterialTypes = std::variant; - void visitTextures(MaterialTypes& material, std::function handler); - MaterialTypes createMaterial(TextureDescriptorPool& pool, cMaterial* material); -} diff --git a/HPL2/include/graphics/GeometrySet.h b/HPL2/include/graphics/GeometrySet.h index 982ef265b..146d2efa5 100644 --- a/HPL2/include/graphics/GeometrySet.h +++ b/HPL2/include/graphics/GeometrySet.h @@ -52,7 +52,7 @@ namespace hpl { inline SharedBuffer& indexBuffer() { return m_geometrySet->m_indexBuffer; } inline std::span vertexStreams() { return m_geometrySet->m_vertexStreams; } inline std::span::iterator getStreamBySemantic(ShaderSemantic semantic) {return m_geometrySet->getStreamBySemantic(semantic);} - inline uint32_t vertextOffset() { return m_vertexAllocation.offset; } + inline uint32_t vertexOffset() { return m_vertexAllocation.offset; } inline uint32_t indexOffset() { return m_indexAllocation.offset; } private: @@ -77,7 +77,7 @@ namespace hpl { inline SharedBuffer& indexBuffer() { return m_indexBuffer; } void operator=(GeometrySet&& set); void operator=(const GeometrySet& set) = delete; - std::shared_ptr allocate(uint32_t numElements, uint32_t numIndecies); + std::shared_ptr allocate(uint32_t numElements, uint32_t numIndecies); private: OffsetAllocator::Allocator m_vertexStreamAllocator; OffsetAllocator::Allocator m_indexStreamAllocator; diff --git a/HPL2/include/graphics/GraphicsAllocator.h b/HPL2/include/graphics/GraphicsAllocator.h index 8b83ccf0e..01b8ae6d8 100644 --- a/HPL2/include/graphics/GraphicsAllocator.h +++ b/HPL2/include/graphics/GraphicsAllocator.h @@ -8,6 +8,7 @@ #include "Common_3/Graphics/Interfaces/IGraphics.h" #include "Common_3/Utilities/RingBuffer.h" #include +#include "math/Math.h" namespace hpl { @@ -17,16 +18,20 @@ namespace hpl { enum AllocationSet { OpaqueSet, + ParticleSet, NumOfAllocationSets }; GraphicsAllocator(ForgeRenderer* renderer); - static constexpr uint32_t OpaqueVertexBufferSize = 1 << 25; - static constexpr uint32_t OpaqueIndexBufferSize = 1 << 23; + static constexpr uint32_t OpaqueVertexBufferSize = 6000000; + static constexpr uint32_t OpaqueIndexBufferSize = 3000000; - static constexpr uint32_t ImmediateVertexBufferSize = 1 << 25; - static constexpr uint32_t ImmediateIndexBufferSize = 1 << 23; + static constexpr uint32_t ParticleVertexBufferSize = 61440; + static constexpr uint32_t ParticleIndexBufferSize = 61440; + + static constexpr uint32_t ImmediateVertexBufferSize = hpl::Math::BYTE_MB * 30; + static constexpr uint32_t ImmediateIndexBufferSize = hpl::Math::BYTE_MB * 15; GPURingBufferOffset allocTransientVertexBuffer(uint32_t size); GPURingBufferOffset allocTransientIndexBuffer(uint32_t size); @@ -35,7 +40,7 @@ namespace hpl { std::array m_geometrySets; ForgeRenderer* m_renderer; - GPURingBuffer* m_transientVertexBuffer = nullptr; - GPURingBuffer* m_transientIndeciesBuffer = nullptr; + GPURingBuffer m_transientVertexBuffer{}; + GPURingBuffer m_transientIndeciesBuffer{}; }; } // namespace hpl diff --git a/HPL2/include/graphics/GraphicsBuffer.h b/HPL2/include/graphics/GraphicsBuffer.h index 516b86fae..ab8075466 100644 --- a/HPL2/include/graphics/GraphicsBuffer.h +++ b/HPL2/include/graphics/GraphicsBuffer.h @@ -239,10 +239,8 @@ namespace hpl { case BufferType::MappedBuffer: switch(m_indexType) { case IndexBufferType::Uint32: - ASSERT(m_asset->m_buffer.begin() + (m_byteOffset + (index * sizeof(uint32_t))) < m_asset->m_buffer.end()); return *reinterpret_cast(reinterpret_cast(m_asset->m_mapped.m_mappedData) + (m_byteOffset + (index * sizeof(uint32_t)))); case IndexBufferType::Uint16: - ASSERT(m_asset->m_buffer.begin() + (m_byteOffset + (index * sizeof(uint16_t))) < m_asset->m_buffer.end()); return *reinterpret_cast(reinterpret_cast(m_asset->m_mapped.m_mappedData) + (m_byteOffset + (index * sizeof(uint16_t)))); } break; @@ -399,8 +397,10 @@ namespace hpl { ASSERT(m_asset->m_buffer.begin() + targetOffset < m_asset->m_buffer.end()); return *reinterpret_cast(m_asset->m_buffer.data() + targetOffset); } - case BufferType::MappedBuffer: { - ASSERT(false); + case BufferType::MappedBuffer: + { + ASSERT(m_asset->m_mapped.m_size == 0 || targetOffset < m_asset->m_mapped.m_size); + return *reinterpret_cast(reinterpret_cast(m_asset->m_mapped.m_mappedData) + targetOffset); break; } } diff --git a/HPL2/include/graphics/GraphicsTypes.h b/HPL2/include/graphics/GraphicsTypes.h index 5d9e5ce9c..276a04e37 100644 --- a/HPL2/include/graphics/GraphicsTypes.h +++ b/HPL2/include/graphics/GraphicsTypes.h @@ -19,6 +19,7 @@ #pragma once +#include #include #include #include "graphics/Color.h" @@ -403,8 +404,12 @@ namespace hpl { eTextureType_LastEnum }; - //----------------------------------------- - + enum class TextureAntistropy: uint8_t{ + Antistropy_None = 0, + Antistropy_8 = 1, + Antistropy_16 = 2, + Antistropy_Count = 3 + }; enum eTextureWrap { @@ -554,7 +559,6 @@ namespace hpl { eMaterialTexture_CubeMap, eMaterialTexture_DissolveAlpha, eMaterialTexture_CubeMapAlpha, - eMaterialTexture_Special, //This means that the texture is not data in the material, but retrieved else where. Such as a reflection texture. eMaterialTexture_LastEnum }; @@ -626,7 +630,6 @@ namespace hpl { eShadowMapResolution_LastEnum, }; - //--------------------------------------- enum eShadowMapQuality { @@ -847,7 +850,9 @@ namespace hpl { //--------------------------------------- - extern tVertexElementFlag GetVertexElementFlagFromEnum(eVertexBufferElement aElement); + extern eShadowMapResolution GetShadowMapResolution(eShadowMapResolution aWanted, eShadowMapResolution aMax); + + extern tVertexElementFlag GetVertexElementFlagFromEnum(eVertexBufferElement aElement); extern int GetVertexFormatByteSize(eVertexBufferElementFormat aFormat); extern int GetVertexElementTextureUnit(eVertexBufferElement aElement); diff --git a/HPL2/include/graphics/IndexPool.h b/HPL2/include/graphics/IndexPool.h index ae63a6f51..9c216cfca 100644 --- a/HPL2/include/graphics/IndexPool.h +++ b/HPL2/include/graphics/IndexPool.h @@ -11,15 +11,19 @@ namespace hpl { class IndexPool { public: - IndexPool(uint32_t reserve); + explicit IndexPool(uint32_t reserve); + IndexPool(); + static constexpr uint32_t InvalidHandle = UINT32_MAX; uint32_t requestId(); + inline uint32_t reserve() {return m_reserve;} void returnId(uint32_t); private: struct IdRange { uint32_t m_start; uint32_t m_end; }; + uint32_t m_reserve; folly::small_vector m_avaliable; }; diff --git a/HPL2/include/graphics/Material.h b/HPL2/include/graphics/Material.h index c3013769d..1bb15081a 100644 --- a/HPL2/include/graphics/Material.h +++ b/HPL2/include/graphics/Material.h @@ -120,7 +120,8 @@ namespace hpl { class cMaterial : public iResourceBase { friend class iMaterialType; public: - static constexpr uint32_t MaxMaterialID = 2048; + static constexpr uint32_t MaxMaterialID = 2048; + static constexpr uint32_t MaxParticleMaterialID = 1024; static constexpr bool IsTranslucent(const MaterialID id) { return id == MaterialID::Water || id == MaterialID::Translucent || @@ -229,7 +230,7 @@ namespace hpl { inline uint32_t Generation() { return m_generation; } inline void IncreaseGeneration() { m_generation++; } private: - TextureAntistropy m_antistropy = Antistropy_None; + TextureAntistropy m_antistropy = TextureAntistropy::Antistropy_None; eTextureWrap m_textureWrap = eTextureWrap::eTextureWrap_Clamp; eTextureFilter m_textureFilter = eTextureFilter::eTextureFilter_Nearest; @@ -248,7 +249,6 @@ namespace hpl { bool mbAutoDestroyTextures = true; bool mbDepthTest = true; - }; }; diff --git a/HPL2/include/graphics/RenderList.h b/HPL2/include/graphics/RenderList.h index 8c4712252..52b996efb 100644 --- a/HPL2/include/graphics/RenderList.h +++ b/HPL2/include/graphics/RenderList.h @@ -19,82 +19,93 @@ #pragma once #include "graphics/Enum.h" +#include #include #include #include #include -#include namespace hpl { - class iRenderable; - class iLight; - class cFrustum; - class cFogArea; + class iRenderable; + class iLight; + class cFrustum; + class cFogArea; class iRenderableContainer; + class iRenderableContainerNode; + class cRenderList { + public: + cRenderList(); + ~cRenderList(); - class cRenderList - { - public: -// static bool DefaultSortZ(iRenderable* apObjectA, iRenderable* apObjectB); -// static bool DefaultSortDiffuse(iRenderable* apObjectA, iRenderable* apObjectB); -// static bool DefaultSortTranslucent(iRenderable* apObjectA, iRenderable* apObjectB); -// static bool DefaultSortDecal(iRenderable* apObjectA, iRenderable* apObjectB); -// static bool DefaultSortIllumination(iRenderable* apObjectA, iRenderable* apObjectB); - - cRenderList(); - ~cRenderList(); - - [[deprecated("use BeginAndReset")]] - void Setup(float afFrameTime, cFrustum *apFrustum); - [[deprecated("Use BeginAndReset")]] - void Clear(); + // can probably be repalced with iRenderableContainer::walkREnderableContainer + static void UpdateRenderListWalkAllNodesTestFrustumAndVisibility( + cRenderList& renderList, + cFrustum& frustum, + iRenderableContainerNode& apNode, + std::span clipPlanes, + tRenderableFlag neededFlags); - void AddObject(iRenderable *apObject); + void AddObject(iRenderable* apObject); - bool ArrayHasObjects(eRenderListType aType); + bool ArrayHasObjects(eRenderListType aType); - std::span GetRenderableItems(eRenderListType aType); - std::span GetOcclusionQueryItems(); - std::span GetTransObjects(); - std::span GetSolidObjects(); - std::span GetFogAreas(); - std::span GetLights(); + std::span GetRenderableItems(eRenderListType aType); + std::span GetOcclusionQueryItems(); + std::span GetTransObjects(); + std::span GetSolidObjects(); + std::span GetFogAreas(); + std::span GetLights(); void BeginAndReset(float frameTime, cFrustum* frustum); void End(tRenderListCompileFlag aFlags); - - iLight* GetLight(int alIdx){ return m_lights[alIdx];} - int GetLightNum(){ return(int)m_lights.size();} - - cFogArea* GetFogArea(int alIdx){ return m_fogAreas[alIdx];} - int GetFogAreaNum(){ return(int)m_fogAreas.size();} - - void PrintAllObjects(); - - //Temp: - int GetSolidObjectNum(){ return (int)m_solidObjects.size();} - iRenderable* GetSolidObject(int alIdx){ return m_solidObjects[alIdx];} - - int GetTransObjectNum(){ return (int)m_transObjects.size();} - iRenderable* GetTransObject(int alIdx){ return m_transObjects[alIdx];} - - private: - float m_frameTime = 0.0f; - cFrustum* m_frustum = nullptr; - - std::vector m_occlusionQueryObjects; - std::vector m_solidObjects; - std::vector m_transObjects; - std::vector m_decalObjects; - std::vector m_illumObjects; - std::vector m_lights; - std::vector m_fogAreas; - std::array,eRenderListType_LastEnum> m_sortedArrays; - }; - - //--------------------------------------------- - -}; + iLight* GetLight(int alIdx) { + return m_lights[alIdx]; + } + int GetLightNum() { + return (int)m_lights.size(); + } + + cFogArea* GetFogArea(int alIdx) { + return m_fogAreas[alIdx]; + } + int GetFogAreaNum() { + return (int)m_fogAreas.size(); + } + + void PrintAllObjects(); + + // Temp: + int GetSolidObjectNum() { + return (int)m_solidObjects.size(); + } + iRenderable* GetSolidObject(int alIdx) { + return m_solidObjects[alIdx]; + } + + int GetTransObjectNum() { + return (int)m_transObjects.size(); + } + iRenderable* GetTransObject(int alIdx) { + return m_transObjects[alIdx]; + } + + private: + float m_frameTime = 0.0f; + cFrustum* m_frustum = nullptr; + + std::vector m_occlusionQueryObjects; + std::vector m_solidObjects; + std::vector m_transObjects; + std::vector m_decalObjects; + std::vector m_illumObjects; + std::vector m_lights; + std::vector m_fogAreas; + std::array, eRenderListType_LastEnum> m_sortedArrays; + }; + + //--------------------------------------------- + +}; // namespace hpl diff --git a/HPL2/include/graphics/Renderable.h b/HPL2/include/graphics/Renderable.h index b2682fad8..08642cad7 100644 --- a/HPL2/include/graphics/Renderable.h +++ b/HPL2/include/graphics/Renderable.h @@ -53,7 +53,7 @@ namespace hpl { virtual cMaterial *GetMaterial()=0; virtual iVertexBuffer* GetVertexBuffer()=0; - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) = 0; + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) = 0; virtual bool CollidesWithBV(cBoundingVolume *apBV); virtual bool CollidesWithFrustum(cFrustum *apFrustum); @@ -119,6 +119,10 @@ namespace hpl { void SetRenderableUserData(void* apData) { mpRenderableUserData = apData; } void* GetRenderableUserData() { return mpRenderableUserData; } + + // utilities + static cRect2l GetClipRectFromObject(iRenderable& object, float afPaddingPercent, cFrustum* apFrustum, const cVector2l& avScreenSize); + static bool IsObjectIsVisible(iRenderable& object, tRenderableFlag neededFlags, std::span clipPlanes = {}); protected: virtual void OnUpdateWorldTransform() override; diff --git a/HPL2/include/graphics/Renderer.h b/HPL2/include/graphics/Renderer.h index 5b25c4211..c17ce5efa 100644 --- a/HPL2/include/graphics/Renderer.h +++ b/HPL2/include/graphics/Renderer.h @@ -64,39 +64,6 @@ namespace hpl { class RenderCallbackMessage; class iRenderer; - namespace rendering::detail { - - eShadowMapResolution GetShadowMapResolution(eShadowMapResolution aWanted, eShadowMapResolution aMax); - /** - * @brief Checks if the given object is occluded by the given planes. - * @param apObject The object to check. - * @param alNeededFlags The flags that the object must have to be considered. - * @param occlusionPlanes The planes to check against. - */ - bool IsObjectVisible(iRenderable *apObject, tRenderableFlag alNeededFlags, std::span occlusionPlanes); - - bool IsRenderableNodeIsVisible(iRenderableContainerNode* apNode, std::span clipPlanes); - bool IsObjectIsVisible(iRenderable* object, tRenderableFlag neededFlags, std::span clipPlanes = {}); - - void WalkAndPrepareRenderList(iRenderableContainer* container,cFrustum* frustum, std::function handler, tRenderableFlag renderableFlag); - - void UpdateRenderListWalkAllNodesTestFrustumAndVisibility( - cRenderList* apRenderList, - cFrustum* frustum, - iRenderableContainerNode* apNode, - std::span clipPlanes, - tRenderableFlag neededFlags); - - void UpdateRenderListWalkAllNodesTestFrustumAndVisibility( - cRenderList* apRenderList, - cFrustum* frustum, - iRenderableContainer* apContainer, - std::span clipPlanes, - tRenderableFlag neededFlags); - - cRect2l GetClipRectFromObject(iRenderable* apObject, float afPaddingPercent, cFrustum* apFrustum, const cVector2l& avScreenSize, float afHalfFovTan); - } - class cRenderSettings { public: @@ -159,13 +126,13 @@ namespace hpl { // ensure the contents is copied to the RenderViewport virtual void Draw( Cmd* cmd, - const ForgeRenderer::Frame& context, + ForgeRenderer::Frame& context, cViewport& viewport, float afFrameTime, cFrustum* apFrustum, cWorld* apWorld, - cRenderSettings* apSettings, - bool abSendFrameBufferToPostEffects) = 0; + cRenderSettings* apSettings + ) = 0; void Update(float afTimeStep); @@ -196,7 +163,6 @@ namespace hpl { bool abSendFrameBufferToPostEffects, bool abAtStartOfRendering=true); cResources* mpResources; - float mfCurrentFrameTime; cRenderSettings *mpCurrentSettings; static int mlRenderFrameCount; diff --git a/HPL2/include/graphics/RendererDeferred.h b/HPL2/include/graphics/RendererDeferred.h index 352138452..7c41845fd 100644 --- a/HPL2/include/graphics/RendererDeferred.h +++ b/HPL2/include/graphics/RendererDeferred.h @@ -87,7 +87,6 @@ namespace hpl { static constexpr uint32_t MaxMaterialSamplers = static_cast(eTextureWrap_LastEnum) * static_cast(eTextureFilter_LastEnum) * static_cast(cMaterial::TextureAntistropy::Antistropy_Count); static constexpr uint32_t MaxObjectTest = 32768; static constexpr uint32_t MaxOcclusionDescSize = 4096; - static constexpr uint32_t MaxQueryPoolSize = MaxOcclusionDescSize * 2; static constexpr uint32_t TranslucencyBlendModeMask = 0xf; @@ -310,30 +309,45 @@ namespace hpl { } }; + + struct QueryCoverageData { + struct CoverageQuery { + uint32_t m_queryIndex; + uint32_t m_maxQueryIndex; + }; + uint32_t m_queryIndex; + SharedQueryPool m_occlusionQuery; + folly::F14FastMap m_coverageQueries; + }; + struct ViewportData { public: ViewportData() = default; ViewportData(const ViewportData&) = delete; - ViewportData(ViewportData&& buffer) - : m_size(buffer.m_size) - , m_refractionImage(std::move(buffer.m_refractionImage)) - , m_gBuffer(std::move(buffer.m_gBuffer)) - , m_reflectionBuffer(std::move(buffer.m_reflectionBuffer)) { + ViewportData(ViewportData&& viewportData) + : m_size(viewportData.m_size) + , m_refractionImage(std::move(viewportData.m_refractionImage)) + , m_gBuffer(std::move(viewportData.m_gBuffer)) + , m_reflectionBuffer(std::move(viewportData.m_reflectionBuffer)) + , m_query(std::move(viewportData.m_query)) { } ViewportData& operator=(const ViewportData&) = delete; - void operator=(ViewportData&& buffer) { - m_size = buffer.m_size; - m_refractionImage = std::move(buffer.m_refractionImage); - m_gBuffer = std::move(buffer.m_gBuffer); - m_reflectionBuffer = std::move(buffer.m_reflectionBuffer); + void operator=(ViewportData&& viewportData) { + m_size = viewportData.m_size; + m_refractionImage = std::move(viewportData.m_refractionImage); + m_gBuffer = std::move(viewportData.m_gBuffer); + m_reflectionBuffer = std::move(viewportData.m_reflectionBuffer); + m_query = std::move(viewportData.m_query); } cVector2l m_size = cVector2l(0, 0); std::array m_gBuffer; std::array m_reflectionBuffer; std::shared_ptr m_refractionImage; + + QueryCoverageData m_query; }; cRendererDeferred( @@ -353,16 +367,14 @@ namespace hpl { return sharedData->m_gBuffer[frameIndex].m_outputBuffer; } - virtual void Draw( Cmd* cmd, - const ForgeRenderer::Frame& frame, + ForgeRenderer::Frame& context, cViewport& viewport, float afFrameTime, cFrustum* apFrustum, cWorld* apWorld, - cRenderSettings* apSettings, - bool abSendFrameBufferToPostEffects) override; + cRenderSettings* apSettings) override; private: iVertexBuffer* GetLightShape(iLight* apLight, eDeferredShapeQuality aQuality) const; @@ -428,17 +440,16 @@ namespace hpl { tRenderableFlag objectVisibilityFlags = eRenderableFlag_VisibleInNonReflection; std::span clipPlanes = {}; bool m_invert = false; - bool m_disableOcclusionQueries = false; + QueryCoverageData* m_query; }; - void cmdPreAndPostZ( + + void cmdPreZ( Cmd* cmd, cWorld* apWorld, - std::set& prePassRenderables, const ForgeRenderer::Frame& frame, cRenderList& renderList, float frameTime, RenderTarget* depthBuffer, - RenderTarget* hiZBuffer, cFrustum* apFrustum, uint32_t frameDescriptorIndex, cMatrixf viewMat, @@ -628,53 +639,14 @@ namespace hpl { } m_materialSet; uint32_t m_activeFrame = 0; // tracks the active frame if differnt then we need to reset some state - SharedCmdPool m_prePassPool; - SharedCmd m_prePassCmd; - SharedFence m_prePassFence; - - SharedRootSignature m_rootSignatureHIZOcclusion; - SharedShader m_ShaderHIZGenerate; - SharedShader m_shaderTestOcclusion; - SharedDescriptorSet m_descriptorSetHIZGenerate; - SharedPipeline m_pipelineHIZGenerate; - - SharedRootSignature m_rootSignatureCopyDepth; - SharedDescriptorSet m_descriptorCopyDepth; - SharedDescriptorSet m_descriptorAABBOcclusionTest; - SharedPipeline m_pipelineCopyDepth; - SharedPipeline m_pipelineAABBOcclusionTest; - SharedShader m_copyDepthShader; - SharedBuffer m_hiZOcclusionUniformBuffer; - SharedBuffer m_hiZBoundBoxBuffer; - SharedBuffer m_occlusionTestBuffer; - - struct OcclusionQueryAlpha { - iRenderable* m_renderable = nullptr; - uint32_t m_maxQueryIndex = 0; - uint32_t m_queryIndex = 0; - }; - - SharedQueryPool m_occlusionQuery; uint32_t m_occlusionIndex = 0; SharedBuffer m_occlusionUniformBuffer; SharedRootSignature m_rootSignatureOcclusuion; SharedDescriptorSet m_descriptorOcclusionConstSet; - SharedBuffer m_occlusionReadBackBuffer; SharedShader m_shaderOcclusionQuery; SharedPipeline m_pipelineMaxOcclusionQuery; SharedPipeline m_pipelineOcclusionQuery; - struct UniformTest { - bool m_preZPass = false; - iRenderable* m_renderable = nullptr; - }; - - struct UniformPropBlock { - uint2 depthDim; - uint32_t numObjects; - uint32_t maxMipLevel; - }; - // light pass struct UniformLightPerFrameSet { float gamma; diff --git a/HPL2/include/graphics/RendererForwardPlus.h b/HPL2/include/graphics/RendererForwardPlus.h deleted file mode 100644 index d4b1dbffc..000000000 --- a/HPL2/include/graphics/RendererForwardPlus.h +++ /dev/null @@ -1,202 +0,0 @@ - -#pragma once - -#include "engine/RTTI.h" - -#include "graphics/ForwardResources.h" -#include "graphics/GraphicsTypes.h" -#include "graphics/IndexPool.h" -#include "graphics/TextureDescriptorPool.h" -#include "graphics/offsetAllocator.h" -#include "scene/Viewport.h" -#include "scene/World.h" -#include "windowing/NativeWindow.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace hpl { - class RendererForwardPlus : public iRenderer { - HPL_RTTI_IMPL_CLASS(iRenderer, cRendererDeferred, "{A3E5E5A1-1F9C-4F5C-9B9B-5B9B9B5B9B9B}") - public: - static constexpr TinyImageFormat DepthBufferFormat = TinyImageFormat_D32_SFLOAT_S8_UINT; - static constexpr TinyImageFormat NormalBufferFormat = TinyImageFormat_R16G16B16A16_SFLOAT; - static constexpr TinyImageFormat PositionBufferFormat = TinyImageFormat_R32G32B32A32_SFLOAT; - static constexpr TinyImageFormat SpecularBufferFormat = TinyImageFormat_R8G8_UNORM; - static constexpr TinyImageFormat ColorBufferFormat = TinyImageFormat_R8G8B8A8_UNORM; - static constexpr TinyImageFormat ShadowDepthBufferFormat = TinyImageFormat_D32_SFLOAT; - - static constexpr uint32_t MaxMaterialSamplers = static_cast(eTextureWrap_LastEnum) * static_cast(eTextureFilter_LastEnum) * static_cast(cMaterial::TextureAntistropy::Antistropy_Count); - - static constexpr uint32_t MaxIndirectDrawArgs = 1024; - static constexpr uint32_t MaxViewportFrameDescriptors = 256; - static constexpr uint32_t MaxObjectUniforms = 4096; - - static constexpr uint32_t LightClusterWidth = 8; - static constexpr uint32_t LightClusterHeight = 8; - static constexpr uint32_t LightClusterLightCount = 128; - - static constexpr uint32_t PointLightCount = 1024; - static constexpr uint32_t MaxTextureCount = 4096; - static constexpr uint32_t MaxOpaqueCount = 512; - - struct ViewportData { - public: - ViewportData() = default; - ViewportData(const ViewportData&) = delete; - ViewportData(ViewportData&& buffer) - : m_size(buffer.m_size) - , m_outputBuffer(std::move(buffer.m_outputBuffer)) - , m_depthBuffer(std::move(buffer.m_depthBuffer)) - , m_testBuffer(std::move(buffer.m_testBuffer)) { - } - - ViewportData& operator=(const ViewportData&) = delete; - void operator=(ViewportData&& buffer) { - m_size = buffer.m_size; - m_outputBuffer = std::move(buffer.m_outputBuffer); - m_depthBuffer = std::move(buffer.m_depthBuffer); - m_testBuffer = std::move(buffer.m_testBuffer); - } - - uint2 m_size = uint2(0, 0); - std::array m_outputBuffer; - std::array m_testBuffer; - std::array m_depthBuffer; - }; - - struct PointLightData { - mat4 m_mvp; - float3 m_lightPos; - uint m_config; - float4 m_lightColor; - float m_radius; - }; - - struct UniformPerFrameData { - mat4 m_invViewRotation; - mat4 m_viewMatrix; - mat4 m_invViewMatrix; - mat4 m_projectionMatrix; - mat4 m_viewProjectionMatrix; - - float worldFogStart; - float worldFogLength; - float oneMinusFogAlpha; - float fogFalloffExp; - float4 fogColor; - - float2 viewTexel; - float2 viewportSize; - float afT; - }; - - struct UniformObject { - float m_dissolveAmount; - uint m_materialIndex; - float m_lightLevel; - float m_illuminationAmount; - mat4 m_modelMat; - mat4 m_invModelMat; - mat4 m_uvMat; - }; - - enum LightType { - PointLight, - BoxLight, - }; - - struct PerFrameOption { - float2 m_size; - Matrix4 m_viewMat; - Matrix4 m_projectionMat; - }; - - RendererForwardPlus(cGraphics* apGraphics, cResources* apResources, std::shared_ptr debug); - - virtual ~RendererForwardPlus(); - virtual SharedRenderTarget GetOutputImage(uint32_t frameIndex, cViewport& viewport) override; - virtual void Draw( - Cmd* cmd, - const ForgeRenderer::Frame& context, - cViewport& viewport, - float afFrameTime, - cFrustum* apFrustum, - cWorld* apWorld, - cRenderSettings* apSettings, - bool abSendFrameBufferToPostEffects) override; - - uint32_t resolveObjectId( - const ForgeRenderer::Frame& frame, cMaterial* apMaterial, iRenderable* apObject, std::optional modelMatrix); - - private: - uint32_t updateFrameDescriptor(const ForgeRenderer::Frame& frame, Cmd* cmd, cWorld* apWorld, const PerFrameOption& options); - uint32_t resolveMaterialID(const ForgeRenderer::Frame& frame,cMaterial* material); - - - std::array m_perFrameBuffer; - std::array m_objectUniformBuffer; - std::array m_indirectDrawArgsBuffer; - SharedBuffer m_opaqueMaterialBuffer; - - // light clusters - SharedRootSignature m_lightClusterRootSignature; - SharedPipeline m_PointLightClusterPipeline; - SharedPipeline m_clearClusterPipeline; - std::array m_perFrameLightCluster; - std::array m_lightClustersBuffer; - std::array m_lightClusterCountBuffer; - std::array m_pointLightBuffer; - std::array, ForgeRenderer::SwapChainLength> m_pointLightAttenutation; - - folly::F14ValueMap m_objectDescriptorLookup; - - UniqueViewportData m_boundViewportData; - cRenderList m_rendererList; - - uint32_t m_objectIndex = 0; - uint32_t m_activeFrame = 0; - uint32_t m_frameIndex = 0; - - SharedRootSignature m_diffuseRootSignature; - SharedPipeline m_diffusePipeline; - CommandSignature* m_cmdSignatureVBPass = NULL; - std::array m_opaqueFrameSet; - std::array m_opaqueConstSet; - SharedDescriptorSet m_opaqueBatchSet; - - struct SceneMaterial { - public: - void* m_material = nullptr; - uint32_t m_version = 0; - IndexPoolHandle m_slot; - resource::MaterialTypes m_resource = std::monostate{}; - }; - - std::array m_batchSampler; - std::array m_sceneMaterial; - IndexPool m_opaqueMaterialPool; - TextureDescriptorPool m_sceneDescriptorPool; - - SharedTexture m_emptyTexture; - SharedShader m_diffuseShader; - SharedShader m_pointlightClusterShader; - SharedShader m_clearClusterShader; - SharedTexture m_falloff; - - SharedSampler m_nearestClampSampler; - - }; -} // namespace hpl diff --git a/HPL2/include/graphics/RendererWireFrame.h b/HPL2/include/graphics/RendererWireFrame.h index 5b76c0266..b75d1300c 100644 --- a/HPL2/include/graphics/RendererWireFrame.h +++ b/HPL2/include/graphics/RendererWireFrame.h @@ -86,13 +86,12 @@ namespace hpl { virtual void Draw( Cmd* cmd, - const ForgeRenderer::Frame& context, + ForgeRenderer::Frame& context, cViewport& viewport, float afFrameTime, cFrustum* apFrustum, cWorld* apWorld, - cRenderSettings* apSettings, - bool abSendFrameBufferToPostEffects) override; + cRenderSettings* apSettings) override; std::array m_frameBufferUniform; uint32_t m_perFrameIndex = 0; diff --git a/HPL2/include/gui/Gui.h b/HPL2/include/gui/Gui.h index 833b02a06..3b01e33b1 100644 --- a/HPL2/include/gui/Gui.h +++ b/HPL2/include/gui/Gui.h @@ -27,6 +27,7 @@ #include "gui/GuiTypes.h" #include "math/MathTypes.h" +#include "scene/Viewport.h" #include "system/SystemTypes.h" #include @@ -117,6 +118,11 @@ namespace hpl { const cColor& aColor=cColor(1,1),bool abAddToList=true, const cVector2f& avStartUV=0, const cVector2f& avEndUV=1, bool flipUVY = false); + cGuiGfxElement* CreateGfxTexture( cViewport* apTexture, bool abAutoDestroyTexture, + eGuiMaterial aMaterial, + const cColor& aColor=cColor(1,1),bool abAddToList=true, + const cVector2f& avStartUV=0, const cVector2f& avEndUV=1, bool flipUVY = false); + /** * Loads several images asFile+00, etc. Used for animations.Must have extension! diff --git a/HPL2/include/gui/GuiGfxElement.h b/HPL2/include/gui/GuiGfxElement.h index aeb5cd646..132b85b5d 100644 --- a/HPL2/include/gui/GuiGfxElement.h +++ b/HPL2/include/gui/GuiGfxElement.h @@ -19,6 +19,7 @@ #pragma once #include "gui/GuiTypes.h" +#include "scene/Viewport.h" #include namespace hpl { @@ -68,13 +69,14 @@ namespace hpl { friend class cGuiRenderObjectCompare; public: - cGuiGfxElement(cGui* apGui); + cGuiGfxElement(cGui* apGui); ~cGuiGfxElement(); void Update(float afTimeStep); void AddImage(cFrameSubImage* apImage); void AddTexture(Image* apTexture, const cVector2f& avStartUV=0, const cVector2f& avEndUV=1); + void BindViewport(cViewport* viewport, const cVector2f& avStartUV=0, const cVector2f& avEndUV=1); void AddImageToBuffer(cFrameSubImage* apImage); @@ -107,6 +109,7 @@ namespace hpl { void SetFlipUvYAxis(bool abX); bool GetFlipUvYAxis() { return mbFlipUvYAxis;} + cVector2f GetImageSize(); void Flush(); @@ -123,6 +126,7 @@ namespace hpl { eGuiMaterial m_materialType = eGuiMaterial::eGuiMaterial_LastEnum; Image* mvTextures[kMaxGuiTextures]; cFrameSubImage* mvImages[kMaxGuiTextures]; + cViewport::ViewportBeforeDraw::Handler m_viewportHandler; bool mbDestroyTexture; diff --git a/HPL2/include/gui/GuiSet.h b/HPL2/include/gui/GuiSet.h index 4b6c112d6..899ed7159 100644 --- a/HPL2/include/gui/GuiSet.h +++ b/HPL2/include/gui/GuiSet.h @@ -27,12 +27,8 @@ namespace hpl { namespace gui { - static constexpr size_t GUI_STREAM_BUFFER_VB_SIZE = 32768; - static constexpr size_t GUI_STREAM_BUFFER_IB_SIZE = 32768; - static constexpr size_t GUI_MAX_BATCHES = 1024; static constexpr uint32_t MAX_GUI_DRAW_CALLS = 1024; - - + void InitializeGui(ForgeRenderer& pipeline); void exitGui(); } diff --git a/HPL2/include/impl/LegacyVertexBuffer.h b/HPL2/include/impl/LegacyVertexBuffer.h index ae6e160a7..08c617343 100644 --- a/HPL2/include/impl/LegacyVertexBuffer.h +++ b/HPL2/include/impl/LegacyVertexBuffer.h @@ -111,7 +111,7 @@ namespace hpl { folly::small_vector m_vertexElement; // elements are in the order they are requested VertexIndexEntry m_indexBuffer; }; - DrawPacket resolveGeometryBinding(uint32_t currentFrame, std::span elements); + DrawPacket resolveGeometryBinding(uint32_t currentFrame); virtual void UnBind() override; diff --git a/HPL2/include/math/Math.h b/HPL2/include/math/Math.h index c8ce4b0bc..350f7f017 100644 --- a/HPL2/include/math/Math.h +++ b/HPL2/include/math/Math.h @@ -31,6 +31,10 @@ #include namespace hpl { + namespace Math { + static constexpr size_t BYTE_MB = 1000000; + } + //--------------------------------------------- class cFrustum; @@ -59,6 +63,10 @@ namespace hpl { return Vector3(vec.x, vec.y, vec.z); } + static Point3 ToForgePoint3(const cVector3f& vec) { + return Point3 (vec.x, vec.y, vec.z); + } + static Vector2 ToForgeVec2(const cVector2f& vec) { return Vector2(vec.x, vec.y); } diff --git a/HPL2/include/scene/Beam.h b/HPL2/include/scene/Beam.h index 62f1d64fc..75cbdedfa 100644 --- a/HPL2/include/scene/Beam.h +++ b/HPL2/include/scene/Beam.h @@ -16,9 +16,7 @@ * You should have received a copy of the GNU General Public License * along with Amnesia: The Dark Descent. If not, see . */ - -#ifndef HPL_BEAM_H -#define HPL_BEAM_H +#pragma once #include "math/MathTypes.h" #include "graphics/GraphicsTypes.h" @@ -28,131 +26,158 @@ namespace hpl { - class cMaterialManager; - class cResources; - class cGraphics; - class cFileSearcher; - class iLowLevelGraphics; - class cMaterial; - class iVertexBuffer; - - - class cBeam; - class cBeamEnd : public iEntity3D - { - friend class cBeam; - friend class cBeamEnd_UpdateCallback; - public: - cBeamEnd(const tString asName, cBeam *apBeam) : iEntity3D(asName), - mColor(1,1),mpBeam(apBeam) {} - - void SetColor(const cColor &aColor); - const cColor& GetColor(){ return mColor;} - - ///////////////////////////////// - //Entity implementation - tString GetEntityType(){ return "BeamEnd";} - private: - cColor mColor; - cBeam *mpBeam; - }; - - //------------------------------------------ - - class cBeamEnd_UpdateCallback : public iEntityCallback - { - public: - void OnTransformUpdate(iEntity3D * apEntity); - }; + class cMaterialManager; + class cResources; + class cGraphics; + class cFileSearcher; + class iLowLevelGraphics; + class cMaterial; + class iVertexBuffer; + + class cBeam; + class cBeamEnd : public iEntity3D { + friend class cBeam; + friend class cBeamEnd_UpdateCallback; + + public: + cBeamEnd(const tString asName, cBeam* apBeam) + : iEntity3D(asName) + , mColor(1, 1) + , mpBeam(apBeam) { + } + + void SetColor(const cColor& aColor); + const cColor& GetColor() { + return mColor; + } + + ///////////////////////////////// + // Entity implementation + tString GetEntityType() { + return "BeamEnd"; + } + + private: + cColor mColor; + cBeam* mpBeam; + }; + + + class cBeamEnd_UpdateCallback : public iEntityCallback { + public: + void OnTransformUpdate(iEntity3D* apEntity); + }; - //------------------------------------------ + + class cBeam : public iRenderable { + friend class cBeamEnd; - class cBeam : public iRenderable - { - friend class cBeamEnd; - public: - cBeam(const tString asName, cResources *apResources,cGraphics *apGraphics); - ~cBeam(); + public: + cBeam(const tString asName, cResources* apResources, cGraphics* apGraphics); + ~cBeam(); - void SetMaterial(cMaterial * apMaterial); + void SetMaterial(cMaterial* apMaterial); - const tString& GetFileName(){return msFileName;} + const tString& GetFileName() { + return msFileName; + } - /** - * Set the size. X= the thickness of the line, width of texture used. Y = the length that one texture height takes. - * \param avSize - */ - void SetSize(const cVector2f& avSize); - cVector2f GetSize(){ return mvSize;} + /** + * Set the size. X= the thickness of the line, width of texture used. Y = the length that one texture height takes. + * \param avSize + */ + void SetSize(const cVector2f& avSize); + cVector2f GetSize() { + return mvSize; + } - void SetColor(const cColor &aColor); - const cColor& GetColor(){ return mColor;} + void SetColor(const cColor& aColor); + const cColor& GetColor() { + return mColor; + } - void SetTileHeight(bool abX); - bool GetTileHeight(){ return mbTileHeight;} + void SetTileHeight(bool abX); + bool GetTileHeight() { + return mbTileHeight; + } - void SetMultiplyAlphaWithColor(bool abX); - bool GetMultiplyAlphaWithColor(){ return mbMultiplyAlphaWithColor;} + void SetMultiplyAlphaWithColor(bool abX); + bool GetMultiplyAlphaWithColor() { + return mbMultiplyAlphaWithColor; + } - cBeamEnd* GetEnd(){ return mpEnd;} + cBeamEnd* GetEnd() { + return mpEnd; + } - bool LoadXMLProperties(const tString asFile); + bool LoadXMLProperties(const tString asFile); - cVector3f GetAxis(){ return mvAxis;} - cVector3f GetMidPosition(){ return mvMidPosition;} + cVector3f GetAxis() { + return mvAxis; + } + cVector3f GetMidPosition() { + return mvMidPosition; + } - ///////////////////////////////// - //Entity implementation - tString GetEntityType(){ return "Beam";} + // Entity implementation + tString GetEntityType() { + return "Beam"; + } - bool IsVisible(); + bool IsVisible(); - //Renderable implementations - virtual cMaterial *GetMaterial() override{ return mpMaterial;} - virtual iVertexBuffer* GetVertexBuffer() override{return mpVtxBuffer;} - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) override; + // Renderable implementations + virtual cMaterial* GetMaterial() override { + return mpMaterial; + } + virtual iVertexBuffer* GetVertexBuffer() override { + return nullptr; + } + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override; - void UpdateGraphicsForFrame(float afFrameTime); + void UpdateGraphicsForFrame(float afFrameTime); - cBoundingVolume* GetBoundingVolume(); + cBoundingVolume* GetBoundingVolume(); - cMatrixf* GetModelMatrix(cFrustum *apFrustum); + cMatrixf* GetModelMatrix(cFrustum* apFrustum); - int GetMatrixUpdateCount(); + int GetMatrixUpdateCount(); + eRenderableType GetRenderType() { + return eRenderableType_Beam; + } - eRenderableType GetRenderType(){ return eRenderableType_Beam;} - private: - cMaterialManager* mpMaterialManager; - cFileSearcher *mpFileSearcher; - iLowLevelGraphics* mpLowLevelGraphics; + private: + std::shared_ptr m_geometry; - cMaterial *mpMaterial; - iVertexBuffer* mpVtxBuffer; + cMaterialManager* mpMaterialManager; + cFileSearcher* mpFileSearcher; + iLowLevelGraphics* mpLowLevelGraphics; - cBeamEnd *mpEnd; + cMaterial* mpMaterial; + cBeamEnd* mpEnd; - tString msFileName; + tString msFileName; - int mlStartTransformCount; - int mlEndTransformCount; + int mlStartTransformCount; + int mlEndTransformCount; - cMatrixf m_mtxTempTransform; + cMatrixf m_mtxTempTransform; - int mlLastRenderCount; + int mlLastRenderCount; - cBeamEnd_UpdateCallback mEndCallback; + cBeamEnd_UpdateCallback mEndCallback; - cVector2f mvSize; + cVector2f mvSize; - cVector3f mvAxis; - cVector3f mvMidPosition; + cVector3f mvAxis; + cVector3f mvMidPosition; - bool mbTileHeight; - bool mbMultiplyAlphaWithColor; + bool mbTileHeight; + bool mbMultiplyAlphaWithColor; - cColor mColor; - }; + cColor mColor = cColor(1,1,1,1); + uint8_t m_activeCopy = 0; + }; -}; -#endif // HPL_BEAM_H +}; // namespace hpl diff --git a/HPL2/include/scene/BillBoard.h b/HPL2/include/scene/BillBoard.h index 9172e632c..350a6d045 100644 --- a/HPL2/include/scene/BillBoard.h +++ b/HPL2/include/scene/BillBoard.h @@ -35,12 +35,13 @@ namespace hpl { class cMaterial; class iVertexBuffer; - //------------------------------------------ - class cBillboard : public iRenderable { HPL_RTTI_IMPL_CLASS(iRenderable, cBillboard, "{e64fb526-0674-4970-b408-a68a7c2cf584}") public: + + static constexpr uint32_t NumberVerts = 4; + cBillboard(const tString asName,const cVector2f& avSize,eBillboardType aType, cResources *apResources,cGraphics *apGraphics); ~cBillboard(); @@ -63,7 +64,6 @@ namespace hpl { void SetHaloAlpha(float afX); float GetHaloAlpha(){ return mfHaloAlpha;} - ///////////////////////////////// //Halo stuff void SetIsHalo(bool abX); bool IsHalo(){ return mbIsHalo;} @@ -73,7 +73,6 @@ namespace hpl { bool UsesOcclusionQuery() override; - ///////////////////////////////// //Entity implementation tString GetEntityType() override{ return "Billboard";} @@ -81,8 +80,8 @@ namespace hpl { //Renderable implementations cMaterial *GetMaterial() override{ return mpMaterial;} - iVertexBuffer* GetVertexBuffer()override{return mpVtxBuffer;} - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) override; + iVertexBuffer* GetVertexBuffer()override{return nullptr;} + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override; cMatrixf* GetModelMatrix(cFrustum *apFrustum)override; @@ -90,14 +89,13 @@ namespace hpl { eRenderableType GetRenderType()override{ return eRenderableType_Billboard;} - float getAreaOfScreenSpace(cFrustum* frustum ); private: + std::shared_ptr m_geometry; cMaterialManager* mpMaterialManager; iLowLevelGraphics* mpLowLevelGraphics; cMaterial *mpMaterial; - iVertexBuffer* mpVtxBuffer; cMatrixf m_mtxHaloOcclusionMatrix; cMatrixf m_mtxTempTransform; @@ -117,6 +115,9 @@ namespace hpl { float mfForwardOffset; cColor mColor; float mfHaloAlpha; - }; + uint32_t m_frameIndex = 0; + bool m_dirtyBuffer = true; + uint8_t m_activeCopy = false; + }; }; diff --git a/HPL2/include/scene/DummyRenderable.h b/HPL2/include/scene/DummyRenderable.h index 943192fcb..9a24f64c6 100644 --- a/HPL2/include/scene/DummyRenderable.h +++ b/HPL2/include/scene/DummyRenderable.h @@ -53,7 +53,7 @@ namespace hpl { virtual cMaterial *GetMaterial() override { return NULL;} virtual iVertexBuffer* GetVertexBuffer() override{ return NULL;} - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) override { + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override { DrawPacket packet; packet.m_type = DrawPacket::Unknown; return packet; diff --git a/HPL2/include/scene/Entity3D.h b/HPL2/include/scene/Entity3D.h index 42a38ce2c..1863caa7a 100644 --- a/HPL2/include/scene/Entity3D.h +++ b/HPL2/include/scene/Entity3D.h @@ -76,6 +76,7 @@ namespace hpl { cMatrixf& GetLocalMatrix(); Matrix4 GetLocalMat(); + Point3 GetWorldPositionP3(); cVector3f GetWorldPosition(); cMatrixf& GetWorldMatrix(); Matrix4 GetWorldMat(); diff --git a/HPL2/include/scene/FogArea.h b/HPL2/include/scene/FogArea.h index b78ed38c7..8360ce9b4 100644 --- a/HPL2/include/scene/FogArea.h +++ b/HPL2/include/scene/FogArea.h @@ -58,19 +58,17 @@ namespace hpl { bool GetShowBacksideWhenOutside(){ return mbShowBacksideWhenOutside; } bool GetShowBacksideWhenInside(){ return mbShowBacksideWhenInside; } - ////////////////////////////// //iEntity implementation tString GetEntityType(){ return "cFogArea";} - /////////////////////////////// //Renderable implementation: - cMaterial *GetMaterial(){ return NULL;} - iVertexBuffer* GetVertexBuffer(){ return NULL;} - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) override; - eRenderableType GetRenderType(){ return eRenderableType_FogArea;} + virtual cMaterial *GetMaterial() override{ return NULL;} + virtual iVertexBuffer* GetVertexBuffer() override{ return NULL;} + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override; + virtual eRenderableType GetRenderType() override { return eRenderableType_FogArea;} - int GetMatrixUpdateCount(){ return GetTransformUpdateCount();} - cMatrixf* GetModelMatrix(cFrustum* apFrustum); + virtual int GetMatrixUpdateCount() override{ return GetTransformUpdateCount();} + virtual cMatrixf* GetModelMatrix(cFrustum* apFrustum) override; private: cColor mColor; diff --git a/HPL2/include/scene/GuiSetEntity.h b/HPL2/include/scene/GuiSetEntity.h index df43b143b..b28a399b0 100644 --- a/HPL2/include/scene/GuiSetEntity.h +++ b/HPL2/include/scene/GuiSetEntity.h @@ -46,17 +46,17 @@ namespace hpl { ///////////////////////////////// //Entity implementation - tString GetEntityType(){ return "GuiSetEntity";} + virtual tString GetEntityType() override{ return "GuiSetEntity";} ///////////////////////////////// //Renderable implementations - cMaterial *GetMaterial(){ return NULL;} - iVertexBuffer* GetVertexBuffer(){return NULL;} - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) { return DrawPacket();} + virtual cMaterial *GetMaterial() override{ return NULL;} + virtual iVertexBuffer* GetVertexBuffer() override{return NULL;} + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override { return DrawPacket();} - eRenderableType GetRenderType(){ return eRenderableType_GuiSet;} - cMatrixf* GetModelMatrix(cFrustum *apFrustum); - int GetMatrixUpdateCount(); + virtual eRenderableType GetRenderType() override { return eRenderableType_GuiSet;} + virtual cMatrixf* GetModelMatrix(cFrustum *apFrustum)override; + virtual int GetMatrixUpdateCount()override; private: cGuiSet *mpGuiSet; diff --git a/HPL2/include/scene/Light.h b/HPL2/include/scene/Light.h index 7f468d308..c9615fe58 100644 --- a/HPL2/include/scene/Light.h +++ b/HPL2/include/scene/Light.h @@ -79,9 +79,6 @@ namespace hpl { class iLight : public iRenderable { - #ifdef __GNUC__ - typedef iRenderable __super; - #endif public: iLight(tString asName, cResources *apResources); virtual ~iLight(); @@ -103,7 +100,7 @@ namespace hpl { //iEntity implementation tString GetEntityType(){ return "iLight";} - virtual bool IsVisible(); + virtual bool IsVisible() override; void OnChangeVisible(); /////////////////////////////// @@ -111,7 +108,7 @@ namespace hpl { virtual cMaterial *GetMaterial() override{ return NULL;} virtual iVertexBuffer* GetVertexBuffer() override{ return NULL;} - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) override { + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override { return DrawPacket(); } diff --git a/HPL2/include/scene/LightPoint.h b/HPL2/include/scene/LightPoint.h index 5dcdce9b9..ef1386dbe 100644 --- a/HPL2/include/scene/LightPoint.h +++ b/HPL2/include/scene/LightPoint.h @@ -17,20 +17,14 @@ * along with Amnesia: The Dark Descent. If not, see . */ -#ifndef HPL_LIGHT_POINT_H -#define HPL_LIGHT_POINT_H +#pragma once #include "scene/Light.h" namespace hpl { - //------------------------------------------ - class cLightPoint : public iLight { - #ifdef __GNUC__ - typedef iLight __super; - #endif public: cLightPoint(tString asName, cResources *apResources); @@ -39,4 +33,3 @@ namespace hpl { }; }; -#endif // HPL_LIGHT_POINT_H diff --git a/HPL2/include/scene/LightSpot.h b/HPL2/include/scene/LightSpot.h index 2b1fa9dbe..1740c5b1d 100644 --- a/HPL2/include/scene/LightSpot.h +++ b/HPL2/include/scene/LightSpot.h @@ -33,9 +33,6 @@ namespace hpl { class cLightSpot : public iLight { - #ifdef __GNUC__ - typedef iLight __super; - #endif public: cLightSpot(tString asName, cResources *apResources); ~cLightSpot(); @@ -87,7 +84,6 @@ namespace hpl { float mfTanHalfFOV; float mfCosHalfFOV; - bool mbProjectionUpdated; bool mbViewProjUpdated; bool mbFrustumUpdated; diff --git a/HPL2/include/scene/ParticleEmitter.h b/HPL2/include/scene/ParticleEmitter.h index b7a1ce1e0..10d531215 100644 --- a/HPL2/include/scene/ParticleEmitter.h +++ b/HPL2/include/scene/ParticleEmitter.h @@ -32,7 +32,6 @@ namespace hpl { class cWorld; class cParticleSystem; - //------------------------------------------------------------------- enum ePEType { @@ -42,8 +41,6 @@ namespace hpl { }; - //------------------------------------------------------------------- - enum eParticleEmitterType { eParticleEmitterType_FixedPoint, @@ -60,7 +57,6 @@ namespace hpl { eParticleEmitterCoordSystem_LastEnum, }; - //------------------------------------------ class cPESubDivision { @@ -68,7 +64,6 @@ namespace hpl { cVector3f mvUV[4]; }; - //------------------------------------------------------------------- enum ePENoiseType { @@ -89,16 +84,6 @@ namespace hpl { ePENoiseType noiseType; } tBeamNoisePoint; - - //------------------------------------------------------------------- - - - ////////////////////////////////////////////////////// - /////////////// PARTICLE ///////////////////////////// - ////////////////////////////////////////////////////// - - //------------------------------------------------------------------- - class cParticle { public: @@ -149,20 +134,11 @@ namespace hpl { int mlHighFreqPoints; std::vector mvBeamPoints; - // --- - }; - //------------------------------------------------------------------- - typedef std::vector tParticleVec; typedef tParticleVec::iterator tParticleVecIt; - //------------------------------------------------------------------- - - ////////////////////////////////////////////////////// - /////////////// PARTICLE SYSTEM ////////////////////// - ////////////////////////////////////////////////////// class iParticleEmitter :public iRenderable { @@ -201,7 +177,7 @@ namespace hpl { virtual cMaterial *GetMaterial() override; virtual iVertexBuffer* GetVertexBuffer() override; - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) override; + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override; virtual cBoundingVolume* GetBoundingVolume() override; @@ -213,6 +189,7 @@ namespace hpl { protected: void SwapRemove(unsigned int alIndex); cParticle* CreateParticle(); + static constexpr uint32_t NumberActiveCopies = 2; virtual void UpdateMotion(float afTimeStep)=0; virtual void SetParticleDefaults(cParticle *apParticle)=0; @@ -240,8 +217,6 @@ namespace hpl { bool mbUpdateGfx; bool mbUpdateBV; - iVertexBuffer *mpVtxBuffer; - std::vector mvSubDivUV; cVector3f mvDirection; @@ -271,21 +246,15 @@ namespace hpl { bool mbUseRevolution; ePEType mPEType; - }; - //----------------------------------------------------------------- + std::shared_ptr m_geometry; + uint32_t m_numberParticlesRender = 0; + uint8_t m_activeCopy = 0; + }; typedef std::list tParticleEmitterList; typedef tParticleEmitterList::iterator tParticleEmitterListIt; - //----------------------------------------------------------------- - - ////////////////////////////////////////////////////// - /////////////// PARTICLE EMITTER DATA //////////////// - ////////////////////////////////////////////////////// - - //----------------------------------------------------------------- - class cResources; class iParticleEmitterData @@ -321,8 +290,6 @@ namespace hpl { float mfWarmUpStepsPerSec; }; - typedef std::map tParticleEmitterDataMap; - typedef tParticleEmitterDataMap::iterator tParticleEmitterDataMapIt; }; diff --git a/HPL2/include/scene/RenderableContainer.h b/HPL2/include/scene/RenderableContainer.h index 3df6c3f2c..e188dedf6 100644 --- a/HPL2/include/scene/RenderableContainer.h +++ b/HPL2/include/scene/RenderableContainer.h @@ -24,6 +24,7 @@ #include "graphics/GraphicsTypes.h" #include "system/SystemTypes.h" #include "scene/SceneTypes.h" +#include #include namespace hpl { @@ -130,6 +131,10 @@ namespace hpl { public: virtual ~iRenderableContainer(){} + static void WalkRenderableContainer( + iRenderableContainer& container, cFrustum* frustum, std::function handler, tRenderableFlag renderableFlag); + static bool IsRenderableNodeIsVisible(iRenderableContainerNode& apNode, std::span clipPlanes); + void UpdateBeforeRendering(); virtual void Add(iRenderable *apRenderable)=0; diff --git a/HPL2/include/scene/RopeEntity.h b/HPL2/include/scene/RopeEntity.h index 1e943bb2c..a786f232b 100644 --- a/HPL2/include/scene/RopeEntity.h +++ b/HPL2/include/scene/RopeEntity.h @@ -34,14 +34,14 @@ namespace hpl { class iVertexBuffer; class iPhysicsRope; - //------------------------------------------ - class cRopeEntity : public iRenderable { public: cRopeEntity(const tString& asName, cResources *apResources,cGraphics *apGraphics, iPhysicsRope *apRope, int alMaxSegments); ~cRopeEntity(); + static constexpr uint32_t NumberOfCopies = 2; + const tString& GetName(){return msName;} iPhysicsRope *GetPhysicsRope(){ return mpRope;} @@ -71,18 +71,15 @@ namespace hpl { void SetLengthTileSize(float afX){ mfLengthTileSize = afX;} float GetLengthTileSize(){ return mfLengthTileSize;} - - ///////////////////////////////// //Entity implementation tString GetEntityType(){ return "RopeEntity";} bool IsVisible(); - ///////////////////////////////// //Renderable implementations virtual cMaterial *GetMaterial() override{ return mpMaterial;} - virtual iVertexBuffer* GetVertexBuffer() override{return mpVtxBuffer;} - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) override; + virtual iVertexBuffer* GetVertexBuffer() override{return nullptr;} + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override; virtual void UpdateGraphicsForFrame(float afFrameTime) override; virtual bool UpdateGraphicsForViewport(cFrustum *apFrustum,float afFrameTime) override; @@ -101,7 +98,7 @@ namespace hpl { iPhysicsRope *mpRope; cMaterial *mpMaterial; - iVertexBuffer* mpVtxBuffer; + std::shared_ptr m_geometry; int mlMaxSegments; @@ -113,6 +110,8 @@ namespace hpl { bool mbMultiplyAlphaWithColor; int mlLastUpdateCount; - }; + uint8_t m_activeCopy = 0; + int m_numberSegments = 0; + }; }; diff --git a/HPL2/include/scene/Scene.h b/HPL2/include/scene/Scene.h index 145e1f270..bc3304ff5 100644 --- a/HPL2/include/scene/Scene.h +++ b/HPL2/include/scene/Scene.h @@ -66,7 +66,7 @@ namespace hpl { * Called by cEngine */ void Render(float afFrameTime, tFlag alFlags) {} //TODO MP: this needs to be replaced - void Render(const ForgeRenderer::Frame&, float afFrameTime, tFlag alFlags); + void Render(ForgeRenderer::Frame&, float afFrameTime, tFlag alFlags); void Update(float timeStep); diff --git a/HPL2/include/scene/SubMeshEntity.h b/HPL2/include/scene/SubMeshEntity.h index 08ccb5fe3..dcdc446b9 100644 --- a/HPL2/include/scene/SubMeshEntity.h +++ b/HPL2/include/scene/SubMeshEntity.h @@ -62,7 +62,7 @@ namespace hpl { virtual void UpdateGraphicsForFrame(float afFrameTime) override; virtual iVertexBuffer* GetVertexBuffer() override; - virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) override; + virtual DrawPacket ResolveDrawPacket(const ForgeRenderer::Frame& frame) override; virtual cBoundingVolume* GetBoundingVolume() override; diff --git a/HPL2/include/scene/Viewport.h b/HPL2/include/scene/Viewport.h index 11ad5d44d..47520671b 100644 --- a/HPL2/include/scene/Viewport.h +++ b/HPL2/include/scene/Viewport.h @@ -60,11 +60,12 @@ namespace hpl { HPL_RTTI_CLASS(cViewport, "{f5d42b52-6e84-4486-afa0-a5888f3513a0}") public: static constexpr Uuid PrimaryViewportTag = hpl::detail::From("{f5d42b52-6e84-4486-afa0-a5888f3513a0}"); - static constexpr size_t MaxViewportHandles = 9; + static constexpr size_t MaxViewportHandles = 12; using ResizeEvent = hpl::Event; using ViewportDispose = hpl::Event<>; using ViewportChange = hpl::Event<>; + using ViewportBeforeDraw = hpl::Event; struct DrawPayloadCommon { cFrustum* m_frustum; @@ -91,6 +92,7 @@ namespace hpl { ~cViewport(); + inline void SetActive(bool abX) { mbActive = abX;} inline void SetVisible(bool abX) { mbVisible = abX;} @@ -113,13 +115,12 @@ namespace hpl { inline void SetRenderer(iRenderer* apRenderer) { mpRenderer = apRenderer; } inline iRenderer* GetRenderer() { return mpRenderer; } - cRenderSettings* GetRenderSettings() { - return mpRenderSettings.get(); - } + cRenderSettings* GetRenderSettings() { return mpRenderSettings.get(); } inline void SetPostEffectComposite(cPostEffectComposite* apPostEffectComposite) { mpPostEffectComposite = apPostEffectComposite; } + inline cPostEffectComposite* GetPostEffectComposite() { return mpPostEffectComposite; } @@ -135,33 +136,28 @@ namespace hpl { const cVector2l GetSize() { return m_size; } - const uint2 GetSizeU2() { - return uint2(m_size.x, m_size.y); - } + const uint2 GetSizeU2() { return uint2(m_size.x, m_size.y); } + uint2 GetSizeU() const { return uint2(m_size.x, m_size.y); } - uint2 GetSizeU() const { - return uint2(m_size.x, m_size.y); + inline SharedRenderTarget& Target(ForgeRenderer::Frame& frame) { return m_targets[frame.m_frameIndex]; } + void SetTarget(std::array&& target); + inline std::shared_ptr& GetImage(ForgeRenderer::Frame& frame) { + return m_images[frame.m_frameIndex]; } - inline SharedRenderTarget& Target() { return m_target; } - void SetTarget(SharedRenderTarget& target); - void SetTarget(SharedRenderTarget&& target); - inline std::shared_ptr& GetImage() { - return m_image; - } + // if a target is not initialized then its assumed to go to the swapchain + void InitializeTarget(Renderer* renderer, RenderTargetDesc desc); + void InvalidateTarget(); void bindToWindow(window::NativeWindowWrapper& window); - void AddViewportCallback(iViewportCallback* apCallback); - void RemoveViewportCallback(iViewportCallback* apCallback); - void RunViewportCallbackMessage(eViewportMessage aMessage); inline void ConnectViewportChanged(ViewportChange::Handler& handler) { handler.Connect(m_viewportChanged);} - inline void ConnectDraw(PostSolidDraw::Handler& handler) { handler.Connect(m_postSolidDraw); } inline void ConnectDraw(PostTranslucenceDraw::Handler& handler) { handler.Connect(m_postTranslucenceDraw); } - + inline void ConnectBeforeDraw(ViewportBeforeDraw::Handler& handler) { handler.Connect(m_viewportBeforeDraw); } inline void SignalDraw(PostSolidDrawPacket& payload) { m_postSolidDraw.Signal(payload);} inline void SignalDraw(PostTranslucenceDrawPacket& payload) { m_postTranslucenceDraw.Signal(payload);} + inline void SignalBeforeDraw(ForgeRenderer::Frame* frame) { m_viewportBeforeDraw.Signal(frame);} inline void SetTag(const Uuid& tag) { m_tag = tag; } inline Uuid Tag() { return m_tag; } @@ -179,8 +175,8 @@ namespace hpl { iRenderer* mpRenderer = nullptr; cPostEffectComposite* mpPostEffectComposite = nullptr; - SharedRenderTarget m_target; - std::shared_ptr m_image; + std::array m_targets; + std::array, ForgeRenderer::SwapChainLength> m_images; cVector2l m_size = { 0, 0 }; Uuid m_tag; @@ -189,17 +185,15 @@ namespace hpl { ViewportDispose m_disposeEvent; ViewportChange m_viewportChanged; + ViewportBeforeDraw m_viewportBeforeDraw; window::WindowEvent::Handler m_windowEventHandler; PostSolidDraw m_postSolidDraw; PostTranslucenceDraw m_postTranslucenceDraw; - tViewportCallbackList mlstCallbacks; tGuiSetList m_guiSets; std::unique_ptr mpRenderSettings; - - template friend class UniqueViewportData; }; diff --git a/HPL2/resource/ShaderList.fsl b/HPL2/resource/ShaderList.fsl index c7c365a84..1d9840bad 100644 --- a/HPL2/resource/ShaderList.fsl +++ b/HPL2/resource/ShaderList.fsl @@ -40,7 +40,6 @@ #frag solid_diffuse_parallax.frag // toned down the parallax effect a bit - #define PARALLAX_ENABLED 1 #define SEARCH_SAMPLE_COUNT 4 #define ALPHA_REJECT 0.5 @@ -277,15 +276,15 @@ #include "forward_diffuse.vert.fsl" #end -#frag forward_diffuse.frag - #define ALPHA_REJECT 0.5 - #include "forward_diffuse.frag.fsl" -#end - -#comp point_light_clusters.comp - #include "point_light_clusters.comp.fsl" -#end - -#comp light_clusters_clear.comp - #include "light_clusters_clear.comp.fsl" -#end +//#frag forward_diffuse.frag +// #define ALPHA_REJECT 0.5 +// #include "forward_diffuse.frag.fsl" +//#end +// +//#comp point_light_clusters.comp +// #include "point_light_clusters.comp.fsl" +//#end +// +//#comp light_clusters_clear.comp +// #include "light_clusters_clear.comp.fsl" +//#end diff --git a/HPL2/resource/generate_hi_z.comp.fsl b/HPL2/resource/generate_hi_z.comp.fsl index 8578808e3..c33dd0c26 100644 --- a/HPL2/resource/generate_hi_z.comp.fsl +++ b/HPL2/resource/generate_hi_z.comp.fsl @@ -2,7 +2,7 @@ /// Copyright 2023 Michael Pollind /// SPDX-License-Identifier: GPL-3.0 -RES(RWTex2D(float), depthInput[16], UPDATE_FREQ_PER_FRAME, u1, binding = 6); +RES(RWTex2D(float), depthInput[16], UPDATE_FREQ_PER_FRAME, u1, binding = 7); PUSH_CONSTANT(uRootConstants, b0) { diff --git a/HPL2/sources/graphics/DebugDraw.cpp b/HPL2/sources/graphics/DebugDraw.cpp index ae0391080..4aab33d05 100644 --- a/HPL2/sources/graphics/DebugDraw.cpp +++ b/HPL2/sources/graphics/DebugDraw.cpp @@ -2,6 +2,7 @@ #include "Common_3/Graphics/Interfaces/IGraphics.h" #include "Common_3/Utilities/Math/MathTypes.h" #include "Common_3/Resources/ResourceLoader/Interfaces/IResourceLoader.h" +#include "graphics/GraphicsAllocator.h" #include "graphics/VertexBuffer.h" #include "scene/Camera.h" @@ -39,22 +40,6 @@ namespace hpl { } DebugDraw::DebugDraw(ForgeRenderer* renderer) { - { - BufferDesc desc = {}; - desc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER; - desc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mSize = ImmediateVertexBufferSize; - desc.pName = "Immediate Vertex Buffer"; - addGPURingBuffer(renderer->Rend(), &desc, &m_vertexBuffer); - } - { - BufferDesc desc = {}; - desc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER; - desc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mSize = ImmediateIndexBufferSize; - desc.pName = "Immediate Index Buffer"; - addGPURingBuffer(renderer->Rend(), &desc, &m_indexBuffer); - } m_bilinearSampler.Load(renderer->Rend(), [&](Sampler** sampler) { SamplerDesc bilinearClampDesc = { FILTER_NEAREST, FILTER_NEAREST, @@ -89,7 +74,7 @@ namespace hpl { for(auto& buffer: m_viewBufferUniform) { buffer.Load([&](Buffer** buffer) { BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER; + desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER | DESCRIPTOR_TYPE_UNIFORM_BUFFER; desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; desc.mDesc.mFirstElement = 0; @@ -152,10 +137,9 @@ namespace hpl { updateDescriptorSet(renderer->Rend(), i, m_perTextureViewDescriptorSet.m_handle, params.size(), params.data()); } VertexLayout uvVertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY - vertexLayout.mBindingCount = 1; - vertexLayout.mBindings[0].mStride = sizeof(float3); -#endif + uvVertexLayout.mBindingCount = 1; + uvVertexLayout.mBindings[0].mStride = sizeof(float3) + sizeof(float2) + sizeof(float4); + uvVertexLayout.mAttribCount = 3; uvVertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; uvVertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -167,19 +151,17 @@ namespace hpl { uvVertexLayout.mAttribs[1].mFormat = TinyImageFormat_R32G32_SFLOAT; uvVertexLayout.mAttribs[1].mBinding = 0; uvVertexLayout.mAttribs[1].mLocation = 1; - uvVertexLayout.mAttribs[1].mOffset = sizeof(float) * 3; + uvVertexLayout.mAttribs[1].mOffset = sizeof(float3); uvVertexLayout.mAttribs[2].mSemantic = SEMANTIC_COLOR; uvVertexLayout.mAttribs[2].mFormat = TinyImageFormat_R32G32B32A32_SFLOAT; uvVertexLayout.mAttribs[2].mBinding = 0; uvVertexLayout.mAttribs[2].mLocation = 2; - uvVertexLayout.mAttribs[2].mOffset = (sizeof(float) * 3) + (sizeof(float) * 2); + uvVertexLayout.mAttribs[2].mOffset = sizeof(float3) + sizeof(float2); VertexLayout colorVertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY - vertexLayout.mBindingCount = 1; - vertexLayout.mBindings[0].mStride = sizeof(float3); -#endif + colorVertexLayout.mBindingCount = 1; + colorVertexLayout.mBindings[0].mStride = sizeof(float3) + sizeof(float4); colorVertexLayout.mAttribCount = 2; colorVertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; colorVertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -191,7 +173,7 @@ namespace hpl { colorVertexLayout.mAttribs[1].mFormat = TinyImageFormat_R32G32B32A32_SFLOAT; colorVertexLayout.mAttribs[1].mBinding = 0; colorVertexLayout.mAttribs[1].mLocation = 1; - colorVertexLayout.mAttribs[1].mOffset = sizeof(float) * 3; + colorVertexLayout.mAttribs[1].mOffset = sizeof(float3); BlendStateDesc blendStateDesc{}; blendStateDesc.mSrcFactors[0] = BC_ONE; @@ -201,11 +183,7 @@ namespace hpl { blendStateDesc.mSrcAlphaFactors[0] = BC_ONE; blendStateDesc.mDstAlphaFactors[0] = BC_ONE; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; -#else blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; -#endif blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -636,11 +614,17 @@ namespace hpl { } void DebugDraw::flush(const ForgeRenderer::Frame& frame, Cmd* cmd, const cViewport& viewport, const cFrustum& frustum, SharedRenderTarget& targetBuffer, SharedRenderTarget& depthBuffer) { + + auto* graphicsAllocator = Interface::Get(); if (frame.m_currentFrame != m_activeFrame) { m_textureLookup.clear(); m_textureId = 0; m_activeFrame = frame.m_currentFrame; } + + + cmdBeginDebugMarker(cmd, 0, 1, 0, "Debug Flush"); + m_frameIndex = (m_frameIndex + 1) % NumberOfPerFrameUniforms; const Matrix4 matMainFrustumView = cMath::ToForgeMatrix4(frustum.GetViewMatrix()); const Matrix4 matMainFrustumProj = cMath::ToForgeMatrix4(frustum.GetProjectionMatrix()); @@ -661,21 +645,18 @@ namespace hpl { FrameUniformBuffer uniformData; uniformData.m_viewProjMat = ((frustum.GetProjectionType() == eProjectionType_Perspective ? Matrix4::identity() : correctionMatrix) * matMainFrustumProj) * matMainFrustumView ; - uniformData.m_viewProj2DMat = Matrix4::orthographic(0.0f, targetBuffer.m_handle->mWidth, targetBuffer.m_handle->mHeight,0.0f, -1000.0f, 1000.0f); + uniformData.m_viewProj2DMat = Matrix4::orthographicLH(0.0f, targetBuffer.m_handle->mWidth, targetBuffer.m_handle->mHeight,0.0f, -1000.0f, 1000.0f); (*reinterpret_cast(updateDesc.pMappedData)) = uniformData; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); } const bool hasDepthBuffer = depthBuffer.IsValid(); - std::array targets = { - targetBuffer.m_handle, - }; - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - cmdBindRenderTargets( - cmd, targets.size(), targets.data(), depthBuffer.m_handle, &loadActions, nullptr, nullptr, -1, -1); + BindRenderTargetsDesc bindTargetDescs = {0}; + bindTargetDescs.mDepthStencil = { depthBuffer.m_handle, LOAD_ACTION_LOAD }; + bindTargetDescs.mRenderTargets[0] = { targetBuffer.m_handle, LOAD_ACTION_LOAD }; + bindTargetDescs.mRenderTargetCount = 1; + cmdBindRenderTargets(cmd, &bindTargetDescs); cmdSetViewport(cmd, 0.0f, 0.0f, static_cast(targetBuffer.m_handle->mWidth), static_cast(targetBuffer.m_handle->mHeight), 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, static_cast(targetBuffer.m_handle->mWidth), static_cast(targetBuffer.m_handle->mHeight)); @@ -697,8 +678,8 @@ namespace hpl { const size_t indexBufferSize = sizeof(uint16_t) * numIndices; const uint32_t vertexBufferStride = sizeof(PositionColorVertex); - GPURingBufferOffset vb = getGPURingBufferOffset(m_vertexBuffer, vertexBufferSize); - GPURingBufferOffset ib = getGPURingBufferOffset(m_indexBuffer, indexBufferSize); + GPURingBufferOffset vb = graphicsAllocator->allocTransientVertexBuffer(vertexBufferSize); + GPURingBufferOffset ib = graphicsAllocator->allocTransientIndexBuffer(indexBufferSize); auto it = m_colorTriangles.begin(); auto lastIt = m_colorTriangles.begin(); @@ -742,8 +723,8 @@ namespace hpl { indexBufferOffset += indexBufferIndex; vertexBufferOffset += vertexBufferIndex; } - endUpdateResource(&vertexUpdateDesc, nullptr); - endUpdateResource(&indexUpdateDesc, nullptr); + endUpdateResource(&vertexUpdateDesc); + endUpdateResource(&indexUpdateDesc); } @@ -765,8 +746,8 @@ namespace hpl { const size_t indexBufferSize = sizeof(uint32_t) * numIndices; const uint32_t vertexBufferStride = sizeof(PositionColorVertex); - GPURingBufferOffset vb = getGPURingBufferOffset(m_vertexBuffer, vertexBufferSize); - GPURingBufferOffset ib = getGPURingBufferOffset(m_indexBuffer, indexBufferSize); + GPURingBufferOffset vb = graphicsAllocator->allocTransientVertexBuffer(vertexBufferSize); + GPURingBufferOffset ib = graphicsAllocator->allocTransientIndexBuffer(indexBufferSize); auto it = m_colorQuads.begin(); auto lastIt = m_colorQuads.begin(); @@ -823,8 +804,8 @@ namespace hpl { indexBufferOffset += indexBufferIndex; vertexBufferOffset += vertexBufferIndex; } - endUpdateResource(&vertexUpdateDesc, nullptr); - endUpdateResource(&indexUpdateDesc, nullptr); + endUpdateResource(&vertexUpdateDesc); + endUpdateResource(&indexUpdateDesc); } if(!m_line2DSegments.empty()) { @@ -836,8 +817,8 @@ namespace hpl { const size_t vbSize = sizeof(PositionColorVertex) * numVertices; const size_t ibSize = sizeof(uint16_t) * numVertices; const uint32_t stride = sizeof(PositionColorVertex); - GPURingBufferOffset vb = getGPURingBufferOffset(m_vertexBuffer, vbSize); - GPURingBufferOffset ib = getGPURingBufferOffset(m_indexBuffer, ibSize); + GPURingBufferOffset vb = graphicsAllocator->allocTransientVertexBuffer(vbSize); + GPURingBufferOffset ib = graphicsAllocator->allocTransientIndexBuffer(ibSize); uint32_t indexBufferOffset = 0; uint32_t vertexBufferOffset = 0; @@ -858,13 +839,13 @@ namespace hpl { float4(segment.m_color.getX(), segment.m_color.getY(), segment.m_color.getZ(), segment.m_color.getW()) }; } - endUpdateResource(&vertexUpdateDesc, nullptr); - endUpdateResource(&indexUpdateDesc, nullptr); + endUpdateResource(&vertexUpdateDesc); + endUpdateResource(&indexUpdateDesc); cmdBindPipeline(cmd, m_lineSegmentPipeline2D.m_handle); cmdBindDescriptorSet(cmd, m_frameIndex, m_perColorViewDescriptorSet.m_handle); cmdBindVertexBuffer(cmd, 1, &vb.pBuffer, &stride, &vb.mOffset); cmdBindIndexBuffer(cmd, ib.pBuffer, INDEX_TYPE_UINT16, ib.mOffset); - cmdDrawIndexed(cmd, numVertices, 0, 0); + cmdDrawIndexed(cmd, indexBufferOffset, 0, 0); } if(!m_uvQuads.empty()) { @@ -883,8 +864,8 @@ namespace hpl { const size_t vertexBufferSize = sizeof(UVVertex) * (m_uvQuads.size() * 4); const size_t indexBufferSize = sizeof(uint16_t) * (m_uvQuads.size() * 6); const uint32_t vertexBufferStride = sizeof(UVVertex); - GPURingBufferOffset vb = getGPURingBufferOffset(m_vertexBuffer, vertexBufferSize); - GPURingBufferOffset ib = getGPURingBufferOffset(m_indexBuffer, indexBufferSize); + GPURingBufferOffset vb = graphicsAllocator->allocTransientVertexBuffer(vertexBufferSize); + GPURingBufferOffset ib = graphicsAllocator->allocTransientIndexBuffer(indexBufferSize); uint32_t indexBufferOffset = 0; uint32_t vertexBufferOffset = 0; @@ -1000,8 +981,8 @@ namespace hpl { vertexBufferOffset += vertexBufferIndex; m_textureId++; } - endUpdateResource(&vertexUpdateDesc, nullptr); - endUpdateResource(&indexUpdateDesc, nullptr); + endUpdateResource(&vertexUpdateDesc); + endUpdateResource(&indexUpdateDesc); //auto lookup = m_textureLookup.find(apObject); } @@ -1019,8 +1000,9 @@ namespace hpl { const size_t vertexBufferSize = sizeof(PositionColorVertex) * numMaxVertices; const size_t indexBufferSize = sizeof(uint32_t) * numMaxVertices; const uint32_t vertexBufferStride = sizeof(PositionColorVertex); - GPURingBufferOffset vb = getGPURingBufferOffset(m_vertexBuffer, vertexBufferSize); - GPURingBufferOffset ib = getGPURingBufferOffset(m_indexBuffer, indexBufferSize); + + GPURingBufferOffset vb = graphicsAllocator->allocTransientVertexBuffer(vertexBufferSize); + GPURingBufferOffset ib = graphicsAllocator->allocTransientIndexBuffer(indexBufferSize); uint32_t indexBufferOffset = 0; uint32_t vertexBufferOffset = 0; @@ -1061,16 +1043,15 @@ namespace hpl { vertexBufferOffset += vertexBufferIndex; }; - endUpdateResource(&vertexUpdateDesc, nullptr); - endUpdateResource(&indexUpdateDesc, nullptr); + endUpdateResource(&vertexUpdateDesc); + endUpdateResource(&indexUpdateDesc); } - - m_line2DSegments.clear(); m_uvQuads.clear(); m_colorQuads.clear(); m_lineSegments.clear(); m_colorTriangles.clear(); + cmdEndDebugMarker(cmd); } } // namespace hpl diff --git a/HPL2/sources/graphics/DrawPacket.cpp b/HPL2/sources/graphics/DrawPacket.cpp index 1283d71ac..27b95bbf7 100644 --- a/HPL2/sources/graphics/DrawPacket.cpp +++ b/HPL2/sources/graphics/DrawPacket.cpp @@ -6,33 +6,37 @@ namespace hpl { - void DrawPacket::cmdBindBuffers(Cmd* cmd, ForgeRenderer::CommandResourcePool* resourcePool, DrawPacket* packet) { + void DrawPacket::cmdBindBuffers(Cmd* cmd, ForgeRenderer::CommandResourcePool* resourcePool, DrawPacket* packet, std::span elements) { folly::small_vector vbBuffer; folly::small_vector vbOffsets; folly::small_vector vbStride; switch (packet->m_type) { case DrawPacketType::DrawIndvidualBuffers: { - for (size_t i = 0; i < packet->m_indvidual.m_numStreams; i++) { - auto& stream = packet->m_indvidual.m_vertexStream[i]; - resourcePool->Push(*stream.m_buffer); - vbBuffer.push_back(stream.m_buffer->m_handle); - vbOffsets.push_back(stream.m_offset); - vbStride.push_back(stream.m_stride); + for(auto& element: elements) { + for (size_t i = 0; i < packet->m_indvidual.m_numStreams; i++) { + auto& stream = packet->m_indvidual.m_vertexStream[i]; + if(stream.m_element == element) { + resourcePool->Push(*stream.m_buffer); + vbBuffer.push_back(stream.m_buffer->m_handle); + vbOffsets.push_back(stream.m_offset); + vbStride.push_back(stream.m_stride); + } + } } - cmdBindVertexBuffer(cmd, packet->m_indvidual.m_numStreams, vbBuffer.data(), vbStride.data(), vbOffsets.data()); + cmdBindVertexBuffer(cmd, elements.size(), vbBuffer.data(), vbStride.data(), vbOffsets.data()); cmdBindIndexBuffer(cmd, packet->m_indvidual.m_indexStream.buffer->m_handle, INDEX_TYPE_UINT32, packet->m_indvidual.m_indexStream.m_offset); break; } case DrawPacketType::DrawGeometryset: { - for(size_t i = 0; i < packet->m_unified.m_numStreams; i++) { - ShaderSemantic semantic = hplToForgeShaderSemantic(packet->m_unified.m_elements[i]); + for(size_t i = 0; i < elements.size(); i++) { + ShaderSemantic semantic = hplToForgeShaderSemantic(elements[i]); auto stream = packet->m_unified.m_subAllocation->getStreamBySemantic(semantic); vbBuffer.push_back(stream->buffer().m_handle); - vbOffsets.push_back((packet->m_unified.m_vertexOffset + packet->m_unified.m_subAllocation->vertextOffset()) * stream->stride()); + vbOffsets.push_back((packet->m_unified.m_vertexOffset + packet->m_unified.m_subAllocation->vertexOffset()) * stream->stride()); vbStride.push_back(stream->stride()); } - cmdBindVertexBuffer(cmd, packet->m_unified.m_numStreams, vbBuffer.data(), vbStride.data(), vbOffsets.data()); + cmdBindVertexBuffer(cmd, elements.size(), vbBuffer.data(), vbStride.data(), vbOffsets.data()); cmdBindIndexBuffer(cmd, packet->m_unified.m_subAllocation->indexBuffer().m_handle, INDEX_TYPE_UINT32, (packet->m_unified.m_subAllocation->indexOffset() + packet->m_unified.m_indexOffset) * GeometrySet::IndexBufferStride ); break; diff --git a/HPL2/sources/graphics/ForgeHandles.cpp b/HPL2/sources/graphics/ForgeHandles.cpp index 5f7e4d605..9ba20ad77 100644 --- a/HPL2/sources/graphics/ForgeHandles.cpp +++ b/HPL2/sources/graphics/ForgeHandles.cpp @@ -239,16 +239,20 @@ namespace hpl { addResource(&textureLoadDesc, &token); return true; }); + // hack to keep texture valid for the frame + waitForToken(&token); + ForgeRenderer* renderer = Interface::Get(); + renderer->GetFrame().m_resourcePool->Push(handle); + auto sourceImageFormat = FromHPLPixelFormat(bitmap.GetPixelFormat()); auto isCompressed = TinyImageFormat_IsCompressed(desc.mFormat); + TextureUpdateDesc update = {handle.m_handle, 0, desc.mMipLevels, 0, desc.mArraySize, RESOURCE_STATE_PIXEL_SHADER_RESOURCE}; + beginUpdateResource(&update); for(uint32_t arrIndex = 0; arrIndex < desc.mArraySize; arrIndex++) { for(uint32_t mipLevel = 0; mipLevel < desc.mMipLevels; mipLevel++) { - TextureUpdateDesc update = {handle.m_handle, mipLevel, arrIndex}; const auto& input = bitmap.GetData(arrIndex, mipLevel); - //auto data = std::span(input->mpData, static_cast(input->mlSize)); - beginUpdateResource(&update); - + uint32_t sourceRowStride; uint32_t destRowStride; if (!util_get_surface_info( @@ -274,25 +278,25 @@ namespace hpl { uint32_t dstElementStride = destRowStride / desc.mWidth; + TextureSubresourceUpdate updateSubResource = update.getSubresourceUpdateDesc(mipLevel, arrIndex); for (size_t z = 0; z < desc.mDepth; ++z) { - uint8_t* dstData = update.pMappedData + (update.mDstSliceStride * z); - auto srcData = input->mpData + update.mSrcSliceStride * z; - for (uint32_t row = 0; row < update.mRowCount; ++row) { + uint8_t* dstData = updateSubResource.pMappedData + (updateSubResource.mDstSliceStride * z); + auto srcData = input->mpData + updateSubResource.mSrcSliceStride * z; + for (uint32_t row = 0; row < updateSubResource.mRowCount; ++row) { if(isCompressed) { - std::memcpy(dstData + (row * update.mDstRowStride), srcData + (row * update.mSrcRowStride), update.mSrcRowStride); + std::memcpy(dstData + (row * updateSubResource.mDstRowStride), srcData + (row * updateSubResource.mSrcRowStride), updateSubResource.mSrcRowStride); } else { for(uint32_t column = 0; column < desc.mWidth; column++) { - std::memset(dstData + (row * update.mDstRowStride + column * dstElementStride), 0xff, dstElementStride); - std::memcpy(dstData + (row * update.mDstRowStride + column * dstElementStride), srcData + (row * sourceRowStride + column * srcElementStride), std::min(dstElementStride, srcElementStride)); + std::memset(dstData + (row * updateSubResource.mDstRowStride + column * dstElementStride), 0xff, dstElementStride); + std::memcpy(dstData + (row * updateSubResource.mDstRowStride + column * dstElementStride), srcData + (row * sourceRowStride + column * srcElementStride), std::min(dstElementStride, srcElementStride)); } } } } - endUpdateResource(&update, &token); } } - waitForToken(&token); + endUpdateResource(&update); return handle; } SharedTexture SharedTexture::CreateCubemapFromHPLBitmaps(const std::span bitmaps, const BitmapCubmapLoadOptions& options) { @@ -306,7 +310,7 @@ namespace hpl { desc.mArraySize = 6; desc.mFormat = FromHPLPixelFormat(bitmaps[0]->GetPixelFormat()); desc.mMipLevels = options.m_useMipmaps ? bitmaps[0]->GetNumOfMipMaps() : 1; - desc.mStartState = RESOURCE_STATE_COMMON; + desc.mStartState = RESOURCE_STATE_PIXEL_SHADER_RESOURCE; desc.mSampleCount = SAMPLE_COUNT_1; desc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE | DESCRIPTOR_TYPE_TEXTURE_CUBE; @@ -317,6 +321,10 @@ namespace hpl { addResource(&textureLoadDesc, &token); return true; }); + waitForToken(&token); + + TextureUpdateDesc update = {handle.m_handle, 0, desc.mMipLevels, 0, desc.mArraySize, RESOURCE_STATE_PIXEL_SHADER_RESOURCE}; + beginUpdateResource(&update); for(auto& bitmap : bitmaps) { ASSERT((options.m_useMipmaps || (bitmap->GetNumOfMipMaps() == desc.mMipLevels)) && "All bitmaps must have the same number of mipmaps"); @@ -334,29 +342,28 @@ namespace hpl { for(uint32_t arrIndex = 0; arrIndex < desc.mArraySize; arrIndex++) { for(uint32_t mipLevel = 0; mipLevel < desc.mMipLevels; mipLevel++) { - TextureUpdateDesc update = {handle.m_handle, mipLevel, arrIndex}; const auto& input = bitmap->GetData(arrIndex, mipLevel); auto data = std::span(input->mpData, static_cast(input->mlSize)); - beginUpdateResource(&update); + auto updateSubResource = update.getSubresourceUpdateDesc(mipLevel, arrIndex); for (uint32_t z = 0; z < desc.mDepth; ++z) { - uint32_t dstElementStride = update.mDstRowStride / desc.mWidth; - uint8_t* dstData = update.pMappedData + update.mDstSliceStride * z; - auto srcData = data.begin() + update.mSrcSliceStride * z; + uint32_t dstElementStride = updateSubResource .mDstRowStride / desc.mWidth; + uint8_t* dstData = updateSubResource.pMappedData + updateSubResource.mDstSliceStride * z; + auto srcData = data.begin() + updateSubResource.mSrcSliceStride * z; - for (uint32_t row = 0; row < update.mRowCount; ++row) { + for (uint32_t row = 0; row < updateSubResource.mRowCount; ++row) { if(isCompressed) { - std::memcpy(dstData + row * update.mDstRowStride, &srcData[row * update.mSrcRowStride], update.mSrcRowStride); + std::memcpy(dstData + row * updateSubResource.mDstRowStride, &srcData[row * updateSubResource.mSrcRowStride], updateSubResource.mSrcRowStride); } else { for(uint32_t column = 0; column < desc.mWidth; column++) { - std::memcpy(dstData + row * update.mDstRowStride + column * dstElementStride, &srcData[row * sourceRowStride + column * srcElementStride], std::min(dstElementStride, srcElementStride)); + std::memcpy(dstData + row * updateSubResource.mDstRowStride + column * dstElementStride, &srcData[row * sourceRowStride + column * srcElementStride], std::min(dstElementStride, srcElementStride)); } } } } - endUpdateResource(&update, &token); } } } + endUpdateResource(&update); return handle; } diff --git a/HPL2/sources/graphics/ForgeRenderer.cpp b/HPL2/sources/graphics/ForgeRenderer.cpp index d661c8fd6..c9ffad64b 100644 --- a/HPL2/sources/graphics/ForgeRenderer.cpp +++ b/HPL2/sources/graphics/ForgeRenderer.cpp @@ -1,11 +1,13 @@ #include +#include "Common_3/OS/Interfaces/IOperatingSystem.h" #include "engine/IUpdateEventLoop.h" #include "engine/Interface.h" #include "graphics/Material.h" #include "windowing/NativeWindow.h" #include "Common_3/Graphics/Interfaces/IGraphics.h" +#include "Common_3/Utilities/RingBuffer.h" #ifdef HPL2_RENDERDOC_ENABLED #ifdef WIN32 @@ -14,101 +16,117 @@ #endif #include "renderdoc_app.h" #endif -extern RendererApi gSelectedRendererApi; namespace hpl { - RendererApi ForgeRenderer::GetApi() { - return gSelectedRendererApi; - } void ForgeRenderer::IncrementFrame() { + if (!m_frame.m_isFinished) { + return; + } + m_frame.m_isFinished = false; + + // Stall if CPU is running "Swap Chain Buffer Count" frames ahead of GPU // m_resourcePoolIndex = (m_resourcePoolIndex + 1) % ResourcePoolSize; - m_currentFrameCount++; - auto frame = GetFrame(); - + //m_currentFrameCount++; + acquireNextImage(m_renderer, m_swapChain.m_handle, m_imageAcquiredSemaphore, NULL, &m_frame.m_swapChainIndex); + m_frame.m_cmdRingElement = getNextGpuCmdRingElement(&m_graphicsCmdRing, true, 1); FenceStatus fenceStatus; - auto& completeFence = frame.m_renderCompleteFence; - getFenceStatus(m_renderer, completeFence, &fenceStatus); - if (fenceStatus == FENCE_STATUS_INCOMPLETE) { - waitForFences(m_renderer, 1, &completeFence); - } - acquireNextImage(m_renderer, m_swapChain.m_handle, m_imageAcquiredSemaphore, nullptr, &m_swapChainIndex); + getFenceStatus(m_renderer, m_frame.m_cmdRingElement.pFence, &fenceStatus); + if (fenceStatus == FENCE_STATUS_INCOMPLETE) + waitForFences(m_renderer, 1, &m_frame.m_cmdRingElement.pFence); + + m_frame.m_currentFrame++; + m_frame.m_frameIndex = (m_frame.m_frameIndex + 1) % ForgeRenderer::SwapChainLength; + //m_frame.m_swapChainTarget = m_swapChain.m_handle->ppRenderTargets[m_frame.m_swapChainIndex]; + m_frame.m_finalRenderTarget = m_finalRenderTarget[m_frame.index()].m_handle; + m_frame.m_resourcePool = &m_resourcePool[m_frame.index()]; + m_frame.m_cmd = m_frame.cmd(); + m_frame.m_renderer = this; - resetCmdPool(m_renderer, frame.m_cmdPool); - frame.m_resourcePool->ResetPool(); - beginCmd(frame.m_cmd); - auto& swapChainImage = frame.m_swapChain->ppRenderTargets[m_swapChainIndex]; + resetCmdPool(m_renderer, m_frame.m_cmdRingElement.pCmdPool); + m_frame.m_resourcePool->ResetPool(); + beginCmd(m_frame.cmd()); + std::array rtBarriers = { - RenderTargetBarrier { swapChainImage, RESOURCE_STATE_PRESENT, RESOURCE_STATE_RENDER_TARGET }, + RenderTargetBarrier { m_frame.finalTarget(), RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, }; - frame.m_resourcePool->Push(m_finalRenderTarget[frame.m_frameIndex]); - cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); - + m_frame.pushResource(m_finalRenderTarget[m_frame.index()]); + cmdResourceBarrier(m_frame.cmd(), 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } void ForgeRenderer::SubmitFrame() { - auto frame = GetFrame(); - auto& swapChainTarget = frame.m_swapChain->ppRenderTargets[frame.m_swapChainIndex]; + RenderTarget* swapChainTarget = m_swapChain.m_handle->ppRenderTargets[m_frame.m_swapChainIndex]; { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(m_frame.cmd(), NULL); std::array rtBarriers = { - RenderTargetBarrier{ m_finalRenderTarget[frame.m_frameIndex].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE}, + RenderTargetBarrier { swapChainTarget, RESOURCE_STATE_PRESENT, RESOURCE_STATE_RENDER_TARGET }, + RenderTargetBarrier{ m_frame.finalTarget(), RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE}, }; - cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); + cmdResourceBarrier(m_frame.cmd(), 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } { - cmdBindRenderTargets(frame.m_cmd, 1, &swapChainTarget, NULL, NULL, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { swapChainTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(m_frame.cmd(), &bindRenderTargets); uint32_t rootConstantIndex = getDescriptorIndexFromName(m_finalRootSignature , "uRootConstants"); - cmdSetViewport(frame.m_cmd, 0.0f, 0.0f, static_cast(swapChainTarget->mWidth), static_cast(swapChainTarget->mHeight), 0.0f, 1.0f); - cmdSetScissor(frame.m_cmd, 0, 0, static_cast(swapChainTarget->mWidth), static_cast(swapChainTarget->mHeight)); - cmdBindPipeline(frame.m_cmd, m_finalPipeline.m_handle); - cmdBindPushConstants(frame.m_cmd, m_finalRootSignature, rootConstantIndex, &m_gamma); - - std::array params = {}; - params[0].pName = "sourceInput"; - params[0].ppTextures = &m_finalRenderTarget[frame.m_frameIndex].m_handle->pTexture; - updateDescriptorSet( - frame.m_renderer->Rend(), 0, m_finalPerFrameDescriptorSet[frame.m_frameIndex].m_handle, params.size(), params.data()); - cmdBindDescriptorSet(frame.m_cmd, 0, m_finalPerFrameDescriptorSet[frame.m_frameIndex].m_handle); - cmdDraw(frame.m_cmd, 3, 0); + cmdSetViewport(m_frame.cmd(), 0.0f, 0.0f, m_frame.finalTarget()->mWidth, m_frame.finalTarget()->mHeight, 0.0f, 1.0f); + cmdSetScissor(m_frame.cmd(), 0, 0, m_frame.finalTarget()->mWidth, m_frame.finalTarget()->mHeight); + cmdBindPipeline(m_frame.cmd(), m_finalPipeline.m_handle); + cmdBindPushConstants(m_frame.cmd(), m_finalRootSignature, rootConstantIndex, &m_gamma); + + std::array params = { + DescriptorData {.pName = "sourceInput", .ppTextures = &m_frame.finalTarget()->pTexture} + }; + updateDescriptorSet(m_renderer, 0, m_finalPerFrameDescriptorSet[m_frame.index()].m_handle, params.size(), params.data()); + cmdBindDescriptorSet(m_frame.cmd(), 0, m_finalPerFrameDescriptorSet[m_frame.index()].m_handle); + cmdDraw(m_frame.cmd(), 3, 0); } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(m_frame.cmd(), NULL); std::array rtBarriers = { - RenderTargetBarrier{ m_finalRenderTarget[frame.m_frameIndex].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET}, RenderTargetBarrier{ swapChainTarget, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_PRESENT }, }; - cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); + cmdResourceBarrier(m_frame.cmd(), 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } - endCmd(m_cmds[CurrentFrameIndex()]); + FlushResourceUpdateDesc flushUpdateDesc = {}; + flushUpdateDesc.mNodeIndex = 0; + flushResourceUpdates(&flushUpdateDesc); + endCmd(m_frame.cmd()); + + m_frame.m_waitSemaphores.push_back(flushUpdateDesc.pOutSubmittedSemaphore); + m_frame.m_waitSemaphores.push_back(m_imageAcquiredSemaphore); QueueSubmitDesc submitDesc = {}; + submitDesc.mWaitSemaphoreCount = m_frame.m_waitSemaphores.size(); + submitDesc.ppWaitSemaphores = m_frame.m_waitSemaphores.data(); submitDesc.mCmdCount = 1; + submitDesc.ppCmds = m_frame.RingElement().pCmds; submitDesc.mSignalSemaphoreCount = 1; - submitDesc.mWaitSemaphoreCount = 1; - submitDesc.ppCmds = &frame.m_cmd; - submitDesc.ppSignalSemaphores = &frame.m_renderCompleteSemaphore; - submitDesc.ppWaitSemaphores = &m_imageAcquiredSemaphore; - submitDesc.pSignalFence = frame.m_renderCompleteFence; + submitDesc.ppSignalSemaphores = &m_frame.RingElement().pSemaphore; + submitDesc.pSignalFence = m_frame.RingElement().pFence; queueSubmit(m_graphicsQueue, &submitDesc); QueuePresentDesc presentDesc = {}; - presentDesc.mIndex = m_swapChainIndex; + presentDesc.mIndex = m_frame.m_swapChainIndex; presentDesc.mWaitSemaphoreCount = 1; presentDesc.pSwapChain = m_swapChain.m_handle; - presentDesc.ppWaitSemaphores = &frame.m_renderCompleteSemaphore; + presentDesc.ppWaitSemaphores = &m_frame.RingElement().pSemaphore; presentDesc.mSubmitDone = true; queuePresent(m_graphicsQueue, &presentDesc); + + m_frame.m_waitSemaphores.clear(); + m_frame.m_isFinished = true; } void ForgeRenderer::InitializeRenderer(window::NativeWindowWrapper* window) { m_window = window; SyncToken token = {}; - RendererDesc desc{}; #ifdef HPL2_RENDERDOC_ENABLED static RENDERDOC_API_1_1_2* rdoc_api = NULL; @@ -126,177 +144,172 @@ namespace hpl { } #endif - #endif - - initRenderer("test", &desc, &m_renderer); - - QueueDesc queueDesc = {}; - queueDesc.mType = QUEUE_TYPE_GRAPHICS; - queueDesc.mFlag = QUEUE_FLAG_INIT_MICROPROFILE; - addQueue(m_renderer, &queueDesc, &m_graphicsQueue); - - for (size_t i = 0; i < m_cmds.size(); i++) { - CmdPoolDesc cmdPoolDesc = {}; - cmdPoolDesc.pQueue = m_graphicsQueue; - addCmdPool(m_renderer, &cmdPoolDesc, &m_cmdPools[i]); - CmdDesc cmdDesc = {}; - cmdDesc.pPool = m_cmdPools[i]; - addCmd(m_renderer, &cmdDesc, &m_cmds[i]); - } - - const auto windowSize = window->GetWindowSize(); - m_swapChain.Load(m_renderer, [&](SwapChain** handle) { - SwapChainDesc swapChainDesc = {}; - swapChainDesc.mWindowHandle = m_window->ForgeWindowHandle(); - swapChainDesc.mPresentQueueCount = 1; - swapChainDesc.ppPresentQueues = &m_graphicsQueue; - swapChainDesc.mWidth = windowSize.x; - swapChainDesc.mHeight = windowSize.y; - swapChainDesc.mImageCount = SwapChainLength; - swapChainDesc.mColorFormat = getRecommendedSwapchainFormat(false, false); - swapChainDesc.mColorClearValue = { { 1, 1, 1, 1 } }; - swapChainDesc.mEnableVsync = false; - addSwapChain(m_renderer, &swapChainDesc, handle); - return true; - }); - RootSignatureDesc graphRootDesc = {}; - addRootSignature(m_renderer, &graphRootDesc, &m_pipelineSignature); - - addSemaphore(m_renderer, &m_imageAcquiredSemaphore); - for (auto& completeSem : m_renderCompleteSemaphores) { - addSemaphore(m_renderer, &completeSem); - } - for (auto& completeFence : m_renderCompleteFences) { - addFence(m_renderer, &completeFence); - } - for(auto& rt: m_finalRenderTarget) { - rt.Load(m_renderer,[&](RenderTarget** target) { - RenderTargetDesc renderTarget = {}; - renderTarget.mArraySize = 1; - renderTarget.mClearValue.depth = 1.0f; - renderTarget.mDepth = 1; - renderTarget.mFormat = TinyImageFormat_R8G8B8A8_UNORM; - renderTarget.mWidth = windowSize.x; - renderTarget.mHeight = windowSize.y; - renderTarget.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; - renderTarget.mSampleCount = SAMPLE_COUNT_1; - renderTarget.mSampleQuality = 0; - renderTarget.mStartState = RESOURCE_STATE_RENDER_TARGET; - renderTarget.pName = "final RT"; - addRenderTarget(m_renderer, &renderTarget, target); - return true; - }); - } - m_pointSampler.Load(m_renderer, [&](Sampler **sampler) { - SamplerDesc samplerDesc = {}; - addSampler(m_renderer, &samplerDesc, sampler); - return true; - }); +#endif - { - m_finalShader.Load(m_renderer, [&](Shader** shader){ - ShaderLoadDesc shaderLoadDesc = {}; - shaderLoadDesc.mStages[0].pFileName = "fullscreen.vert"; - shaderLoadDesc.mStages[1].pFileName = "final_posteffect.frag"; - addShader(m_renderer, &shaderLoadDesc, shader); - return true; - }); - - std::array samplers = { - m_pointSampler.m_handle - }; - std::array samplerName = { - (const char*)"inputSampler" - }; - RootSignatureDesc rootDesc = { &m_finalShader.m_handle, 1 }; - rootDesc.ppStaticSamplers = samplers.data(); - rootDesc.ppStaticSamplerNames = samplerName.data(); - rootDesc.mStaticSamplerCount = 1; - addRootSignature(m_renderer, &rootDesc, &m_finalRootSignature); - - DescriptorSetDesc setDesc = { m_finalRootSignature, DESCRIPTOR_UPDATE_FREQ_PER_FRAME, 1}; - for(auto& desc: m_finalPerFrameDescriptorSet) { - desc.Load(m_renderer, [&](DescriptorSet** handle) { - addDescriptorSet(m_renderer, &setDesc, handle); + RendererDesc settings; + memset(&settings, 0, sizeof(settings)); + initRenderer("HPL2", &settings, &m_renderer); + + QueueDesc queueDesc = {}; + queueDesc.mType = QUEUE_TYPE_GRAPHICS; + queueDesc.mFlag = QUEUE_FLAG_INIT_MICROPROFILE; + addQueue(m_renderer, &queueDesc, &m_graphicsQueue); + + GpuCmdRingDesc cmdRingDesc = {}; + cmdRingDesc.pQueue = m_graphicsQueue; + cmdRingDesc.mPoolCount = SwapChainLength; + cmdRingDesc.mCmdPerPoolCount = 1; + cmdRingDesc.mAddSyncPrimitives = true; + addGpuCmdRing(m_renderer, &cmdRingDesc, &m_graphicsCmdRing); + + WindowHandle winHandle = m_window->ForgeWindowHandle(); + m_swapChainCount = getRecommendedSwapchainImageCount(m_renderer, &winHandle); + const auto windowSize = window->GetWindowSize(); + m_swapChain.Load(m_renderer, [&](SwapChain** handle) { + SwapChainDesc swapChainDesc = {}; + swapChainDesc.mWindowHandle = winHandle; + swapChainDesc.mPresentQueueCount = 1; + swapChainDesc.ppPresentQueues = &m_graphicsQueue; + swapChainDesc.mWidth = windowSize.x; + swapChainDesc.mHeight = windowSize.y; + swapChainDesc.mImageCount = m_swapChainCount; + swapChainDesc.mColorFormat = TinyImageFormat_R8G8B8A8_UNORM; // getRecommendedSwapchainFormat(false, false); + swapChainDesc.mColorSpace = COLOR_SPACE_SDR_LINEAR; + swapChainDesc.mColorClearValue = { { 1, 1, 1, 1 } }; + swapChainDesc.mEnableVsync = false; + addSwapChain(m_renderer, &swapChainDesc, handle); + return true; + }); + RootSignatureDesc graphRootDesc = {}; + addRootSignature(m_renderer, &graphRootDesc, &m_pipelineSignature); + + addSemaphore(m_renderer, &m_imageAcquiredSemaphore); + for (auto& rt : m_finalRenderTarget) { + rt.Load(m_renderer, [&](RenderTarget** target) { + RenderTargetDesc renderTarget = {}; + renderTarget.mArraySize = 1; + renderTarget.mClearValue.depth = 1.0f; + renderTarget.mDepth = 1; + renderTarget.mFormat = TinyImageFormat_R8G8B8A8_UNORM; + renderTarget.mWidth = windowSize.x; + renderTarget.mHeight = windowSize.y; + renderTarget.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; + renderTarget.mSampleCount = SAMPLE_COUNT_1; + renderTarget.mSampleQuality = 0; + renderTarget.mStartState = RESOURCE_STATE_SHADER_RESOURCE; + renderTarget.pName = "final output RT"; + addRenderTarget(m_renderer, &renderTarget, target); + return true; + }); + } + m_pointSampler.Load(m_renderer, [&](Sampler** sampler) { + SamplerDesc samplerDesc = {}; + addSampler(m_renderer, &samplerDesc, sampler); return true; }); - } - m_finalPipeline.Load(m_renderer, [&](Pipeline** pipeline) { - DepthStateDesc depthStateDisabledDesc = {}; - depthStateDisabledDesc.mDepthWrite = false; - depthStateDisabledDesc.mDepthTest = false; - - RasterizerStateDesc rasterStateNoneDesc = {}; - rasterStateNoneDesc.mCullMode = CULL_MODE_NONE; - - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_GRAPHICS; - GraphicsPipelineDesc& graphicsPipelineDesc = pipelineDesc.mGraphicsDesc; - graphicsPipelineDesc.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; - graphicsPipelineDesc.pShaderProgram = m_finalShader.m_handle; - graphicsPipelineDesc.pRootSignature = m_finalRootSignature; - graphicsPipelineDesc.mRenderTargetCount = 1; - graphicsPipelineDesc.mDepthStencilFormat = TinyImageFormat_UNDEFINED; - graphicsPipelineDesc.pVertexLayout = NULL; - graphicsPipelineDesc.pRasterizerState = &rasterStateNoneDesc; - graphicsPipelineDesc.pDepthState = &depthStateDisabledDesc; - graphicsPipelineDesc.pBlendState = NULL; - - graphicsPipelineDesc.pColorFormats = &m_swapChain.m_handle->ppRenderTargets[0]->mFormat; - graphicsPipelineDesc.mSampleCount = m_swapChain.m_handle->ppRenderTargets[0]->mSampleCount; - graphicsPipelineDesc.mSampleQuality = m_swapChain.m_handle->ppRenderTargets[0]->mSampleQuality; - addPipeline(m_renderer, &pipelineDesc, pipeline); - return true; - }); - } - { - ShaderLoadDesc postProcessCopyShaderDec = {}; - postProcessCopyShaderDec.mStages[0].pFileName = "fullscreen.vert"; - postProcessCopyShaderDec.mStages[1].pFileName = "post_processing_copy.frag"; - addShader(m_renderer, &postProcessCopyShaderDec, &m_copyShader); - - RootSignatureDesc rootDesc = { &m_copyShader, 1 }; - addRootSignature(m_renderer, &rootDesc, &m_copyPostProcessingRootSignature); - DescriptorSetDesc setDesc = { m_copyPostProcessingRootSignature, DESCRIPTOR_UPDATE_FREQ_PER_DRAW, MaxCopyFrames }; - addDescriptorSet(m_renderer, &setDesc, &m_copyPostProcessingDescriptorSet); - - DepthStateDesc depthStateDisabledDesc = {}; - depthStateDisabledDesc.mDepthWrite = false; - depthStateDisabledDesc.mDepthTest = false; - - RasterizerStateDesc rasterStateNoneDesc = {}; - rasterStateNoneDesc.mCullMode = CULL_MODE_NONE; - - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_GRAPHICS; - GraphicsPipelineDesc& copyPipelineDesc = pipelineDesc.mGraphicsDesc; - copyPipelineDesc.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; - copyPipelineDesc.pShaderProgram = m_copyShader; - copyPipelineDesc.pRootSignature = m_copyPostProcessingRootSignature; - copyPipelineDesc.mRenderTargetCount = 1; - copyPipelineDesc.mDepthStencilFormat = TinyImageFormat_UNDEFINED; - copyPipelineDesc.pVertexLayout = NULL; - copyPipelineDesc.pRasterizerState = &rasterStateNoneDesc; - copyPipelineDesc.pDepthState = &depthStateDisabledDesc; - copyPipelineDesc.pBlendState = NULL; - - { - TinyImageFormat format = TinyImageFormat_R8G8B8A8_UNORM; - copyPipelineDesc.pColorFormats = &format; - copyPipelineDesc.mSampleCount = SAMPLE_COUNT_1; - copyPipelineDesc.mSampleQuality = m_swapChain.m_handle->ppRenderTargets[0]->mSampleQuality; - addPipeline(m_renderer, &pipelineDesc, &m_copyPostProcessingPipelineToUnormR8G8B8A8); - } - { - copyPipelineDesc.pColorFormats = &m_swapChain.m_handle->ppRenderTargets[0]->mFormat; - copyPipelineDesc.mSampleCount = m_swapChain.m_handle->ppRenderTargets[0]->mSampleCount; - copyPipelineDesc.mSampleQuality = m_swapChain.m_handle->ppRenderTargets[0]->mSampleQuality; - addPipeline(m_renderer, &pipelineDesc, &m_copyPostProcessingPipelineToSwapChain ); - } - } + { + m_finalShader.Load(m_renderer, [&](Shader** shader) { + ShaderLoadDesc shaderLoadDesc = {}; + shaderLoadDesc.mStages[0].pFileName = "fullscreen.vert"; + shaderLoadDesc.mStages[1].pFileName = "final_posteffect.frag"; + addShader(m_renderer, &shaderLoadDesc, shader); + return true; + }); + + std::array samplers = { m_pointSampler.m_handle }; + std::array samplerName = { (const char*)"inputSampler" }; + RootSignatureDesc rootDesc = { &m_finalShader.m_handle, 1 }; + rootDesc.ppStaticSamplers = samplers.data(); + rootDesc.ppStaticSamplerNames = samplerName.data(); + rootDesc.mStaticSamplerCount = 1; + addRootSignature(m_renderer, &rootDesc, &m_finalRootSignature); + + DescriptorSetDesc setDesc = { m_finalRootSignature, DESCRIPTOR_UPDATE_FREQ_PER_FRAME, 1 }; + for (auto& desc : m_finalPerFrameDescriptorSet) { + desc.Load(m_renderer, [&](DescriptorSet** handle) { + addDescriptorSet(m_renderer, &setDesc, handle); + return true; + }); + } + m_finalPipeline.Load(m_renderer, [&](Pipeline** pipeline) { + DepthStateDesc depthStateDisabledDesc = {}; + depthStateDisabledDesc.mDepthWrite = false; + depthStateDisabledDesc.mDepthTest = false; + + RasterizerStateDesc rasterStateNoneDesc = {}; + rasterStateNoneDesc.mCullMode = CULL_MODE_NONE; + + PipelineDesc pipelineDesc = {}; + pipelineDesc.mType = PIPELINE_TYPE_GRAPHICS; + GraphicsPipelineDesc& graphicsPipelineDesc = pipelineDesc.mGraphicsDesc; + graphicsPipelineDesc.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; + graphicsPipelineDesc.pShaderProgram = m_finalShader.m_handle; + graphicsPipelineDesc.pRootSignature = m_finalRootSignature; + graphicsPipelineDesc.mRenderTargetCount = 1; + graphicsPipelineDesc.mDepthStencilFormat = TinyImageFormat_UNDEFINED; + graphicsPipelineDesc.pVertexLayout = NULL; + graphicsPipelineDesc.pRasterizerState = &rasterStateNoneDesc; + graphicsPipelineDesc.pDepthState = &depthStateDisabledDesc; + graphicsPipelineDesc.pBlendState = NULL; + + graphicsPipelineDesc.pColorFormats = &m_swapChain.m_handle->ppRenderTargets[0]->mFormat; + graphicsPipelineDesc.mSampleCount = m_swapChain.m_handle->ppRenderTargets[0]->mSampleCount; + graphicsPipelineDesc.mSampleQuality = m_swapChain.m_handle->ppRenderTargets[0]->mSampleQuality; + addPipeline(m_renderer, &pipelineDesc, pipeline); + return true; + }); + } + { + ShaderLoadDesc postProcessCopyShaderDec = {}; + postProcessCopyShaderDec.mStages[0].pFileName = "fullscreen.vert"; + postProcessCopyShaderDec.mStages[1].pFileName = "post_processing_copy.frag"; + addShader(m_renderer, &postProcessCopyShaderDec, &m_copyShader); + + RootSignatureDesc rootDesc = { &m_copyShader, 1 }; + addRootSignature(m_renderer, &rootDesc, &m_copyPostProcessingRootSignature); + DescriptorSetDesc setDesc = { m_copyPostProcessingRootSignature, DESCRIPTOR_UPDATE_FREQ_PER_DRAW, MaxCopyFrames }; + addDescriptorSet(m_renderer, &setDesc, &m_copyPostProcessingDescriptorSet[0]); + addDescriptorSet(m_renderer, &setDesc, &m_copyPostProcessingDescriptorSet[1]); + + DepthStateDesc depthStateDisabledDesc = {}; + depthStateDisabledDesc.mDepthWrite = false; + depthStateDisabledDesc.mDepthTest = false; + + RasterizerStateDesc rasterStateNoneDesc = {}; + rasterStateNoneDesc.mCullMode = CULL_MODE_NONE; + + PipelineDesc pipelineDesc = {}; + pipelineDesc.mType = PIPELINE_TYPE_GRAPHICS; + GraphicsPipelineDesc& copyPipelineDesc = pipelineDesc.mGraphicsDesc; + copyPipelineDesc.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; + copyPipelineDesc.pShaderProgram = m_copyShader; + copyPipelineDesc.pRootSignature = m_copyPostProcessingRootSignature; + copyPipelineDesc.mRenderTargetCount = 1; + copyPipelineDesc.mDepthStencilFormat = TinyImageFormat_UNDEFINED; + copyPipelineDesc.pVertexLayout = NULL; + copyPipelineDesc.pRasterizerState = &rasterStateNoneDesc; + copyPipelineDesc.pDepthState = &depthStateDisabledDesc; + copyPipelineDesc.pBlendState = NULL; + + { + TinyImageFormat format = TinyImageFormat_R8G8B8A8_UNORM; + copyPipelineDesc.pColorFormats = &format; + copyPipelineDesc.mSampleCount = SAMPLE_COUNT_1; + copyPipelineDesc.mSampleQuality = m_swapChain.m_handle->ppRenderTargets[0]->mSampleQuality; + addPipeline(m_renderer, &pipelineDesc, &m_copyPostProcessingPipelineToUnormR8G8B8A8); + } + + { + copyPipelineDesc.pColorFormats = &m_swapChain.m_handle->ppRenderTargets[0]->mFormat; + copyPipelineDesc.mSampleCount = m_swapChain.m_handle->ppRenderTargets[0]->mSampleCount; + copyPipelineDesc.mSampleQuality = m_swapChain.m_handle->ppRenderTargets[0]->mSampleQuality; + addPipeline(m_renderer, &pipelineDesc, &m_copyPostProcessingPipelineToSwapChain); + } + } - m_windowEventHandler.Connect(window->NativeWindowEvent()); + m_windowEventHandler.Connect(window->NativeWindowEvent()); + IncrementFrame(); } Sampler* ForgeRenderer::resolve(SamplerPoolKey key) { @@ -326,15 +339,16 @@ namespace hpl { swapChainDesc.ppPresentQueues = &m_graphicsQueue; swapChainDesc.mWidth = windowSize.x; swapChainDesc.mHeight = windowSize.y; - swapChainDesc.mImageCount = SwapChainLength; - swapChainDesc.mColorFormat = getRecommendedSwapchainFormat(false, false); + swapChainDesc.mImageCount = m_swapChainCount; + swapChainDesc.mColorFormat = TinyImageFormat_R8G8B8A8_UNORM;//getRecommendedSwapchainFormat(false, false); + swapChainDesc.mColorSpace = COLOR_SPACE_SDR_LINEAR; swapChainDesc.mColorClearValue = { { 1, 1, 1, 1 } }; - swapChainDesc.mEnableVsync = false; + swapChainDesc.mEnableVsync = true; addSwapChain(m_renderer, &swapChainDesc, handle); return true; }); - removeSemaphore(m_renderer, m_imageAcquiredSemaphore); - addSemaphore(m_renderer, &m_imageAcquiredSemaphore); + //removeSemaphore(m_renderer, m_imageAcquiredSemaphore); + //addSemaphore(m_renderer, &m_imageAcquiredSemaphore); for(auto& rt: m_finalRenderTarget) { rt.Load(m_renderer,[&](RenderTarget** target) { RenderTargetDesc renderTarget = {}; @@ -347,7 +361,7 @@ namespace hpl { renderTarget.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; renderTarget.mSampleCount = SAMPLE_COUNT_1; renderTarget.mSampleQuality = 0; - renderTarget.mStartState = RESOURCE_STATE_RENDER_TARGET; + renderTarget.mStartState = RESOURCE_STATE_SHADER_RESOURCE; renderTarget.pName = "final RT"; addRenderTarget(m_renderer, &renderTarget, target); return true; @@ -361,27 +375,25 @@ namespace hpl { }){ } - void ForgeRenderer::InitializeResource() { - } void ForgeRenderer::cmdCopyTexture(Cmd* cmd, Texture* srcTexture, RenderTarget* dstTexture) { ASSERT(srcTexture != nullptr); ASSERT(dstTexture != nullptr); + m_copyRegionDescriptorIndex = (m_copyRegionDescriptorIndex + 1) % MaxCopyFrames; - std::array params = {}; - params[0].pName = "inputMap"; - params[0].ppTextures = &srcTexture; - - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + std::array params = { + DescriptorData { .pName = "inputMap", .ppTextures = &srcTexture} + }; - cmdBindRenderTargets(cmd, 1, &dstTexture, NULL, &loadActions, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { dstTexture, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(cmd, &bindRenderTargets); cmdSetViewport(cmd, 0.0f, 0.0f, static_cast(dstTexture->mWidth), static_cast(dstTexture->mHeight), 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, dstTexture->mWidth, dstTexture->mHeight); - updateDescriptorSet(m_renderer, m_copyRegionDescriptorIndex, m_copyPostProcessingDescriptorSet, params.size(), params.data()); - auto swapChainFormat = getRecommendedSwapchainFormat(false, false); + updateDescriptorSet(m_renderer, m_copyRegionDescriptorIndex, m_copyPostProcessingDescriptorSet[m_frame.index()], params.size(), params.data()); + auto swapChainFormat = TinyImageFormat_R8G8B8A8_UNORM;//getSupportedSwapchainFormat(m_renderer, false, false); switch(dstTexture->mFormat) { case TinyImageFormat_R8G8B8A8_UNORM: cmdBindPipeline(cmd, m_copyPostProcessingPipelineToUnormR8G8B8A8); @@ -391,9 +403,8 @@ namespace hpl { break; } - cmdBindDescriptorSet(cmd, m_copyRegionDescriptorIndex, m_copyPostProcessingDescriptorSet); + cmdBindDescriptorSet(cmd, m_copyRegionDescriptorIndex, m_copyPostProcessingDescriptorSet[m_frame.index()]); cmdDraw(cmd, 3, 0); - m_copyRegionDescriptorIndex = (m_copyRegionDescriptorIndex + 1) % MaxCopyFrames; } }; // namespace hpl diff --git a/HPL2/sources/graphics/ForwardResources.cpp b/HPL2/sources/graphics/ForwardResources.cpp deleted file mode 100644 index 9004b6d3d..000000000 --- a/HPL2/sources/graphics/ForwardResources.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include "graphics/ForwardResources.h" -#include "graphics/GraphicsTypes.h" -#include "graphics/Material.h" - -#include -#include - -namespace hpl::resource { - - LightResourceVariants CreateFromLight(iLight& light) { - return std::monostate{}; - } - - void visitTextures(MaterialTypes& material, std::function handler) { - if(auto* item = std::get_if(&material)) { - struct { - eMaterialTexture m_type; - uint16_t* m_value; - } m_textures[] = { - {eMaterialTexture_Diffuse, &item->m_tex.m_diffues}, - {eMaterialTexture_NMap, &item->m_tex.m_normal}, - {eMaterialTexture_Specular, &item->m_tex.m_specular}, - {eMaterialTexture_Alpha, &item->m_tex.m_alpha}, - {eMaterialTexture_Height, &item->m_tex.m_height}, - {eMaterialTexture_Illumination, &item->m_tex.m_illuminiation}, - {eMaterialTexture_DissolveAlpha, &item->m_tex.m_dissolveAlpha}, - {eMaterialTexture_CubeMapAlpha, &item->m_tex.m_cubeMapAlpha}, - }; - for(auto& tex: m_textures) { - if(*tex.m_value != UINT16_MAX) { - handler(tex.m_type, *tex.m_value); - } - } - } - } - std::variant createMaterial(TextureDescriptorPool& pool, cMaterial* material) { - ASSERT(material); - auto& descriptor = material->Descriptor(); - switch (descriptor.m_id) { - case hpl::MaterialID::SolidDiffuse: { - DiffuseMaterial result = {}; - struct { - eMaterialTexture m_type; - uint16_t* m_value; - } m_textures[] = { - {eMaterialTexture_Diffuse, &result.m_tex.m_diffues}, - {eMaterialTexture_NMap, &result.m_tex.m_normal}, - {eMaterialTexture_Alpha, &result.m_tex.m_alpha}, - {eMaterialTexture_Specular, &result.m_tex.m_specular}, - {eMaterialTexture_Height, &result.m_tex.m_height}, - {eMaterialTexture_Illumination, &result.m_tex.m_illuminiation}, - {eMaterialTexture_DissolveAlpha, &result.m_tex.m_dissolveAlpha}, - {eMaterialTexture_CubeMapAlpha, &result.m_tex.m_cubeMapAlpha}, - }; - for(auto& tex: m_textures) { - auto* image = material->GetImage(tex.m_type); - (*tex.m_value) = UINT16_MAX; - if(image) { - uint32_t handle = pool.request(image->GetTexture()); - (*tex.m_value) = static_cast(handle); - } - } - result.m_heightMapScale = descriptor.m_solid.m_heightMapScale; - result.m_heigtMapBias = descriptor.m_solid.m_heightMapBias; - result.m_frenselBias = descriptor.m_solid.m_frenselBias; - result.m_frenselPow = descriptor.m_solid.m_frenselPow; - return result; - } - case hpl::MaterialID::Decal: - break; - case hpl::MaterialID::Translucent: - break; - case hpl::MaterialID::Water: - break; - default: - break; - } - return std::monostate{}; - } -} diff --git a/HPL2/sources/graphics/GeometrySet.cpp b/HPL2/sources/graphics/GeometrySet.cpp index c33834628..7c374ecfa 100644 --- a/HPL2/sources/graphics/GeometrySet.cpp +++ b/HPL2/sources/graphics/GeometrySet.cpp @@ -22,6 +22,17 @@ namespace hpl { auto subAllocation = std::make_shared(); subAllocation->m_indexAllocation = m_indexStreamAllocator.allocate(numIndecies); subAllocation->m_vertexAllocation = m_vertexStreamAllocator.allocate(numElements); + + auto vertexStorageReport = m_vertexStreamAllocator.storageReport(); + auto indexStorageReport = m_indexStreamAllocator.storageReport(); + LOGF(LogLevel::eINFO, "vertex storage total free space: %d largest region: %d", vertexStorageReport.totalFreeSpace, vertexStorageReport.largestFreeRegion); + LOGF(LogLevel::eINFO, "index storage total free space: %d largest region: %d", indexStorageReport.totalFreeSpace, indexStorageReport.largestFreeRegion); + + ASSERT(subAllocation->m_indexAllocation.offset != OffsetAllocator::Allocation::NO_SPACE); + ASSERT(subAllocation->m_indexAllocation.metadata != OffsetAllocator::Allocation::NO_SPACE); + ASSERT(subAllocation->m_vertexAllocation.offset != OffsetAllocator::Allocation::NO_SPACE); + ASSERT(subAllocation->m_vertexAllocation.metadata != OffsetAllocator::Allocation::NO_SPACE); + subAllocation->m_geometrySet = this; return subAllocation; @@ -49,8 +60,10 @@ namespace hpl { vertexStream.m_buffer.Load([&](Buffer** buffer) { BufferLoadDesc loadDesc = {}; loadDesc.ppBuffer = buffer; - loadDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER; + loadDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER | DESCRIPTOR_TYPE_BUFFER_RAW; loadDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; + loadDesc.mDesc.mStructStride = vertexStream.m_stride; + loadDesc.mDesc.mElementCount = numElements; loadDesc.mDesc.mSize = numElements * vertexStream.m_stride; loadDesc.mDesc.pName = desc.m_name; addResource(&loadDesc, nullptr); @@ -60,8 +73,10 @@ namespace hpl { m_indexBuffer.Load([&](Buffer** buffer) { BufferLoadDesc loadDesc = {}; loadDesc.ppBuffer = buffer; - loadDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_INDEX_BUFFER; + loadDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_INDEX_BUFFER | DESCRIPTOR_TYPE_BUFFER_RAW; loadDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; + loadDesc.mDesc.mStructStride = sizeof(uint32_t); + loadDesc.mDesc.mElementCount = numIndecies; loadDesc.mDesc.mSize = numIndecies * sizeof(uint32_t); loadDesc.mDesc.pName = "GeometrySet Index"; addResource(&loadDesc, nullptr); diff --git a/HPL2/sources/graphics/Graphics.cpp b/HPL2/sources/graphics/Graphics.cpp index eeda4159f..e29b2e1b6 100644 --- a/HPL2/sources/graphics/Graphics.cpp +++ b/HPL2/sources/graphics/Graphics.cpp @@ -24,7 +24,6 @@ #include "engine/Updateable.h" #include "graphics/ForgeRenderer.h" -#include "graphics/RendererForwardPlus.h" #include "system/LowLevelSystem.h" #include "system/String.h" #include "system/Platform.h" @@ -150,11 +149,7 @@ namespace hpl { mvRenderers.resize(2, NULL); m_debug = std::make_shared(Interface::Get()); - #if USE_FORWARD_PLUS_BACKEND - mvRenderers[eRenderer_Main] = new RendererForwardPlus(this, apResources, m_debug); - #else - mvRenderers[eRenderer_Main] = new cRendererDeferred(this, apResources, m_debug); - #endif + mvRenderers[eRenderer_Main] = new cRendererDeferred(this, apResources, m_debug); mvRenderers[eRenderer_WireFrame] = new cRendererWireFrame(this, apResources, m_debug); } else diff --git a/HPL2/sources/graphics/GraphicsAllocator.cpp b/HPL2/sources/graphics/GraphicsAllocator.cpp index abb509160..d13dcc36d 100644 --- a/HPL2/sources/graphics/GraphicsAllocator.cpp +++ b/HPL2/sources/graphics/GraphicsAllocator.cpp @@ -20,6 +20,14 @@ namespace hpl { }; m_geometrySets[AllocationSet::OpaqueSet] = GeometrySet(OpaqueVertexBufferSize, OpaqueIndexBufferSize, streamDesc); } + { + std::array streamDesc = { + GeometrySet::GeometryStreamDesc("opaque_position", ShaderSemantic::SEMANTIC_POSITION, sizeof(float3)), + GeometrySet::GeometryStreamDesc("opaque_uv0", ShaderSemantic::SEMANTIC_TEXCOORD0, sizeof(float2)), + GeometrySet::GeometryStreamDesc("opaque_color", ShaderSemantic::SEMANTIC_COLOR, sizeof(float4)), + }; + m_geometrySets[AllocationSet::ParticleSet] = GeometrySet(ParticleVertexBufferSize, ParticleIndexBufferSize, streamDesc); + } { BufferDesc desc = {}; @@ -40,18 +48,9 @@ namespace hpl { } GPURingBufferOffset GraphicsAllocator::allocTransientVertexBuffer(uint32_t size) { - return getGPURingBufferOffset(m_transientVertexBuffer, size); + return getGPURingBufferOffset(&m_transientVertexBuffer, size); } GPURingBufferOffset GraphicsAllocator::allocTransientIndexBuffer(uint32_t size) { - return getGPURingBufferOffset(m_transientIndeciesBuffer, size); + return getGPURingBufferOffset(&m_transientIndeciesBuffer, size); } - - // GraphicsAllocator::OffsetAllocHandle GraphicsAllocator::allocVertexFromSharedBuffer(uint32_t size) { - // OffsetAllocator::Allocation alloc = m_vertexBufferAllocator.allocate(size); - // return OffsetAllocHandle(&m_vertexBufferAllocator, alloc, m_sharedVertexBuffer); - // } - // GraphicsAllocator::OffsetAllocHandle GraphicsAllocator::allocIndeciesFromSharedBuffer(uint32_t size) { - // OffsetAllocator::Allocation alloc = m_indexBufferAllocator.allocate(size); - // return OffsetAllocHandle(&m_indexBufferAllocator, alloc, m_sharedIndexBuffer); - // } } // namespace hpl diff --git a/HPL2/sources/graphics/GraphicsTypes.cpp b/HPL2/sources/graphics/GraphicsTypes.cpp index 229e802a3..a45656481 100644 --- a/HPL2/sources/graphics/GraphicsTypes.cpp +++ b/HPL2/sources/graphics/GraphicsTypes.cpp @@ -25,11 +25,17 @@ namespace hpl { - ////////////////////////////////////////////////////////////////////////// - // GLOBAL FUNCTIONS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- + eShadowMapResolution GetShadowMapResolution(eShadowMapResolution aWanted, eShadowMapResolution aMax) { + if (aMax == eShadowMapResolution_High) + { + return aWanted; + } + else if (aMax == eShadowMapResolution_Medium) + { + return aWanted == eShadowMapResolution_High ? eShadowMapResolution_Medium : aWanted; + } + return eShadowMapResolution_Low; + } tVertexElementFlag GetVertexElementFlagFromEnum(eVertexBufferElement aElement) { diff --git a/HPL2/sources/graphics/IndexPool.cpp b/HPL2/sources/graphics/IndexPool.cpp index a4a0a7cf7..052de75f0 100644 --- a/HPL2/sources/graphics/IndexPool.cpp +++ b/HPL2/sources/graphics/IndexPool.cpp @@ -7,10 +7,16 @@ namespace hpl { - IndexPool::IndexPool(uint32_t reserve) { + IndexPool::IndexPool(uint32_t reserve): + m_reserve(reserve) { m_avaliable.push_back({0, reserve - 1}); } + IndexPool::IndexPool(): + m_reserve(0) { + + } + uint32_t IndexPool::requestId() { if(m_avaliable.size() > 0) { auto& entry = m_avaliable[m_avaliable.size() - 1]; @@ -23,7 +29,8 @@ namespace hpl { entry.m_end--; return res; } - return UINT32_MAX; + LOGF(LogLevel::eERROR, "ran out of index in pool."); + return IndexPool::InvalidHandle; } void IndexPool::returnId(uint32_t index) { diff --git a/HPL2/sources/graphics/Material.cpp b/HPL2/sources/graphics/Material.cpp index 099068e2b..f7ad95d0f 100644 --- a/HPL2/sources/graphics/Material.cpp +++ b/HPL2/sources/graphics/Material.cpp @@ -52,11 +52,11 @@ namespace hpl { void cMaterial::SetTextureAnisotropy(float afx) { if (afx >= 16.0f) { - m_antistropy = Antistropy_16; + m_antistropy = TextureAntistropy::Antistropy_16; } else if (afx >= 8.0f) { - m_antistropy = Antistropy_8; + m_antistropy = TextureAntistropy::Antistropy_8; } else { - m_antistropy = Antistropy_None; + m_antistropy = TextureAntistropy::Antistropy_None; } IncreaseGeneration(); } @@ -218,7 +218,6 @@ namespace hpl { } case eMaterialUvAnimation_Rotate: { cVector3f vDir = GetAxisVector(pAnim->mAxis); - cMatrixf mtxRot = cMath::MatrixRotate(vDir * pAnim->mfSpeed * mfAnimTime, eEulerRotationOrder_XYZ); m_mtxUV = cMath::MatrixMul(m_mtxUV, mtxRot); break; diff --git a/HPL2/sources/graphics/PassHBAOPlus.cpp b/HPL2/sources/graphics/PassHBAOPlus.cpp index 82cf21af8..770f8c9ef 100644 --- a/HPL2/sources/graphics/PassHBAOPlus.cpp +++ b/HPL2/sources/graphics/PassHBAOPlus.cpp @@ -219,7 +219,7 @@ namespace hpl::renderer { BufferUpdateDesc updateDesc = { viewportData->m_constBuffer.m_handle, 0, sizeof(HBAORootConstant) }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = constData; - endUpdateResource(&updateDesc, &token); + endUpdateResource(&updateDesc); waitForToken(&token); { std::array descriptorData = {}; diff --git a/HPL2/sources/graphics/PostEffectComposite.cpp b/HPL2/sources/graphics/PostEffectComposite.cpp index 4764d0ee1..164c8be88 100644 --- a/HPL2/sources/graphics/PostEffectComposite.cpp +++ b/HPL2/sources/graphics/PostEffectComposite.cpp @@ -96,14 +96,14 @@ namespace hpl { return; } if(pogoTargetIndex == 0) { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ boundData->m_renderTarget[0].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, RenderTargetBarrier{ boundData->m_renderTarget[1].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE}, }; cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } else { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ boundData->m_renderTarget[0].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE}, RenderTargetBarrier{ boundData->m_renderTarget[1].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, diff --git a/HPL2/sources/graphics/PostEffect_Bloom.cpp b/HPL2/sources/graphics/PostEffect_Bloom.cpp index 6f8201a40..d35cd7b5f 100644 --- a/HPL2/sources/graphics/PostEffect_Bloom.cpp +++ b/HPL2/sources/graphics/PostEffect_Bloom.cpp @@ -23,15 +23,9 @@ #include "graphics/ForgeHandles.h" #include "graphics/Graphics.h" -#include "graphics/FrameBuffer.h" -#include "graphics/Image.h" -#include "graphics/LowLevelGraphics.h" #include "graphics/PostEffectComposite.h" -#include "graphics/RenderTarget.h" -#include "graphics/Texture.h" #include "math/MathTypes.h" -#include "system/PreprocessParser.h" #include namespace hpl @@ -227,7 +221,7 @@ namespace hpl ASSERT(input && "Invalid input texture"); uint32_t blurPostEffectConstIndex = getDescriptorIndexFromName(mpBloomType->m_blurSignature.m_handle, "rootConstant"); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ bloomData->m_blurTargets[0].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, RenderTargetBarrier{ bloomData->m_blurTargets[1].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE}, @@ -235,11 +229,16 @@ namespace hpl cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; auto& blurTarget = bloomData->m_blurTargets[0].m_handle; - cmdBindRenderTargets(frame.m_cmd, 1, &blurTarget , NULL, &loadActions, NULL, NULL, -1, -1); + //LoadActionsDesc loadActions = {}; + //loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + //loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //cmdBindRenderTargets(frame.m_cmd, 1, &blurTarget , NULL, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { blurTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets ); std::array params = {}; params[0].pName = "sourceInput"; @@ -253,12 +252,13 @@ namespace hpl cmdBindDescriptorSet(frame.m_cmd, mpBloomType->m_setIndex, mpBloomType->m_perFrameDescriptorSets[frame.m_frameIndex].m_handle); float2 blurScale = float2(mParams.mfBlurSize, 0.0f); + cmdBindPushConstants(frame.m_cmd, mpBloomType->m_blurSignature.m_handle, blurPostEffectConstIndex, &blurScale); cmdDraw(frame.m_cmd, 3, 0); mpBloomType->m_setIndex = (mpBloomType->m_setIndex + 1) % cPostEffectType_Bloom::DescriptorSetSize; } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ bloomData->m_blurTargets[0].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, @@ -268,12 +268,17 @@ namespace hpl cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - auto& blurTarget = bloomData->m_blurTargets[1].m_handle; - cmdBindRenderTargets(frame.m_cmd, 1, &blurTarget, NULL, &loadActions, NULL, NULL, -1, -1); + //LoadActionsDesc loadActions = {}; + //loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + //loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //cmdBindRenderTargets(frame.m_cmd, 1, &blurTarget, NULL, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { blurTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets ); + std::array params = {}; params[0].pName = "sourceInput"; @@ -301,7 +306,7 @@ namespace hpl } cmdEndDebugMarker(frame.m_cmd); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ bloomData->m_blurTargets[1].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, @@ -315,11 +320,14 @@ namespace hpl } { cmdBeginDebugMarker(frame.m_cmd, 0, 1, 0, "Bloom Add"); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - - cmdBindRenderTargets(frame.m_cmd, 1, &renderTarget, NULL, &loadActions, NULL, NULL, -1, -1); + //LoadActionsDesc loadActions = {}; + //loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + //loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //cmdBindRenderTargets(frame.m_cmd, 1, &renderTarget, NULL, &loadActions, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { renderTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); std::array params = {}; params[0].pName = "sourceInput"; @@ -340,7 +348,7 @@ namespace hpl cmdEndDebugMarker(frame.m_cmd); } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ bloomData->m_blurTargets[1].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, diff --git a/HPL2/sources/graphics/PostEffect_ColorConvTex.cpp b/HPL2/sources/graphics/PostEffect_ColorConvTex.cpp index 4021dc5e7..064c694b2 100644 --- a/HPL2/sources/graphics/PostEffect_ColorConvTex.cpp +++ b/HPL2/sources/graphics/PostEffect_ColorConvTex.cpp @@ -154,11 +154,10 @@ namespace hpl uint32_t rootConstantIndex = getDescriptorIndexFromName(mpSpecificType->m_rootSignature.m_handle, "rootConstant"); cmdBindPushConstants(frame.m_cmd, mpSpecificType->m_rootSignature.m_handle, rootConstantIndex, &alphaFade); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - - cmdBindRenderTargets(frame.m_cmd, 1, &renderTarget, NULL, &loadActions, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { renderTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); std::array params = {}; params[0].pName = "sourceInput"; diff --git a/HPL2/sources/graphics/PostEffect_ImageTrail.cpp b/HPL2/sources/graphics/PostEffect_ImageTrail.cpp index 53390bc30..d1d799dca 100644 --- a/HPL2/sources/graphics/PostEffect_ImageTrail.cpp +++ b/HPL2/sources/graphics/PostEffect_ImageTrail.cpp @@ -82,11 +82,7 @@ namespace hpl { blendStateDesc.mSrcAlphaFactors[0] = BC_SRC_ALPHA; blendStateDesc.mDstAlphaFactors[0] = BC_ONE_MINUS_SRC_ALPHA; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; - #ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = ALL; - #else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; - #endif + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -180,7 +176,7 @@ namespace hpl { } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ imageTrailData->m_accumulationTarget.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, @@ -207,12 +203,16 @@ namespace hpl { updateDescriptorSet(renderer->Rend(), mpImageTrailType->m_descIndex, mpImageTrailType->m_perFrameDescriptorSet[frame.m_frameIndex].m_handle, params.size(), params.data()); } - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //LoadActionsDesc loadActions = {}; + //loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + //loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //std::array inputTargets = { imageTrailData->m_accumulationTarget.m_handle }; + //cmdBindRenderTargets(frame.m_cmd, inputTargets.size(), inputTargets.data(), NULL, &loadActions, NULL, NULL, -1, -1); - std::array inputTargets = { imageTrailData->m_accumulationTarget.m_handle }; - cmdBindRenderTargets(frame.m_cmd, inputTargets.size(), inputTargets.data(), NULL, &loadActions, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { imageTrailData->m_accumulationTarget.m_handle , LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); uint32_t rootConstantIndex = getDescriptorIndexFromName(mpImageTrailType->m_rootSignature.m_handle, "rootConstant"); cmdBindPushConstants(frame.m_cmd, mpImageTrailType->m_rootSignature.m_handle, rootConstantIndex, &alpha); @@ -223,7 +223,7 @@ namespace hpl { cmdDraw(frame.m_cmd, 3, 0); mpImageTrailType->m_descIndex = (mpImageTrailType->m_descIndex + 1) % cPostEffectType_ImageTrail::DescSetSize; { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ imageTrailData->m_accumulationTarget.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, diff --git a/HPL2/sources/graphics/PostEffect_RadialBlur.cpp b/HPL2/sources/graphics/PostEffect_RadialBlur.cpp index e9d8e1cf6..25fb5384c 100644 --- a/HPL2/sources/graphics/PostEffect_RadialBlur.cpp +++ b/HPL2/sources/graphics/PostEffect_RadialBlur.cpp @@ -143,11 +143,15 @@ namespace hpl uint32_t rootConstantIndex = getDescriptorIndexFromName(mpRadialBlurType->m_rootSignature.m_handle, "rootConstant"); cmdBindPushConstants(frame.m_cmd, mpRadialBlurType->m_rootSignature.m_handle, rootConstantIndex, ¶ms); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - - cmdBindRenderTargets(frame.m_cmd, 1, &renderTarget, NULL, &loadActions, NULL, NULL, -1, -1); + //LoadActionsDesc loadActions = {}; + //loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + //loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //cmdBindRenderTargets(frame.m_cmd, 1, &renderTarget, NULL, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { renderTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); std::array descData = {}; descData[0].pName = "sourceInput"; diff --git a/HPL2/sources/graphics/RenderList.cpp b/HPL2/sources/graphics/RenderList.cpp index 5e16f98f1..d65eebf73 100644 --- a/HPL2/sources/graphics/RenderList.cpp +++ b/HPL2/sources/graphics/RenderList.cpp @@ -24,6 +24,7 @@ #include "graphics/Renderable.h" #include "graphics/Renderer.h" #include "graphics/SubMesh.h" +#include "scene/RenderableContainer.h" #include "scene/FogArea.h" #include "scene/Light.h" @@ -38,6 +39,50 @@ namespace hpl { + void cRenderList::UpdateRenderListWalkAllNodesTestFrustumAndVisibility( + cRenderList& renderList, + cFrustum& frustum, + iRenderableContainerNode& apNode, + std::span clipPlanes, + tRenderableFlag neededFlags) { + + apNode.UpdateBeforeUse(); + + // Get frustum collision, if previous was inside, then this is too! + eCollision frustumCollision = frustum.CollideNode(&apNode); + + // Do a visible check but always iterate the root node! + if (apNode.GetParent()) { + if (frustumCollision == eCollision_Outside) { + return; + } + if (iRenderableContainer::IsRenderableNodeIsVisible(apNode, clipPlanes) == false) { + return; + } + } + + // Iterate children + if (apNode.HasChildNodes()) { + for(auto& node: apNode.GetChildNodes()) { + UpdateRenderListWalkAllNodesTestFrustumAndVisibility(renderList, frustum, *node, clipPlanes, neededFlags); + } + } + + // Iterate objects + if (apNode.HasObjects()) { + for(auto& object: apNode.GetObjects()) { + if (iRenderable::IsObjectIsVisible(*object, neededFlags) == false) { + continue; + } + + if (frustumCollision == eCollision_Inside || object->CollidesWithFrustum(&frustum)) { + renderList.AddObject(object); + } + } + } + } + + static bool SortFunc_Z(iRenderable* apObjectA, iRenderable* apObjectB) { cMaterial* pMatA = apObjectA->GetMaterial(); cMaterial* pMatB = apObjectB->GetMaterial(); @@ -48,13 +93,6 @@ namespace hpl { return pMatA->GetAlphaMode() < pMatB->GetAlphaMode(); } - ////////////////////////// - // If alpha, sort by texture (we know alpha is same for both materials, so can just test one) - if (pMatA->GetAlphaMode() == eMaterialAlphaMode_Trans) { - if (pMatA->GetImage(eMaterialTexture_Diffuse) != pMatB->GetImage(eMaterialTexture_Diffuse)) { - return pMatA->GetImage(eMaterialTexture_Diffuse) < pMatB->GetImage(eMaterialTexture_Diffuse); - } - } ////////////////////////// // View space depth, no need to test further since Z should almost never be the same for two objects. @@ -65,14 +103,14 @@ namespace hpl { static bool SortFunc_Diffuse(iRenderable* apObjectA, iRenderable* apObjectB) { - cMaterial* pMatA = apObjectA->GetMaterial(); - cMaterial* pMatB = apObjectB->GetMaterial(); - - if (apObjectA->GetModelMatrixPtr() != apObjectB->GetModelMatrixPtr()) { - return apObjectA->GetModelMatrixPtr() < apObjectB->GetModelMatrixPtr(); - } - - return apObjectA < apObjectB; + // cMaterial* pMatA = apObjectA->GetMaterial(); + // cMaterial* pMatB = apObjectB->GetMaterial(); + // + // if (apObjectA->GetModelMatrixPtr() != apObjectB->GetModelMatrixPtr()) { + // return apObjectA->GetModelMatrixPtr() < apObjectB->GetModelMatrixPtr(); + // } + + return apObjectA->GetViewSpaceZ() > apObjectB->GetViewSpaceZ(); } static bool SortFunc_Translucent(iRenderable* apObjectA, iRenderable* apObjectB) { @@ -276,11 +314,6 @@ namespace hpl { } } - void cRenderList::Setup(float afFrameTime, cFrustum* apFrustum) { - m_frameTime = afFrameTime; - m_frustum = apFrustum; - } - void cRenderList::AddObject(iRenderable* apObject) { ASSERT(m_frustum && "call begin with frustum"); @@ -318,7 +351,6 @@ namespace hpl { apObject->SetModelMatrixPtr(apObject->GetModelMatrix(NULL)); } - //////////////////////////////////////// // Calculate the View Z value // For transparent and non decals! if (isValidMaterial && cMaterial::IsTranslucent(pMaterial->Descriptor().m_id) && pMaterial->Descriptor().m_id != MaterialID::Decal) { @@ -385,23 +417,6 @@ namespace hpl { } } - void cRenderList::Clear() { - // Use resize instead of clear, because that way capacity is preserved and allocation is never - // needed unless there is a need to increase the vector size. - - m_occlusionQueryObjects.resize(0); - m_transObjects.resize(0); - m_decalObjects.resize(0); - m_solidObjects.resize(0); - m_illumObjects.resize(0); - m_lights.resize(0); - m_fogAreas.resize(0); - - for (int i = 0; i < eRenderListType_LastEnum; ++i) { - m_sortedArrays[i].resize(0); - } - } - void cRenderList::PrintAllObjects() { Log("---------------------------------\n"); Log("------ RENDER LIST CONTENTS -----\n"); diff --git a/HPL2/sources/graphics/Renderable.cpp b/HPL2/sources/graphics/Renderable.cpp index b820d9a4f..723ff7153 100644 --- a/HPL2/sources/graphics/Renderable.cpp +++ b/HPL2/sources/graphics/Renderable.cpp @@ -26,6 +26,47 @@ namespace hpl { + cRect2l iRenderable::GetClipRectFromObject(iRenderable& object,float afPaddingPercent, cFrustum* apFrustum, const cVector2l& avScreenSize) { + cBoundingVolume* pBV = object.GetBoundingVolume(); + + const float halfFovTan = tan(apFrustum->GetFOV() * 0.5f); + cRect2l clipRect; + cMath::GetClipRectFromBV(clipRect, *pBV, apFrustum, avScreenSize, halfFovTan); + + // Add 20% padding on clip rect + int lXInc = (int)((float)clipRect.w * halfFovTan); + int lYInc = (int)((float)clipRect.h * halfFovTan); + + clipRect.x = cMath::Max(clipRect.x - lXInc, 0); + clipRect.y = cMath::Max(clipRect.y - lYInc, 0); + clipRect.w = cMath::Min(clipRect.w + lXInc * 2, avScreenSize.x - clipRect.x); + clipRect.h = cMath::Min(clipRect.h + lYInc * 2, avScreenSize.y - clipRect.y); + + return clipRect; + } + + bool iRenderable::IsObjectIsVisible(iRenderable& object, tRenderableFlag neededFlags, std::span clipPlanes) { + if (!object.IsVisible()) + { + return false; + } + + if ((object.GetRenderFlags() & neededFlags) != neededFlags) + { + return false; + } + + for (auto& plane : clipPlanes) + { + cBoundingVolume* pBV = object.GetBoundingVolume(); + if (cMath::CheckPlaneBVCollision(plane, *pBV) == eCollision_Outside) + { + return false; + } + } + return true; + } + iRenderable::iRenderable(const tString &asName) : iEntity3D(asName) { diff --git a/HPL2/sources/graphics/Renderer.cpp b/HPL2/sources/graphics/Renderer.cpp index 8af40b57c..97764b548 100644 --- a/HPL2/sources/graphics/Renderer.cpp +++ b/HPL2/sources/graphics/Renderer.cpp @@ -68,213 +68,8 @@ namespace hpl eParallaxQuality iRenderer::mParallaxQuality = eParallaxQuality_Low; bool iRenderer::mbParallaxEnabled = true; bool iRenderer::mbRefractionEnabled = true; - - //----------------------------------------------------------------------- - int iRenderer::mlRenderFrameCount = 0; - namespace rendering::detail - { - - cRect2l GetClipRectFromObject(iRenderable* apObject, float afPaddingPercent, cFrustum* apFrustum, const cVector2l& avScreenSize, float afHalfFovTan) { - cBoundingVolume* pBV = apObject->GetBoundingVolume(); - - cRect2l clipRect; - if (afHalfFovTan == 0) - afHalfFovTan = tan(apFrustum->GetFOV() * 0.5f); - cMath::GetClipRectFromBV(clipRect, *pBV, apFrustum, avScreenSize, afHalfFovTan); - - // Add 20% padding on clip rect - int lXInc = (int)((float)clipRect.w * afHalfFovTan); - int lYInc = (int)((float)clipRect.h * afHalfFovTan); - - clipRect.x = cMath::Max(clipRect.x - lXInc, 0); - clipRect.y = cMath::Max(clipRect.y - lYInc, 0); - clipRect.w = cMath::Min(clipRect.w + lXInc * 2, avScreenSize.x - clipRect.x); - clipRect.h = cMath::Min(clipRect.h + lYInc * 2, avScreenSize.y - clipRect.y); - - return clipRect; - } - - void WalkAndPrepareRenderList(iRenderableContainer* container,cFrustum* frustum, std::function handler, tRenderableFlag renderableFlag) { - - std::function walkRenderables; - walkRenderables = [&](iRenderableContainerNode* childNode) { - childNode->UpdateBeforeUse(); - for (auto& childNode : childNode->GetChildNodes()) { - childNode->UpdateBeforeUse(); - eCollision frustumCollision = frustum->CollideNode(childNode); - if (frustumCollision == eCollision_Outside) { - continue; - } - if (frustum->CheckAABBNearPlaneIntersection(childNode->GetMin(), childNode->GetMax())) { - cVector3f vViewSpacePos = cMath::MatrixMul(frustum->GetViewMatrix(), childNode->GetCenter()); - childNode->SetViewDistance(vViewSpacePos.z); - childNode->SetInsideView(true); - } else { - // Frustum origin is outside of node. Do intersection test. - cVector3f vIntersection; - cMath::CheckAABBLineIntersection( - childNode->GetMin(), childNode->GetMax(), frustum->GetOrigin(), childNode->GetCenter(), &vIntersection, NULL); - cVector3f vViewSpacePos = cMath::MatrixMul(frustum->GetViewMatrix(), vIntersection); - childNode->SetViewDistance(vViewSpacePos.z); - childNode->SetInsideView(false); - } - walkRenderables(childNode); - } - for (auto& pObject : childNode->GetObjects()) { - if (!rendering::detail::IsObjectIsVisible(pObject, renderableFlag, {})) { - continue; - } - handler(pObject); - } - }; - auto rootNode = container->GetRoot(); - rootNode->UpdateBeforeUse(); - rootNode->SetInsideView(true); - walkRenderables(rootNode); - } - - - void UpdateRenderListWalkAllNodesTestFrustumAndVisibility( - cRenderList* apRenderList, - cFrustum* frustum, - iRenderableContainerNode* apNode, - std::span clipPlanes, - tRenderableFlag neededFlags) { - apNode->UpdateBeforeUse(); - - /////////////////////////////////////// - // Get frustum collision, if previous was inside, then this is too! - eCollision frustumCollision = frustum->CollideNode(apNode); - - //////////////////////////////// - // Do a visible check but always iterate the root node! - if (apNode->GetParent()) { - if (frustumCollision == eCollision_Outside) { - return; - } - if (detail::IsRenderableNodeIsVisible(apNode, clipPlanes) == false) { - return; - } - } - - //////////////////////// - // Iterate children - if (apNode->HasChildNodes()) { - for(auto& node: apNode->GetChildNodes()) { - UpdateRenderListWalkAllNodesTestFrustumAndVisibility(apRenderList, frustum, node, clipPlanes, neededFlags); - } - } - - ///////////////////////////// - // Iterate objects - if (apNode->HasObjects()) { - for(auto& object: apNode->GetObjects()) { - if (detail::IsObjectIsVisible(object, neededFlags) == false) { - continue; - } - - if (frustumCollision == eCollision_Inside || object->CollidesWithFrustum(frustum)) { - apRenderList->AddObject(object); - } - } - } - } - - eShadowMapResolution GetShadowMapResolution(eShadowMapResolution aWanted, eShadowMapResolution aMax) - { - if (aMax == eShadowMapResolution_High) - { - return aWanted; - } - else if (aMax == eShadowMapResolution_Medium) - { - return aWanted == eShadowMapResolution_High ? eShadowMapResolution_Medium : aWanted; - } - return eShadowMapResolution_Low; - } - - - bool IsRenderableNodeIsVisible(iRenderableContainerNode* apNode, std::span clipPlanes) { - for(auto& plane: clipPlanes) - { - if (cMath::CheckPlaneAABBCollision(plane, apNode->GetMin(), apNode->GetMax(), apNode->GetCenter(), apNode->GetRadius()) == - eCollision_Outside) - { - return false; - } - } - return true; - } - - bool IsObjectVisible(iRenderable* apObject, tRenderableFlag alNeededFlags, std::span occlusionPlanes) - { - if (!apObject->IsVisible()) - { - return false; - } - - if ((apObject->GetRenderFlags() & alNeededFlags) != alNeededFlags) - { - return false; - } - - for (auto& plane : occlusionPlanes) - { - cBoundingVolume* pBV = apObject->GetBoundingVolume(); - if (cMath::CheckPlaneBVCollision(plane, *pBV) == eCollision_Outside) - { - return false; - } - } - return true; - } - - - void UpdateRenderListWalkAllNodesTestFrustumAndVisibility( - cRenderList* apRenderList, - cFrustum* frustum, - iRenderableContainer* apContainer, - std::span clipPlanes, - tRenderableFlag neededFlags) { - apContainer->UpdateBeforeRendering(); - - rendering::detail::UpdateRenderListWalkAllNodesTestFrustumAndVisibility( - apRenderList, - frustum, - apContainer->GetRoot(), - clipPlanes, - neededFlags); - } - - bool IsObjectIsVisible( - iRenderable* object, - tRenderableFlag neededFlags, - std::span clipPlanes) { - - if (object->IsVisible() == false) - return false; - - ///////////////////////////// - // Check flags - if ((object->GetRenderFlags() & neededFlags) != neededFlags) - return false; - - if (!clipPlanes.empty()) - { - cBoundingVolume* pBV = object->GetBoundingVolume(); - for(auto& planes: clipPlanes) - { - if (cMath::CheckPlaneBVCollision(planes, *pBV) == eCollision_Outside) { - return false; - } - } - } - return true; - } - } // namespace rendering::detail - bool cRendererNodeSortFunc::operator()(const iRenderableContainerNode* apNodeA, const iRenderableContainerNode* apNodeB) const { if (apNodeA->IsInsideView() != apNodeB->IsInsideView()) @@ -287,13 +82,11 @@ namespace hpl cRenderSettings::cRenderSettings(bool abIsReflection) { - //////////////////////// // Set up General Variables mbIsReflection = abIsReflection; mClearColor = cColor(0, 0); - //////////////////////// // Set up Render Variables // Change this later I assume: mlMinimumObjectsBeforeOcclusionTesting = 0; // 8;//8 should be good default, giving a good amount of colliders, or? Clarifiction: @@ -311,7 +104,6 @@ namespace hpl mbRenderWorldReflection = true; - //////////////////////// // Set up Shadow Variables mbRenderShadows = true; mfShadowMapBias = 4; // The constant bias @@ -365,9 +157,6 @@ namespace hpl bool abSendFrameBufferToPostEffects, bool abAtStartOfRendering) { - ////////////////////////////////////////// - // Set up variables - mfCurrentFrameTime = afFrameTime; mpCurrentSettings = apSettings; } diff --git a/HPL2/sources/graphics/RendererDeferred.cpp b/HPL2/sources/graphics/RendererDeferred.cpp index b414e075d..f736538f5 100644 --- a/HPL2/sources/graphics/RendererDeferred.cpp +++ b/HPL2/sources/graphics/RendererDeferred.cpp @@ -182,7 +182,7 @@ namespace hpl { if (frustumCollision == eCollision_Outside) { return; } - if (rendering::detail::IsRenderableNodeIsVisible(apNode, clipPlanes) == false) { + if (iRenderableContainer::IsRenderableNodeIsVisible(*apNode, clipPlanes) == false) { return; } } @@ -197,7 +197,7 @@ namespace hpl { // Iterate objects for (auto& object : apNode->GetObjects()) { // Check so visible and shadow caster - if (rendering::detail::IsObjectIsVisible(object, eRenderableFlag_ShadowCaster, clipPlanes) == false || + if (iRenderable::IsObjectIsVisible(*object, eRenderableFlag_ShadowCaster, clipPlanes) == false || object->GetMaterial() == NULL || cMaterial::IsTranslucent(object->GetMaterial()->Descriptor().m_id)) { continue; } @@ -661,192 +661,8 @@ namespace hpl { }); } - // prepass - m_prePassPool.Load(forgeRenderer->Rend(), [&](CmdPool** pool) { - CmdPoolDesc cmdPoolDesc = {}; - cmdPoolDesc.pQueue = forgeRenderer->GetGraphicsQueue(); - cmdPoolDesc.mTransient = true; - addCmdPool(forgeRenderer->Rend(), &cmdPoolDesc, pool); - return true; - }); - m_prePassCmd.Load(forgeRenderer->Rend(), [&](Cmd** cmd) { - CmdDesc cmdDesc = {}; - cmdDesc.pPool = m_prePassPool.m_handle; - addCmd(forgeRenderer->Rend(), &cmdDesc, cmd); - return true; - }); - m_prePassFence.Load(forgeRenderer->Rend(), [&](Fence** fence) { - addFence(forgeRenderer->Rend(), fence); - return true; - }); - // hi-z { - m_ShaderHIZGenerate.Load(forgeRenderer->Rend(), [&](Shader** shader) { - ShaderLoadDesc loadDesc = {}; - loadDesc.mStages[0].pFileName = "generate_hi_z.comp"; - addShader(forgeRenderer->Rend(), &loadDesc, shader); - return true; - }); - - m_shaderTestOcclusion.Load(forgeRenderer->Rend(), [&](Shader** shader) { - ShaderLoadDesc loadDesc = {}; - loadDesc.mStages[0].pFileName = "test_AABB_hi_z.comp"; - addShader(forgeRenderer->Rend(), &loadDesc, shader); - return true; - }); - - m_copyDepthShader.Load(forgeRenderer->Rend(), [&](Shader** shader) { - ShaderLoadDesc loadDesc = {}; - loadDesc.mStages[0].pFileName = "fullscreen.vert"; - loadDesc.mStages[1].pFileName = "copy_hi_z.frag"; - addShader(forgeRenderer->Rend(), &loadDesc, shader); - return true; - }); - - m_hiZOcclusionUniformBuffer.Load([&](Buffer** buf) { - BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; - desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mDesc.mSize = sizeof(cRendererDeferred::UniformPropBlock); - desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; - desc.pData = nullptr; - desc.ppBuffer = buf; - addResource(&desc, nullptr); - return true; - }); - m_hiZBoundBoxBuffer.Load([&](Buffer** buf) { - BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER; - desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mDesc.mElementCount = cRendererDeferred::MaxObjectTest; - desc.mDesc.mStructStride = sizeof(float4); - desc.mDesc.mSize = desc.mDesc.mStructStride * desc.mDesc.mElementCount; - desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; - desc.pData = nullptr; - desc.ppBuffer = buf; - addResource(&desc, nullptr); - return true; - }); - m_occlusionTestBuffer.Load([&](Buffer** buf) { - BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_RW_BUFFER; - desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_TO_CPU; - desc.mDesc.mElementCount = cRendererDeferred::MaxObjectTest; - desc.mDesc.mStructStride = sizeof(uint32_t); - desc.mDesc.mSize = sizeof(uint32_t) * cRendererDeferred::MaxObjectTest; - desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; - desc.pData = nullptr; - desc.ppBuffer = buf; - addResource(&desc, nullptr); - return true; - }); - m_rootSignatureHIZOcclusion.Load(forgeRenderer->Rend(), [&](RootSignature** sig) { - std::array shaders = { m_ShaderHIZGenerate.m_handle, m_shaderTestOcclusion.m_handle }; - RootSignatureDesc rootSignatureDesc = {}; - const char* pStaticSamplers[] = { "depthSampler" }; - rootSignatureDesc.mStaticSamplerCount = 1; - rootSignatureDesc.ppStaticSamplers = &m_bilinearSampler.m_handle; - rootSignatureDesc.ppStaticSamplerNames = pStaticSamplers; - rootSignatureDesc.ppShaders = shaders.data(); - rootSignatureDesc.mShaderCount = shaders.size(); - addRootSignature(forgeRenderer->Rend(), &rootSignatureDesc, sig); - return true; - }); - m_descriptorSetHIZGenerate.Load(forgeRenderer->Rend(), [&](DescriptorSet** set) { - DescriptorSetDesc setDesc = { m_rootSignatureHIZOcclusion.m_handle, - DESCRIPTOR_UPDATE_FREQ_PER_FRAME, - cRendererDeferred::MaxHiZMipLevels }; - addDescriptorSet(forgeRenderer->Rend(), &setDesc, set); - return true; - }); - m_rootSignatureCopyDepth.Load(forgeRenderer->Rend(), [&](RootSignature** signature) { - std::array shaders = { m_copyDepthShader.m_handle }; - RootSignatureDesc rootSignatureDesc = {}; - const char* pStaticSamplers[] = { "depthSampler" }; - - rootSignatureDesc.ppShaders = shaders.data(); - rootSignatureDesc.mShaderCount = shaders.size(); - rootSignatureDesc.mStaticSamplerCount = 1; - rootSignatureDesc.ppStaticSamplers = &m_samplerPointClampToBorder.m_handle; - rootSignatureDesc.ppStaticSamplerNames = pStaticSamplers; - addRootSignature(forgeRenderer->Rend(), &rootSignatureDesc, signature); - return true; - }); - - m_descriptorCopyDepth.Load(forgeRenderer->Rend(), [&](DescriptorSet** handle) { - DescriptorSetDesc setDesc = { m_rootSignatureCopyDepth.m_handle, DESCRIPTOR_UPDATE_FREQ_PER_FRAME, 1 }; - addDescriptorSet(forgeRenderer->Rend(), &setDesc, handle); - return true; - }); - m_pipelineHIZGenerate.Load(forgeRenderer->Rend(), [&](Pipeline** pipeline) { - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_COMPUTE; - ComputePipelineDesc& computePipelineDesc = pipelineDesc.mComputeDesc; - computePipelineDesc.pShaderProgram = m_ShaderHIZGenerate.m_handle; - computePipelineDesc.pRootSignature = m_rootSignatureHIZOcclusion.m_handle; - addPipeline(forgeRenderer->Rend(), &pipelineDesc, pipeline); - return true; - }); - - m_pipelineAABBOcclusionTest.Load(forgeRenderer->Rend(), [&](Pipeline** handle) { - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_COMPUTE; - ComputePipelineDesc& computePipelineDesc = pipelineDesc.mComputeDesc; - computePipelineDesc.pShaderProgram = m_shaderTestOcclusion.m_handle; - computePipelineDesc.pRootSignature = m_rootSignatureHIZOcclusion.m_handle; - addPipeline(forgeRenderer->Rend(), &pipelineDesc, handle); - return true; - }); - - m_descriptorAABBOcclusionTest.Load(forgeRenderer->Rend(), [&](DescriptorSet** handle) { - DescriptorSetDesc setDesc = { m_rootSignatureHIZOcclusion.m_handle, DESCRIPTOR_UPDATE_FREQ_PER_FRAME, 1 }; - addDescriptorSet(forgeRenderer->Rend(), &setDesc, handle); - return true; - }); - - m_pipelineCopyDepth.Load(forgeRenderer->Rend(), [&](Pipeline** handle) { - RasterizerStateDesc rasterStateNoneDesc = {}; - rasterStateNoneDesc.mCullMode = CULL_MODE_NONE; - - DepthStateDesc depthStateDisabledDesc = {}; - depthStateDisabledDesc.mDepthWrite = false; - depthStateDisabledDesc.mDepthTest = false; - - std::array imageTargets = { TinyImageFormat_R32_SFLOAT }; - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_GRAPHICS; - GraphicsPipelineDesc& graphicsPipelineDesc = pipelineDesc.mGraphicsDesc; - graphicsPipelineDesc.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; - graphicsPipelineDesc.mRenderTargetCount = imageTargets.size(); - graphicsPipelineDesc.pColorFormats = imageTargets.data(); - graphicsPipelineDesc.pShaderProgram = m_copyDepthShader.m_handle; - graphicsPipelineDesc.pRootSignature = m_rootSignatureCopyDepth.m_handle; - graphicsPipelineDesc.mRenderTargetCount = 1; - graphicsPipelineDesc.mDepthStencilFormat = TinyImageFormat_UNDEFINED; - graphicsPipelineDesc.pVertexLayout = NULL; - graphicsPipelineDesc.mSampleCount = SAMPLE_COUNT_1; - graphicsPipelineDesc.pRasterizerState = &rasterStateNoneDesc; - graphicsPipelineDesc.pDepthState = &depthStateDisabledDesc; - graphicsPipelineDesc.pBlendState = NULL; - addPipeline(forgeRenderer->Rend(), &pipelineDesc, handle); - return true; - }); - } - { - m_occlusionReadBackBuffer.Load([&](Buffer** buf) { - BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_RW_BUFFER; - desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_TO_CPU; - desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; - desc.mDesc.mElementCount = cRendererDeferred::MaxObjectTest; - desc.mDesc.mStructStride = sizeof(uint64_t); - desc.mDesc.mSize = desc.mDesc.mStructStride * desc.mDesc.mElementCount; - desc.pData = nullptr; - desc.ppBuffer = buf; - addResource(&desc, nullptr); - return true; - }); m_shaderOcclusionQuery.Load(forgeRenderer->Rend(), [&](Shader** handle) { ShaderLoadDesc loadDesc = {}; @@ -879,10 +695,8 @@ namespace hpl { { VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 1; - vertexLayout.mBindings[0].mStride = sizeof(float3); -#endif + vertexLayout.mBindings[0].mStride = sizeof(float4); vertexLayout.mAttribCount = 1; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -904,7 +718,6 @@ namespace hpl { graphicsPipelineDesc.pShaderProgram = m_shaderOcclusionQuery.m_handle; graphicsPipelineDesc.pRootSignature = m_rootSignatureOcclusuion.m_handle; graphicsPipelineDesc.mDepthStencilFormat = DepthBufferFormat; - graphicsPipelineDesc.pVertexLayout = NULL; graphicsPipelineDesc.mSampleCount = SAMPLE_COUNT_1; graphicsPipelineDesc.mDepthStencilFormat = DepthBufferFormat; graphicsPipelineDesc.pRasterizerState = &rasterStateNoneDesc; @@ -923,13 +736,6 @@ namespace hpl { return true; }); } - m_occlusionQuery.Load(forgeRenderer->Rend(), [&](QueryPool** pool) { - QueryPoolDesc queryPoolDesc = {}; - queryPoolDesc.mType = QUERY_TYPE_OCCLUSION; - queryPoolDesc.mQueryCount = MaxQueryPoolSize; - addQueryPool(forgeRenderer->Rend(), &queryPoolDesc, pool); - return true; - }); } // -------------- Fog ---------------------------- { @@ -973,11 +779,8 @@ namespace hpl { }); VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 1; - vertexLayout.mBindings[0].mStride = sizeof(float3); -#endif - + vertexLayout.mBindings[0].mStride = sizeof(float4); vertexLayout.mAttribCount = 1; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -999,11 +802,7 @@ namespace hpl { blendStateDesc.mSrcAlphaFactors[0] = BC_SRC_ALPHA; blendStateDesc.mDstAlphaFactors[0] = BC_ONE_MINUS_SRC_ALPHA; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; -#else blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; -#endif blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -1050,11 +849,7 @@ namespace hpl { blendStateDesc.mSrcAlphaFactors[0] = BC_SRC_ALPHA; blendStateDesc.mDstAlphaFactors[0] = BC_ONE_MINUS_SRC_ALPHA; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; -#else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; -#endif + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -1068,7 +863,7 @@ namespace hpl { graphicsPipelineDesc.pShaderProgram = m_fogPass.m_fullScreenShader.m_handle; graphicsPipelineDesc.pRootSignature = m_fogPass.m_fogRootSignature.m_handle; graphicsPipelineDesc.mRenderTargetCount = 1; - graphicsPipelineDesc.mDepthStencilFormat = TinyImageFormat_UNDEFINED; + graphicsPipelineDesc.mDepthStencilFormat = DepthBufferFormat; graphicsPipelineDesc.pVertexLayout = NULL; graphicsPipelineDesc.pRasterizerState = &rasterStateNoneDesc; graphicsPipelineDesc.pDepthState = &depthStateDisabledDesc; @@ -1263,13 +1058,11 @@ namespace hpl { // diffuse material pass { VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 4; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); vertexLayout.mBindings[2].mStride = sizeof(float3); vertexLayout.mBindings[3].mStride = sizeof(float3); -#endif vertexLayout.mAttribCount = 4; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -1346,12 +1139,10 @@ namespace hpl { // decal material pass { VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 3; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); vertexLayout.mBindings[2].mStride = sizeof(float4); -#endif vertexLayout.mAttribCount = 3; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -1405,12 +1196,8 @@ namespace hpl { blendStateDesc.mSrcAlphaFactors[0] = hpl::HPL2BlendTable[blendMode].srcAlpha; blendStateDesc.mDstAlphaFactors[0] = hpl::HPL2BlendTable[blendMode].dstAlpha; blendStateDesc.mBlendAlphaModes[0] = hpl::HPL2BlendTable[blendMode].alphaMode; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; -#else - blendStateDesc.mColorWriteMasks[0] = - ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; -#endif + + blendStateDesc.mColorWriteMasks[0] =ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; pipelineSettings.pBlendState = &blendStateDesc; rasterizerStateDesc.mFrontFace = FRONT_FACE_CCW; @@ -1431,13 +1218,11 @@ namespace hpl { VertexLayout vertexLayout = {}; vertexLayout.mAttribCount = 4; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 4; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); vertexLayout.mBindings[2].mStride = sizeof(float3); vertexLayout.mBindings[3].mStride = sizeof(float3); -#endif vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; vertexLayout.mAttribs[0].mBinding = 0; @@ -1652,11 +1437,9 @@ namespace hpl { { // layout and pipeline for sphere draw VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 2; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); -#endif vertexLayout.mAttribCount = 2; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -1675,11 +1458,7 @@ namespace hpl { rasterizerStateDesc.mFrontFace = FRONT_FACE_CCW; BlendStateDesc blendStateDesc{}; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = ALL; -#else blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; -#endif blendStateDesc.mSrcFactors[0] = BC_ONE; blendStateDesc.mDstFactors[0] = BC_ONE; blendStateDesc.mBlendModes[0] = BM_ADD; @@ -1726,12 +1505,10 @@ namespace hpl { // translucency pass { VertexLayout particleVertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY particleVertexLayout.mBindingCount = 3; particleVertexLayout.mBindings[0].mStride = sizeof(float3); particleVertexLayout.mBindings[1].mStride = sizeof(float2); particleVertexLayout.mBindings[2].mStride = sizeof(float4); -#endif particleVertexLayout.mAttribCount = 3; particleVertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; @@ -1754,14 +1531,12 @@ namespace hpl { VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 5; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); vertexLayout.mBindings[2].mStride = sizeof(float3); vertexLayout.mBindings[3].mStride = sizeof(float3); - vertexLayout.mBindings[4].mStride = sizeof(float3); -#endif + vertexLayout.mBindings[4].mStride = sizeof(float4); vertexLayout.mAttribCount = 5; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -1810,11 +1585,7 @@ namespace hpl { pipelineBlendGroup[key.m_id].Load(forgeRenderer->Rend(), [&](Pipeline** pipeline) { BlendStateDesc blendStateDesc{}; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = ALL; -#else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; -#endif + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -1866,11 +1637,7 @@ namespace hpl { pipelineBlendGroup[key.m_id].Load(forgeRenderer->Rend(), [&](Pipeline** pipeline) { BlendStateDesc blendStateDesc{}; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; -#else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; -#endif + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -1918,11 +1685,7 @@ namespace hpl { key.m_id = pipelineKey; pipelineBlendGroup[key.m_id].Load(forgeRenderer->Rend(), [&](Pipeline** pipeline) { BlendStateDesc blendStateDesc{}; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = ALL; -#else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; -#endif + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -1973,11 +1736,8 @@ namespace hpl { key.m_id = pipelineKey; m_materialTranslucencyPass.m_refractionPipeline[key.m_id].Load(forgeRenderer->Rend(), [&](Pipeline** pipeline) { BlendStateDesc blendStateDesc{}; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = ALL; -#else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; -#endif + + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -2165,10 +1925,8 @@ namespace hpl { }); VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 1; - vertexLayout.mBindings[0].mStride = sizeof(float3); -#endif + vertexLayout.mBindings[0].mStride = sizeof(float4); vertexLayout.mAttribCount = 1; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -2222,11 +1980,7 @@ namespace hpl { blendStateDesc.mSrcAlphaFactors[0] = BC_ONE; blendStateDesc.mDstAlphaFactors[0] = BC_ONE; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; -#else blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; -#endif blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -2460,7 +2214,7 @@ namespace hpl { uniformFrameData->afT = GetTimeCount(); const auto fogColor = apWorld->GetFogColor(); uniformFrameData->fogColor = float4(fogColor.r, fogColor.g, fogColor.b, fogColor.a); - endUpdateResource(&updatePerFrameConstantsDesc, NULL); + endUpdateResource(&updatePerFrameConstantsDesc); m_materialSet.m_frameIndex = (m_materialSet.m_frameIndex + 1) % MaxViewportFrameDescriptors; return index; @@ -2475,13 +2229,20 @@ namespace hpl { RenderTarget* outputBuffer, AdditionalIlluminationPassOptions options) { uint32_t materialObjectIndex = getDescriptorIndexFromName(m_materialRootSignature.m_handle, "materialRootConstant"); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - std::array targets = { - outputBuffer, - }; - cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, nullptr, nullptr, -1, -1); + //LoadActionsDesc loadActions = {}; + //loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + //loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + //std::array targets = { + // outputBuffer, + //}; + //cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, nullptr, nullptr, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mDepthStencil = { .pDepthStencil =depthBuffer, .mLoadAction = LOAD_ACTION_LOAD }; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = BindRenderTargetDesc{outputBuffer, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(cmd, &bindRenderTargets); + cmdSetViewport(cmd, 0.0f, 0.0f, outputBuffer->mWidth, outputBuffer->mHeight, 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, outputBuffer->mWidth, outputBuffer->mHeight); cmdBindPipeline(cmd, options.m_invert ? m_solidIlluminationPipelineCW.m_handle : m_solidIlluminationPipelineCCW.m_handle); @@ -2494,7 +2255,7 @@ namespace hpl { eVertexBufferElement_Position, eVertexBufferElement_Texture0, }; - DrawPacket drawPacket = illuminationItem->ResolveDrawPacket(frame, targets); + DrawPacket drawPacket = illuminationItem->ResolveDrawPacket(frame); if (pMaterial == nullptr || drawPacket.m_type == DrawPacket::Unknown) { continue; } @@ -2503,7 +2264,7 @@ namespace hpl { uint32_t instance = cmdBindMaterialAndObject(cmd, frame, pMaterial, illuminationItem); materialConst.objectId = instance; materialConst.m_sceneAlpha = illuminationItem->GetIlluminationAmount(); - DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &drawPacket); + DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &drawPacket, targets); cmdBindPushConstants(cmd, m_materialRootSignature.m_handle, materialObjectIndex, &materialConst); cmdDrawIndexed(cmd, drawPacket.numberOfIndecies(), 0, 0); } @@ -2611,7 +2372,7 @@ namespace hpl { if (deferredLight.m_insideNearPlane) { castShadow = true; - shadowMapResolution = rendering::detail::GetShadowMapResolution( + shadowMapResolution = hpl::GetShadowMapResolution( light->GetShadowMapResolution(), mpCurrentSettings->mMaxShadowMapResolution); } else { cVector3f vIntersection = pLightSpot->GetFrustum()->GetOrigin(); @@ -2621,7 +2382,7 @@ namespace hpl { float fDistToLight = cMath::Vector3Dist(apFrustum->GetOrigin(), vIntersection); castShadow = true; - shadowMapResolution = rendering::detail::GetShadowMapResolution( + shadowMapResolution = hpl::GetShadowMapResolution( light->GetShadowMapResolution(), mpCurrentSettings->mMaxShadowMapResolution); /////////////////////// @@ -2704,7 +2465,7 @@ namespace hpl { beginCmd(shadowMapData->m_cmd.m_handle); { - cmdBindRenderTargets(shadowMapData->m_cmd.m_handle, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(shadowMapData->m_cmd.m_handle, NULL); std::array rtBarriers = { RenderTargetBarrier{ shadowMapData->m_target.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_DEPTH_WRITE }, @@ -2713,20 +2474,10 @@ namespace hpl { shadowMapData->m_cmd.m_handle, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionDepth = LOAD_ACTION_CLEAR; - loadActions.mLoadActionStencil = LOAD_ACTION_DONTCARE; - loadActions.mClearDepth = { .depth = 1.0f, .stencil = 0 }; - cmdBindRenderTargets( - shadowMapData->m_cmd.m_handle, - 0, - NULL, - shadowMapData->m_target.m_handle, - &loadActions, - NULL, - NULL, - -1, - -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mDepthStencil = { .pDepthStencil = shadowMapData->m_target.m_handle, .mLoadAction = LOAD_ACTION_CLEAR }; + cmdBindRenderTargets(shadowMapData->m_cmd.m_handle, &bindRenderTargets); + cmdSetViewport( shadowMapData->m_cmd.m_handle, 0.0f, @@ -2763,14 +2514,14 @@ namespace hpl { eVertexBufferElement_Texture0, eVertexBufferElement_Normal, eVertexBufferElement_Texture1Tangent }; - DrawPacket packet = pObject->ResolveDrawPacket(frame, targets); + DrawPacket packet = pObject->ResolveDrawPacket(frame); if (packet.m_type == DrawPacket::Unknown || descriptor.m_id == MaterialID::Unknown) { return; } MaterialRootConstant materialConst = {}; uint32_t instance = cmdBindMaterialAndObject(shadowMapData->m_cmd.m_handle, frame, pMaterial, pObject); materialConst.objectId = instance; - DrawPacket::cmdBindBuffers(shadowMapData->m_cmd.m_handle, frame.m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(shadowMapData->m_cmd.m_handle, frame.m_resourcePool, &packet, targets); cmdBindPushConstants( shadowMapData->m_cmd.m_handle, m_materialRootSignature.m_handle, @@ -2779,7 +2530,7 @@ namespace hpl { cmdDrawIndexed(shadowMapData->m_cmd.m_handle, packet.numberOfIndecies(), 0, 0); } { - cmdBindRenderTargets(shadowMapData->m_cmd.m_handle, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(shadowMapData->m_cmd.m_handle, NULL); std::array rtBarriers = { RenderTargetBarrier{ shadowMapData->m_target.m_handle, RESOURCE_STATE_DEPTH_WRITE, RESOURCE_STATE_SHADER_RESOURCE }, @@ -2947,7 +2698,7 @@ namespace hpl { m_lightIndex * sizeof(UniformLightData) }; beginUpdateResource(&updateDesc); memcpy(updateDesc.pMappedData, &uniformObjectData, sizeof(UniformLightData)); - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); updateDescriptorSet( frame.m_renderer->Rend(), m_lightIndex, m_lightPerLightSet[frame.m_frameIndex].m_handle, paramCount, params); @@ -2957,18 +2708,28 @@ namespace hpl { return index; }; { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - loadActions.mLoadActionStencil = LOAD_ACTION_CLEAR; - loadActions.mClearColorValues[0] = ClearValue{ .r = options.m_clearColor.getX(), + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; + // loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + // loadActions.mLoadActionStencil = LOAD_ACTION_CLEAR; + // loadActions.mClearColorValues[0] = ClearValue{ .r = options.m_clearColor.getX(), + // .g = options.m_clearColor.getY(), + // .b = options.m_clearColor.getZ(), + // .a = options.m_clearColor.getW() }; + // std::array targets = { + // outputBuffer, + // }; + // cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, nullptr, nullptr, -1, -1); + + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mDepthStencil = { .pDepthStencil = depthBuffer, .mLoadAction = LOAD_ACTION_LOAD, .mLoadActionStencil = LOAD_ACTION_CLEAR}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = BindRenderTargetDesc{.pRenderTarget = outputBuffer, .mLoadAction = LOAD_ACTION_CLEAR, .mClearValue = { .r = options.m_clearColor.getX(), .g = options.m_clearColor.getY(), .b = options.m_clearColor.getZ(), - .a = options.m_clearColor.getW() }; - std::array targets = { - outputBuffer, - }; - cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, nullptr, nullptr, -1, -1); + .a = options.m_clearColor.getW() }, .mOverrideClearValue = true, }; + cmdBindRenderTargets(cmd, &bindRenderTargets); } cmdSetViewport(cmd, 0.0f, 0.0f, outputBuffer->mWidth, outputBuffer->mHeight, 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, outputBuffer->mWidth, outputBuffer->mHeight); @@ -3011,8 +2772,8 @@ namespace hpl { auto lightShape = GetLightShape(light->m_light, eDeferredShapeQuality_High); ASSERT(lightShape && "Light shape not found"); DrawPacket packet = - static_cast(lightShape)->resolveGeometryBinding(frame.m_currentFrame, elements); - DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet); + static_cast(lightShape)->resolveGeometryBinding(frame.m_currentFrame); + DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet, elements); cmdBindPipeline(cmd, options.m_invert ? m_lightStencilPipelineCW.m_handle : m_lightStencilPipelineCCW.m_handle); uint32_t instance = cmdBindLightDescriptor(light); // bind light descriptor light uniforms @@ -3054,14 +2815,9 @@ namespace hpl { cmdBindPushConstants(cmd, m_lightPassRootSignature.m_handle, lightRootConstantIndex, &instance); cmdDrawIndexed(cmd, packet.numberOfIndecies(), 0, 0); { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - loadActions.mLoadActionStencil = LOAD_ACTION_CLEAR; - std::array targets = { - outputBuffer, - }; - cmdBindRenderTargets(cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + + cmdBindRenderTargets(cmd, NULL); + { std::array rtBarriers = { RenderTargetBarrier{ depthBuffer, RESOURCE_STATE_DEPTH_WRITE, RESOURCE_STATE_PRESENT }, @@ -3074,8 +2830,18 @@ namespace hpl { }; cmdResourceBarrier(cmd, 0, NULL, 0, nullptr, rtBarriers.size(), rtBarriers.data()); } - - cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, nullptr, nullptr, -1, -1); + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + // loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + // loadActions.mLoadActionStencil = LOAD_ACTION_CLEAR; + // std::array targets = { + // outputBuffer, + // }; + BindRenderTargetsDesc bindRenderTargets = {0}; + bindRenderTargets.mDepthStencil = { .pDepthStencil = depthBuffer, .mLoadAction = LOAD_ACTION_LOAD, .mLoadActionStencil = LOAD_ACTION_CLEAR}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = BindRenderTargetDesc{outputBuffer, LOAD_ACTION_LOAD}; + cmdBindRenderTargets(cmd, &bindRenderTargets); } } cmdEndDebugMarker(cmd); @@ -3115,10 +2881,10 @@ namespace hpl { std::array targets = { eVertexBufferElement_Position }; auto lightShape = GetLightShape(light->m_light, eDeferredShapeQuality_High); ASSERT(lightShape && "Light shape not found"); - DrawPacket packet = static_cast(lightShape)->resolveGeometryBinding(frame.m_currentFrame, targets); + DrawPacket packet = static_cast(lightShape)->resolveGeometryBinding(frame.m_currentFrame); uint32_t instance = cmdBindLightDescriptor(light); - DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet, targets); cmdBindPushConstants(cmd, m_lightPassRootSignature.m_handle, lightRootConstantIndex, &instance); cmdDrawIndexed(cmd, packet.numberOfIndecies(), 0, 0); } @@ -3141,15 +2907,26 @@ namespace hpl { uint32_t materialObjectIndex = getDescriptorIndexFromName(m_materialRootSignature.m_handle, "materialRootConstant"); { cmdBeginDebugMarker(cmd, 0, 1, 0, "Build GBuffer"); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; - loadActions.mLoadActionsColor[1] = LOAD_ACTION_CLEAR; - loadActions.mLoadActionsColor[2] = LOAD_ACTION_CLEAR; - loadActions.mLoadActionsColor[3] = LOAD_ACTION_CLEAR; - loadActions.mClearColorValues[0] = { .r = 0.0f, .g = 0.0f, .b = 0.0f, .a = 0.0f }; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - std::array targets = { colorBuffer, normalBuffer, positionBuffer, specularBuffer }; - cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, NULL, NULL, -1, -1); + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; + // loadActions.mLoadActionsColor[1] = LOAD_ACTION_CLEAR; + // loadActions.mLoadActionsColor[2] = LOAD_ACTION_CLEAR; + // loadActions.mLoadActionsColor[3] = LOAD_ACTION_CLEAR; + // loadActions.mClearColorValues[0] = { .r = 0.0f, .g = 0.0f, .b = 0.0f, .a = 0.0f }; + // loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + // std::array targets = { colorBuffer, normalBuffer, positionBuffer, specularBuffer }; + // cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, NULL, NULL, -1, -1); + + + BindRenderTargetsDesc bindRenderTargets = {0}; + bindRenderTargets.mDepthStencil = { .pDepthStencil = depthBuffer, .mLoadAction = LOAD_ACTION_LOAD }; + bindRenderTargets.mRenderTargetCount = 4; + bindRenderTargets.mRenderTargets[0] = BindRenderTargetDesc{colorBuffer, LOAD_ACTION_CLEAR}; + bindRenderTargets.mRenderTargets[1] = BindRenderTargetDesc{normalBuffer, LOAD_ACTION_CLEAR}; + bindRenderTargets.mRenderTargets[2] = BindRenderTargetDesc{positionBuffer, LOAD_ACTION_CLEAR}; + bindRenderTargets.mRenderTargets[3] = BindRenderTargetDesc{specularBuffer, LOAD_ACTION_CLEAR}; + cmdBindRenderTargets(cmd, &bindRenderTargets); + cmdSetViewport(cmd, 0.0f, 0.0f, colorBuffer->mWidth, colorBuffer->mHeight, 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, colorBuffer->mWidth, colorBuffer->mHeight); cmdBindPipeline( @@ -3160,13 +2937,12 @@ namespace hpl { cmdBindDescriptorSet(cmd, frameDescriptorIndex, m_materialSet.m_frameSet[frame.m_frameIndex].m_handle); for (auto& diffuseItem : renderList.GetRenderableItems(eRenderListType_Diffuse)) { - cMaterial* pMaterial = diffuseItem->GetMaterial(); std::array targets = { eVertexBufferElement_Position, eVertexBufferElement_Texture0, eVertexBufferElement_Normal, eVertexBufferElement_Texture1Tangent }; - DrawPacket packet = diffuseItem->ResolveDrawPacket(frame, targets); + DrawPacket packet = diffuseItem->ResolveDrawPacket(frame); if (pMaterial == nullptr || packet.m_type == DrawPacket::Unknown) { continue; } @@ -3175,7 +2951,7 @@ namespace hpl { MaterialRootConstant materialConst = {}; uint32_t instance = cmdBindMaterialAndObject(cmd, frame, pMaterial, diffuseItem); materialConst.objectId = instance; - DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet, targets); cmdBindPushConstants(cmd, m_materialRootSignature.m_handle, materialObjectIndex, &materialConst); cmdDrawIndexed(cmd, packet.numberOfIndecies(), 0, 0); } @@ -3187,13 +2963,20 @@ namespace hpl { // ------------------------------------------------------------------------------------ { cmdBeginDebugMarker(cmd, 0, 1, 0, "Build Decal"); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - std::array targets = { - colorBuffer, - }; - cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, NULL, NULL, -1, -1); + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + // loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + // std::array targets = { + // colorBuffer, + // }; + // cmdBindRenderTargets(cmd, targets.size(), targets.data(), depthBuffer, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mDepthStencil = { .pDepthStencil = depthBuffer, .mLoadAction = LOAD_ACTION_LOAD }; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = BindRenderTargetDesc{colorBuffer, LOAD_ACTION_LOAD}; + cmdBindRenderTargets(cmd, &bindRenderTargets); + cmdSetViewport(cmd, 0.0f, 0.0f, colorBuffer->mWidth, colorBuffer->mHeight, 0.0f, 1.0f); cmdSetScissor(cmd, 0, 0, colorBuffer->mWidth, colorBuffer->mHeight); @@ -3201,7 +2984,7 @@ namespace hpl { for (auto& decalItem : m_rendererList.GetRenderableItems(eRenderListType_Decal)) { cMaterial* pMaterial = decalItem->GetMaterial(); std::array targets = { eVertexBufferElement_Position, eVertexBufferElement_Texture0, eVertexBufferElement_Color0 }; - DrawPacket packet = decalItem->ResolveDrawPacket(frame, targets); + DrawPacket packet = decalItem->ResolveDrawPacket(frame); if (pMaterial == nullptr || packet.m_type == DrawPacket::Unknown) { continue; } @@ -3215,241 +2998,97 @@ namespace hpl { MaterialRootConstant materialConst = {}; uint32_t instance = cmdBindMaterialAndObject(cmd, frame, pMaterial, decalItem); materialConst.objectId = instance; - DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet, targets); cmdBindPushConstants(cmd, m_materialRootSignature.m_handle, materialObjectIndex, &materialConst); cmdDrawIndexed(cmd, packet.numberOfIndecies(), 0, 0); } cmdEndDebugMarker(cmd); } } - - void cRendererDeferred::cmdPreAndPostZ( + void cRendererDeferred::cmdPreZ( Cmd* cmd, cWorld* apWorld, - std::set& prePassRenderables, const ForgeRenderer::Frame& frame, cRenderList& renderList, float frameTime, RenderTarget* depthBuffer, - RenderTarget* hiZBuffer, cFrustum* apFrustum, uint32_t frameDescriptorIndex, cMatrixf viewMat, cMatrixf projectionMat, AdditionalZPassOptions options) { - ASSERT(depthBuffer && "Depth buffer not created"); - ASSERT(hiZBuffer && "Depth buffer not created"); - - FenceStatus fenceStatus; - getFenceStatus(frame.m_renderer->Rend(), m_prePassFence.m_handle, &fenceStatus); - if (fenceStatus == FENCE_STATUS_INCOMPLETE) { - waitForFences(frame.m_renderer->Rend(), 1, &m_prePassFence.m_handle); - } - resetCmdPool(frame.m_renderer->Rend(), m_prePassPool.m_handle); - - uint32_t materialObjectIndex = getDescriptorIndexFromName(m_materialRootSignature.m_handle, "materialRootConstant"); + cmdBeginDebugMarker(cmd, 0, 1, 0, "Pre Z"); - struct RenderableContainer { - iRenderableContainer* m_continer; - eWorldContainerType m_type; - }; - std::array worldContainers = { - RenderableContainer{ apWorld->GetRenderableContainer(eWorldContainerType_Dynamic), eWorldContainerType_Dynamic }, - RenderableContainer{ apWorld->GetRenderableContainer(eWorldContainerType_Static), eWorldContainerType_Static } - }; + BindRenderTargetsDesc bindRenderTargets = { 0 }; + bindRenderTargets.mDepthStencil = { .pDepthStencil = depthBuffer, + .mLoadAction = LOAD_ACTION_CLEAR, + .mClearValue = { .depth = 1.0f, .stencil = 0 } }; + cmdBindRenderTargets(cmd, &bindRenderTargets); - for (auto& container : worldContainers) { - container.m_continer->UpdateBeforeRendering(); - } - std::vector uniformTest; - uint32_t queryIndex = 0; - std::vector occlusionQueryAlpha; - // start pre-z pass - beginCmd(m_prePassCmd.m_handle); - { - std::function walkRenderables; - walkRenderables = [&](iRenderableContainerNode* childNode, eWorldContainerType containerType) { - childNode->UpdateBeforeUse(); - for (auto& childNode : childNode->GetChildNodes()) { - childNode->UpdateBeforeUse(); - eCollision frustumCollision = apFrustum->CollideNode(childNode); - if (frustumCollision == eCollision_Outside) { - continue; - } - if (apFrustum->CheckAABBNearPlaneIntersection(childNode->GetMin(), childNode->GetMax())) { - cVector3f vViewSpacePos = cMath::MatrixMul(apFrustum->GetViewMatrix(), childNode->GetCenter()); - childNode->SetViewDistance(vViewSpacePos.z); - childNode->SetInsideView(true); - } else { - // Frustum origin is outside of node. Do intersection test. - cVector3f vIntersection; - cMath::CheckAABBLineIntersection( - childNode->GetMin(), childNode->GetMax(), apFrustum->GetOrigin(), childNode->GetCenter(), &vIntersection, NULL); - cVector3f vViewSpacePos = cMath::MatrixMul(apFrustum->GetViewMatrix(), vIntersection); - childNode->SetViewDistance(vViewSpacePos.z); - childNode->SetInsideView(false); - } - walkRenderables(childNode, containerType); - } - for (auto& pObject : childNode->GetObjects()) { - if (!rendering::detail::IsObjectIsVisible(pObject, options.objectVisibilityFlags, options.clipPlanes)) { - continue; - } - const bool visibleLastFrame = (prePassRenderables.empty() || prePassRenderables.contains(pObject)); - - auto& test = uniformTest.emplace_back(); - test.m_preZPass = visibleLastFrame; - test.m_renderable = pObject; - - cMaterial* pMaterial = pObject->GetMaterial(); - - if (pObject && pObject->GetRenderFrameCount() != iRenderer::GetRenderFrameCount()) { - pObject->SetRenderFrameCount(iRenderer::GetRenderFrameCount()); - pObject->UpdateGraphicsForFrame(frameTime); - } - - if (pMaterial && pMaterial->GetRenderFrameCount() != iRenderer::GetRenderFrameCount()) { - pMaterial->SetRenderFrameCount(iRenderer::GetRenderFrameCount()); - pMaterial->UpdateBeforeRendering(frameTime); - } - //////////////////////////////////////// - // Update per viewport specific and set amtrix point - // Skip this for non-decal translucent! This is because the water rendering might mess it up otherwise! - if (pMaterial == NULL || cMaterial::IsTranslucent(pMaterial->Descriptor().m_id) == false || - pMaterial->Descriptor().m_id == MaterialID::Decal) { - // skip rendering if the update return false - if (pObject->UpdateGraphicsForViewport(apFrustum, frameTime) == false) { - continue; - } + cmdSetViewport( + cmd, + 0.0f, + 0.0f, + static_cast(depthBuffer->mWidth), + static_cast(depthBuffer->mHeight), + 0.0f, + 1.0f); + cmdSetScissor(cmd, 0, 0, static_cast(depthBuffer->mWidth), static_cast(depthBuffer->mHeight)); + cmdBindPipeline(cmd, options.m_invert ? m_zPassPipelineCW.m_handle : m_zPassPipelineCCW.m_handle); - pObject->SetModelMatrixPtr(pObject->GetModelMatrix(apFrustum)); - } - // Only set a matrix used for sorting. Calculate the proper in the trans rendering! - else { - pObject->SetModelMatrixPtr(pObject->GetModelMatrix(NULL)); - } + cmdBindDescriptorSet(cmd, frameDescriptorIndex, m_materialSet.m_frameSet[frame.m_frameIndex].m_handle); - if (visibleLastFrame && pObject->UsesOcclusionQuery() && !options.m_disableOcclusionQueries) { - auto& occlusionAlpha = occlusionQueryAlpha.emplace_back(); - occlusionAlpha.m_renderable = pObject; - } - } - }; - for (auto& it : worldContainers) { - iRenderableContainerNode* pNode = it.m_continer->GetRoot(); - pNode->UpdateBeforeUse(); // Make sure node is updated. - pNode->SetInsideView(true); // We never want to check root! Assume player is inside. - walkRenderables(pNode, it.m_type); + const uint32_t materialObjectIndex = getDescriptorIndexFromName(m_materialRootSignature.m_handle, "materialRootConstant"); + for(auto& renderable: renderList.GetRenderableItems(eRenderListType_Z)) { + if (!iRenderable::IsObjectIsVisible(*renderable, options.objectVisibilityFlags, options.clipPlanes)) { + continue; } - std::sort(uniformTest.begin(), uniformTest.end(), [&](UniformTest& apObjectA, UniformTest& apObjectB) { - cMaterial* pMatA = apObjectA.m_renderable->GetMaterial(); - cMaterial* pMatB = apObjectB.m_renderable->GetMaterial(); - if (!(pMatA && pMatB)) { - return false; - } - - ////////////////////////// - // Alpha mode - if (pMatA->GetAlphaMode() != pMatB->GetAlphaMode()) { - return pMatA->GetAlphaMode() < pMatB->GetAlphaMode(); - } - - ////////////////////////// - // If alpha, sort by texture (we know alpha is same for both materials, so can just test one) - if (pMatA->GetAlphaMode() == eMaterialAlphaMode_Trans) { - if (pMatA->GetImage(eMaterialTexture_Diffuse) != pMatB->GetImage(eMaterialTexture_Diffuse)) { - return pMatA->GetImage(eMaterialTexture_Diffuse) < pMatB->GetImage(eMaterialTexture_Diffuse); - } - } - - // View space depth, no need to test further since Z should almost never be the same for two objects. - // use ">" since we want to render things closest to the screen first. - return apObjectA.m_renderable->GetViewSpaceZ() > apObjectB.m_renderable->GetViewSpaceZ(); - // return apObjectA < apObjectB; - }); - - cmdBeginDebugMarker(m_prePassCmd.m_handle, 0, 1, 0, "Pre Z"); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_DONTCARE; - loadActions.mLoadActionDepth = LOAD_ACTION_CLEAR; - loadActions.mLoadActionStencil = LOAD_ACTION_DONTCARE; - loadActions.mClearDepth = { .depth = 1.0f, .stencil = 0 }; - - cmdBindRenderTargets(m_prePassCmd.m_handle, 0, NULL, depthBuffer, &loadActions, NULL, NULL, -1, -1); - - cmdSetViewport( - m_prePassCmd.m_handle, - 0.0f, - 0.0f, - static_cast(depthBuffer->mWidth), - static_cast(depthBuffer->mHeight), - 0.0f, - 1.0f); - cmdSetScissor(m_prePassCmd.m_handle, 0, 0, static_cast(depthBuffer->mWidth), static_cast(depthBuffer->mHeight)); - cmdBindPipeline(m_prePassCmd.m_handle, options.m_invert ? m_zPassPipelineCW.m_handle : m_zPassPipelineCCW.m_handle); - - cmdBindDescriptorSet(m_prePassCmd.m_handle, frameDescriptorIndex, m_materialSet.m_frameSet[frame.m_frameIndex].m_handle); - - UniformPropBlock uniformPropBlock = {}; - for (size_t i = 0; i < uniformTest.size(); i++) { - auto& test = uniformTest[i]; - cMaterial* pMaterial = test.m_renderable->GetMaterial(); - - ASSERT(uniformTest.size() < MaxObjectTest && "Too many renderables"); - auto* pBoundingVolume = test.m_renderable->GetBoundingVolume(); - - BufferUpdateDesc updateDesc = { m_hiZBoundBoxBuffer.m_handle, i * (2 * sizeof(float4)), sizeof(float4) * 2 }; - auto boundBoxMin = pBoundingVolume->GetMin(); - auto boundBoxMax = pBoundingVolume->GetMax(); - beginUpdateResource(&updateDesc); - reinterpret_cast(updateDesc.pMappedData)[0] = float4(boundBoxMin.x, boundBoxMin.y, boundBoxMin.z, 0.0f); - reinterpret_cast(updateDesc.pMappedData)[1] = float4(boundBoxMax.x, boundBoxMax.y, boundBoxMax.z, 0.0f); - endUpdateResource(&updateDesc, nullptr); - - if (!test.m_preZPass || !pMaterial || cMaterial::IsTranslucent(pMaterial->Descriptor().m_id)) { - continue; - } - - std::array targets = { eVertexBufferElement_Position, - eVertexBufferElement_Texture0, - eVertexBufferElement_Normal, - eVertexBufferElement_Texture1Tangent }; - DrawPacket packet = test.m_renderable->ResolveDrawPacket(frame, targets); - if (packet.m_type == DrawPacket::Unknown) { - continue; - } - MaterialRootConstant materialConst = {}; - uint32_t instance = cmdBindMaterialAndObject(m_prePassCmd.m_handle, frame, pMaterial, test.m_renderable, {}); - materialConst.objectId = instance; - DrawPacket::cmdBindBuffers(m_prePassCmd.m_handle, frame.m_resourcePool, &packet); - cmdBindPushConstants(m_prePassCmd.m_handle, m_materialRootSignature.m_handle, materialObjectIndex, &materialConst); - cmdDrawIndexed(m_prePassCmd.m_handle, packet.numberOfIndecies(), 0, 0); + cMaterial* pMaterial = renderable->GetMaterial(); + std::array targets = { eVertexBufferElement_Position, + eVertexBufferElement_Texture0, + eVertexBufferElement_Normal, + eVertexBufferElement_Texture1Tangent }; + DrawPacket packet = renderable->ResolveDrawPacket(frame); + if (packet.m_type == DrawPacket::Unknown) { + continue; } - - uniformPropBlock.maxMipLevel = hiZBuffer->mMipLevels - 1; - uniformPropBlock.depthDim = uint2(depthBuffer->mWidth, depthBuffer->mHeight); - uniformPropBlock.numObjects = uniformTest.size(); - - BufferUpdateDesc updateDesc = { m_hiZOcclusionUniformBuffer.m_handle, 0, sizeof(UniformPropBlock) }; - beginUpdateResource(&updateDesc); - (*reinterpret_cast(updateDesc.pMappedData)) = uniformPropBlock; - endUpdateResource(&updateDesc, nullptr); - cmdEndDebugMarker(m_prePassCmd.m_handle); + MaterialRootConstant materialConst = {}; + uint32_t instance = cmdBindMaterialAndObject(cmd, frame, pMaterial, renderable, {}); + materialConst.objectId = instance; + DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet, targets); + cmdBindPushConstants(cmd, m_materialRootSignature.m_handle, materialObjectIndex, &materialConst); + cmdDrawIndexed(cmd, packet.numberOfIndecies(), 0, 0); } + { - cmdBeginDebugMarker(m_prePassCmd.m_handle, 1, 1, 0, "Occlusion Query"); + cmdBindRenderTargets(cmd, NULL); + std::array rtBarriers = { + RenderTargetBarrier{ depthBuffer, RESOURCE_STATE_DEPTH_WRITE, RESOURCE_STATE_DEPTH_WRITE }, + }; + cmdResourceBarrier(cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); + bindRenderTargets.mDepthStencil = { .pDepthStencil = depthBuffer, + .mLoadAction = LOAD_ACTION_LOAD, + .mClearValue = { .depth = 1.0f, .stencil = 0 } }; + cmdBindRenderTargets(cmd, &bindRenderTargets); + } + if (options.m_query) { + auto* query = options.m_query; + cmdBeginDebugMarker(cmd, 1, 1, 0, "Occlusion Query"); std::array targets = { eVertexBufferElement_Position }; - DrawPacket packet = static_cast(m_box.get())->resolveGeometryBinding(frame.m_currentFrame, targets); + DrawPacket packet = static_cast(m_box.get())->resolveGeometryBinding(frame.m_currentFrame); uint32_t occlusionObjectIndex = getDescriptorIndexFromName(m_rootSignatureOcclusuion.m_handle, "rootConstant"); uint32_t occlusionIndex = 0; cMatrixf viewProj = cMath::MatrixMul(projectionMat, viewMat); - cmdBindDescriptorSet(m_prePassCmd.m_handle, 0, m_descriptorOcclusionConstSet.m_handle); - for (auto& query : occlusionQueryAlpha) { - if (TypeInfo::IsType(*query.m_renderable)) { - cBillboard* pBillboard = static_cast(query.m_renderable); + cmdBindDescriptorSet(cmd, 0, m_descriptorOcclusionConstSet.m_handle); + for (auto& renderable : renderList.GetOcclusionQueryItems()) { + if(query->m_queryIndex >= MaxOcclusionDescSize - 2) { + break; + } + if (TypeInfo::IsType(*renderable)) { + cBillboard* pBillboard = static_cast(renderable); auto mvp = cMath::ToForgeMatrix4(cMath::MatrixMul( viewProj, cMath::MatrixMul(pBillboard->GetWorldMatrix(), cMath::MatrixScale(pBillboard->GetHaloSourceSize())))); @@ -3457,217 +3096,70 @@ namespace hpl { BufferUpdateDesc updateDesc = { m_occlusionUniformBuffer.m_handle, m_occlusionIndex * sizeof(mat4) }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = mvp; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); + cmdBindPushConstants(cmd, m_rootSignatureOcclusuion.m_handle, occlusionObjectIndex, &m_occlusionIndex); - cmdBindPushConstants( - m_prePassCmd.m_handle, m_rootSignatureOcclusuion.m_handle, occlusionObjectIndex, &m_occlusionIndex); + DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet, targets); - DrawPacket::cmdBindBuffers(m_prePassCmd.m_handle, frame.m_resourcePool, &packet); + QueryCoverageData::CoverageQuery queryCoverage = QueryCoverageData::CoverageQuery{ + .m_queryIndex = query->m_queryIndex++, + .m_maxQueryIndex = query->m_queryIndex++, + }; + query->m_coverageQueries.try_emplace(renderable, queryCoverage); QueryDesc queryDesc = {}; - queryDesc.mIndex = queryIndex++; - cmdBindPipeline(m_prePassCmd.m_handle, m_pipelineOcclusionQuery.m_handle); - cmdBeginQuery(m_prePassCmd.m_handle, m_occlusionQuery.m_handle, &queryDesc); - cmdDrawIndexed(m_prePassCmd.m_handle, packet.numberOfIndecies(), 0, 0); - cmdEndQuery(m_prePassCmd.m_handle, m_occlusionQuery.m_handle, &queryDesc); - query.m_queryIndex = queryDesc.mIndex; - - queryDesc.mIndex = queryIndex++; - cmdBindPipeline(m_prePassCmd.m_handle, m_pipelineMaxOcclusionQuery.m_handle); - cmdBeginQuery(m_prePassCmd.m_handle, m_occlusionQuery.m_handle, &queryDesc); - cmdDrawIndexed(m_prePassCmd.m_handle, packet.numberOfIndecies(), 0, 0); - cmdEndQuery(m_prePassCmd.m_handle, m_occlusionQuery.m_handle, &queryDesc); - query.m_maxQueryIndex = queryDesc.mIndex; - - m_occlusionIndex = (m_occlusionIndex + 1) % MaxOcclusionDescSize; - } - } - cmdEndDebugMarker(m_prePassCmd.m_handle); - } - // hi-z generate pass - { - cmdBeginDebugMarker(m_prePassCmd.m_handle, 0, 0, 0, "Generate HI-Z"); - { - cmdBindRenderTargets(m_prePassCmd.m_handle, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); - std::array rtBarriers = { - RenderTargetBarrier{ depthBuffer, RESOURCE_STATE_DEPTH_WRITE, RESOURCE_STATE_SHADER_RESOURCE }, - RenderTargetBarrier{ hiZBuffer, RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_RENDER_TARGET }, - }; - cmdResourceBarrier(m_prePassCmd.m_handle, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); - } - { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - loadActions.mClearColorValues[0] = { .r = 1.0f, .g = 0.0f, .b = 0.0f, .a = 0.0f }; - cmdBindRenderTargets(m_prePassCmd.m_handle, 1, &hiZBuffer, NULL, &loadActions, NULL, NULL, -1, -1); - - std::array params = {}; - params[0].pName = "sourceInput"; - params[0].ppTextures = &depthBuffer->pTexture; - updateDescriptorSet(frame.m_renderer->Rend(), 0, m_descriptorCopyDepth.m_handle, params.size(), params.data()); - - cmdSetViewport(m_prePassCmd.m_handle, 0.0f, 0.0f, depthBuffer->mWidth, depthBuffer->mHeight, 0.0f, 1.0f); - cmdSetScissor(m_prePassCmd.m_handle, 0, 0, depthBuffer->mWidth, depthBuffer->mHeight); - cmdBindPipeline(m_prePassCmd.m_handle, m_pipelineCopyDepth.m_handle); - - cmdBindDescriptorSet(m_prePassCmd.m_handle, 0, m_descriptorCopyDepth.m_handle); - cmdDraw(m_prePassCmd.m_handle, 3, 0); - } - - { - cmdBindRenderTargets(m_prePassCmd.m_handle, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); - std::array rtBarriers = { - RenderTargetBarrier{ depthBuffer, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_DEPTH_WRITE }, - RenderTargetBarrier{ hiZBuffer, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_UNORDERED_ACCESS }, - }; - cmdResourceBarrier(m_prePassCmd.m_handle, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); - } - uint32_t rootConstantIndex = getDescriptorIndexFromName(m_rootSignatureHIZOcclusion.m_handle, "uRootConstants"); - uint32_t width = static_cast(depthBuffer->mWidth); - uint32_t height = static_cast(depthBuffer->mHeight); - for (uint32_t lod = 1; lod < hiZBuffer->mMipLevels; ++lod) { - std::array params = {}; - params[0].pName = "depthInput"; - params[0].mBindMipChain = true; - params[0].ppTextures = &hiZBuffer->pTexture; - updateDescriptorSet(frame.m_renderer->Rend(), lod, m_descriptorSetHIZGenerate.m_handle, params.size(), params.data()); - - width /= 2; - height /= 2; - struct { - uint2 screenDim; - uint32_t mipLevel; - } pushConstants = {}; - - pushConstants.mipLevel = lod; - pushConstants.screenDim = uint2(depthBuffer->mWidth, depthBuffer->mHeight); - - // bind lod to push constant - cmdBindPushConstants(m_prePassCmd.m_handle, m_rootSignatureHIZOcclusion.m_handle, rootConstantIndex, &pushConstants); - cmdBindDescriptorSet(m_prePassCmd.m_handle, lod, m_descriptorSetHIZGenerate.m_handle); - cmdBindPipeline(m_prePassCmd.m_handle, m_pipelineHIZGenerate.m_handle); - cmdDispatch(m_prePassCmd.m_handle, static_cast(width / 16) + 1, static_cast(height / 16) + 1, 1); - - std::array rtBarriers = { - RenderTargetBarrier{ hiZBuffer, RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_UNORDERED_ACCESS }, - }; - cmdResourceBarrier(m_prePassCmd.m_handle, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); - } - { - std::array rtBarriers = { RenderTargetBarrier{ - hiZBuffer, RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_SHADER_RESOURCE } }; - cmdResourceBarrier(m_prePassCmd.m_handle, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); - } - cmdEndDebugMarker(m_prePassCmd.m_handle); - - cmdBeginDebugMarker(m_prePassCmd.m_handle, 0, 1, 0, "AABB Hi-Z"); - { - std::array params = {}; - params[0].pName = "perFrameConstants"; - params[0].ppBuffers = &m_perFrameBuffer[frameDescriptorIndex].m_handle; - params[1].pName = "objectUniformBlock"; - params[1].ppBuffers = &m_hiZOcclusionUniformBuffer.m_handle; - params[2].pName = "occlusionTest"; - params[2].ppBuffers = &m_occlusionTestBuffer.m_handle; - params[3].pName = "occlusionBoxBuffer"; - params[3].ppBuffers = &m_hiZBoundBoxBuffer.m_handle; - params[4].pName = "depthTest"; - params[4].ppTextures = &hiZBuffer->pTexture; - updateDescriptorSet(frame.m_renderer->Rend(), 0, m_descriptorAABBOcclusionTest.m_handle, params.size(), params.data()); - - cmdBindDescriptorSet(m_prePassCmd.m_handle, 0, m_descriptorAABBOcclusionTest.m_handle); - cmdBindPipeline(m_prePassCmd.m_handle, m_pipelineAABBOcclusionTest.m_handle); - cmdDispatch(m_prePassCmd.m_handle, static_cast(uniformTest.size() / 128) + 1, 1, 1); - { - std::array rtBarriers = { RenderTargetBarrier{ - hiZBuffer, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_UNORDERED_ACCESS } }; - cmdResourceBarrier(m_prePassCmd.m_handle, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); - } - } - cmdEndDebugMarker(m_prePassCmd.m_handle); - cmdResolveQuery(m_prePassCmd.m_handle, m_occlusionQuery.m_handle, m_occlusionReadBackBuffer.m_handle, 0, queryIndex); - endCmd(m_prePassCmd.m_handle); - - // Submit the gpu work. - QueueSubmitDesc submitDesc = {}; - submitDesc.mCmdCount = 1; - submitDesc.ppCmds = &m_prePassCmd.m_handle; - submitDesc.pSignalFence = m_prePassFence.m_handle; - submitDesc.mSubmitDone = true; - queueSubmit(frame.m_renderer->GetGraphicsQueue(), &submitDesc); - - FenceStatus fenceStatus; - getFenceStatus(frame.m_renderer->Rend(), m_prePassFence.m_handle, &fenceStatus); - if (fenceStatus == FENCE_STATUS_INCOMPLETE) { - waitForFences(frame.m_renderer->Rend(), 1, &m_prePassFence.m_handle); - } - - uint64_t* occlusionCount = reinterpret_cast(m_occlusionReadBackBuffer.m_handle->pCpuMappedAddress); - for (auto& query : occlusionQueryAlpha) { - if (TypeInfo::IsType(*query.m_renderable)) { - cBillboard* pBillboard = static_cast(query.m_renderable); - float maxSamples = static_cast(occlusionCount[query.m_maxQueryIndex]); - float samples = static_cast(occlusionCount[query.m_queryIndex]); - float billboardCoverage = pBillboard->getAreaOfScreenSpace(apFrustum); - if (maxSamples > 0.0f) { - pBillboard->SetHaloAlpha(billboardCoverage * (samples / maxSamples)); - } else { - pBillboard->SetHaloAlpha(0.0f); - } - } - } - } - - prePassRenderables.clear(); - - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_DONTCARE; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - loadActions.mLoadActionStencil = LOAD_ACTION_DONTCARE; - loadActions.mClearDepth = { .depth = 1.0f, .stencil = 0 }; - - cmdBeginDebugMarker(cmd, 0, 1, 0, "Post Z"); - cmdBindRenderTargets(cmd, 0, NULL, depthBuffer, &loadActions, NULL, NULL, -1, -1); - cmdSetViewport(cmd, 0.0f, 0.0f, depthBuffer->mWidth, depthBuffer->mHeight, 0.0f, 1.0f); - cmdSetScissor(cmd, 0, 0, depthBuffer->mWidth, depthBuffer->mHeight); - - cmdBindPipeline(cmd, options.m_invert ? m_zPassPipelineCW.m_handle : m_zPassPipelineCCW.m_handle); - cmdBindDescriptorSet(cmd, frameDescriptorIndex, m_materialSet.m_frameSet[frame.m_frameIndex].m_handle); + queryDesc.mIndex = queryCoverage.m_queryIndex; + cmdBindPipeline(cmd, m_pipelineOcclusionQuery.m_handle); + cmdBeginQuery(cmd, query->m_occlusionQuery.m_handle, &queryDesc); + cmdDrawIndexed(cmd, packet.numberOfIndecies(), 0, 0); + cmdEndQuery(cmd, query->m_occlusionQuery.m_handle, &queryDesc); - auto* testResult = reinterpret_cast(m_occlusionTestBuffer.m_handle->pCpuMappedAddress); - for (size_t i = 0; i < uniformTest.size(); ++i) { - if (testResult[i] == 1) { - renderList.AddObject(uniformTest[i].m_renderable); - prePassRenderables.insert(uniformTest[i].m_renderable); - if (!uniformTest[i].m_preZPass) { - auto* renderable = uniformTest[i].m_renderable; - eMaterialRenderMode renderMode = - renderable->GetCoverageAmount() >= 1 ? eMaterialRenderMode_Z : eMaterialRenderMode_Z_Dissolve; - - cMaterial* pMaterial = renderable->GetMaterial(); - if (!pMaterial || cMaterial::IsTranslucent(pMaterial->Descriptor().m_id)) { - continue; - } - std::array targets = { eVertexBufferElement_Position, - eVertexBufferElement_Texture0, - eVertexBufferElement_Normal, - eVertexBufferElement_Texture1Tangent }; - DrawPacket drawPacket = renderable->ResolveDrawPacket(frame, targets); - if (drawPacket.m_type == DrawPacket::Unknown) { - continue; - } + queryDesc.mIndex = queryCoverage.m_maxQueryIndex++; + cmdBindPipeline(cmd, m_pipelineMaxOcclusionQuery.m_handle); + cmdBeginQuery(cmd, query->m_occlusionQuery.m_handle, &queryDesc); + cmdDrawIndexed(cmd, packet.numberOfIndecies(), 0, 0); + cmdEndQuery(cmd, query->m_occlusionQuery.m_handle, &queryDesc); - MaterialRootConstant materialConst = {}; - uint32_t instance = cmdBindMaterialAndObject(cmd, frame, pMaterial, renderable); - materialConst.objectId = instance; - DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &drawPacket); - cmdBindPushConstants(cmd, m_materialRootSignature.m_handle, materialObjectIndex, &materialConst); - cmdDrawIndexed(cmd, drawPacket.numberOfIndecies(), 0, 0); + m_occlusionIndex = (m_occlusionIndex + 1) % MaxOcclusionDescSize; } } + cmdEndDebugMarker(cmd); } + //for (size_t i = 0; i < uniformTest.size(); i++) { + // auto& test = uniformTest[i]; + // cMaterial* pMaterial = test.m_renderable->GetMaterial(); + + // ASSERT(uniformTest.size() < MaxObjectTest && "Too many renderables"); + // auto* pBoundingVolume = test.m_renderable->GetBoundingVolume(); + + // BufferUpdateDesc updateDesc = { m_hiZBoundBoxBuffer.m_handle, i * (2 * sizeof(float4)), sizeof(float4) * 2 }; + // auto boundBoxMin = pBoundingVolume->GetMin(); + // auto boundBoxMax = pBoundingVolume->GetMax(); + // beginUpdateResource(&updateDesc); + // reinterpret_cast(updateDesc.pMappedData)[0] = float4(boundBoxMin.x, boundBoxMin.y, boundBoxMin.z, 0.0f); + // reinterpret_cast(updateDesc.pMappedData)[1] = float4(boundBoxMax.x, boundBoxMax.y, boundBoxMax.z, 0.0f); + // endUpdateResource(&updateDesc); + + // if (!test.m_preZPass || !pMaterial || cMaterial::IsTranslucent(pMaterial->Descriptor().m_id)) { + // continue; + // } + + // std::array targets = { eVertexBufferElement_Position, + // eVertexBufferElement_Texture0, + // eVertexBufferElement_Normal, + // eVertexBufferElement_Texture1Tangent }; + // DrawPacket packet = test.m_renderable->ResolveDrawPacket(frame); + // if (packet.m_type == DrawPacket::Unknown) { + // continue; + // } + // MaterialRootConstant materialConst = {}; + // uint32_t instance = cmdBindMaterialAndObject(m_prePassCmd.m_handle, frame, pMaterial, test.m_renderable, {}); + // materialConst.objectId = instance; + // DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet, targets); + // cmdBindPushConstants(cmd, m_materialRootSignature.m_handle, materialObjectIndex, &materialConst); + // cmdDrawIndexed(cmd, packet.numberOfIndecies(), 0, 0); + //} cmdEndDebugMarker(cmd); } @@ -3697,7 +3189,7 @@ namespace hpl { beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = material::UniformMaterialBlock::CreateFromMaterial(*apMaterial); - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); std::array params{}; size_t paramCount = 0; @@ -3778,13 +3270,14 @@ namespace hpl { sizeof(cRendererDeferred::UniformObject) * index }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = uniformObjectData; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); m_materialSet.m_objectDescriptorLookup[apObject] = index; } cmdBindDescriptorSet( cmd, - detail::resolveTextureFilterGroup(apMaterial->GetTextureAntistropy(), apMaterial->GetTextureWrap(), apMaterial->GetTextureFilter()), + detail::resolveTextureFilterGroup( + apMaterial->GetTextureAntistropy(), apMaterial->GetTextureWrap(), apMaterial->GetTextureFilter()), m_materialSet.m_materialConstSet.m_handle); cmdBindDescriptorSet(cmd, apMaterial->Index(), m_materialSet.m_perBatchSet[frame.m_frameIndex].m_handle); return index; @@ -3824,6 +3317,7 @@ namespace hpl { buffer.m_depthBuffer.Load(renderer.Rend(), [&](RenderTarget** handle) { auto targetDesc = deferredRenderTargetDesc(); + targetDesc.mClearValue = {.depth = 1.0f, .stencil = 0}; targetDesc.mFormat = DepthBufferFormat; targetDesc.mStartState = RESOURCE_STATE_DEPTH_WRITE; targetDesc.pName = "Depth RT"; @@ -3889,15 +3383,14 @@ namespace hpl { void cRendererDeferred::Draw( Cmd* cmd, - const ForgeRenderer::Frame& frame, + ForgeRenderer::Frame& frame, cViewport& viewport, float afFrameTime, cFrustum* apFrustum, cWorld* apWorld, - cRenderSettings* apSettings, - bool abSendFrameBufferToPostEffects) { + cRenderSettings* apSettings) { // keep around for the moment ... - BeginRendering(afFrameTime, apFrustum, apWorld, apSettings, abSendFrameBufferToPostEffects); + BeginRendering(afFrameTime, apFrustum, apWorld, apSettings, false); if (frame.m_currentFrame != m_activeFrame) { m_materialSet.m_objectIndex = 0; @@ -3915,7 +3408,6 @@ namespace hpl { const Matrix4 mainFrustumViewMat = apFrustum->GetViewMat(); const Matrix4 mainFrustumProjMat = apFrustum->GetProjectionMat(); - // auto& swapChainImage = frame.m_swapChain->ppRenderTargets[frame.m_swapChainIndex]; auto common = m_boundViewportData.resolve(viewport); if (!common || common->m_size != viewport.GetSize()) { auto* forgeRenderer = Interface::Get(); @@ -3926,6 +3418,16 @@ namespace hpl { } if (common) { // reusing state from gbuffer viewportData->m_reflectionBuffer = std::move(common->m_reflectionBuffer); + viewportData->m_query = std::move(viewportData->m_query); + } + if(!viewportData->m_query.m_occlusionQuery.IsValid()){ + viewportData->m_query.m_occlusionQuery.Load(forgeRenderer->Rend(), [&](QueryPool** pool) { + QueryPoolDesc queryPoolDesc = {}; + queryPoolDesc.mType = QUERY_TYPE_OCCLUSION; + queryPoolDesc.mQueryCount = MaxOcclusionDescSize; + addQueryPool(forgeRenderer->Rend(), &queryPoolDesc, pool); + return true; + }); } for (auto& reflection : viewportData->m_reflectionBuffer) { RebuildGBuffer(*forgeRenderer, reflection.m_buffer, viewportData->m_size.x / 2, viewportData->m_size.y / 2); @@ -3990,29 +3492,102 @@ namespace hpl { frame.m_resourcePool->Push(currentGBuffer.m_refractionImage); // Setup far plane coordinates - /////////////////////////// - // Occlusion testing - m_rendererList.BeginAndReset(afFrameTime, apFrustum); - cmdPreAndPostZ( - frame.m_cmd, + // setup render list + { + m_rendererList.BeginAndReset(afFrameTime, apFrustum); + auto* dynamicContainer = apWorld->GetRenderableContainer(eWorldContainerType_Dynamic); + auto* staticContainer = apWorld->GetRenderableContainer(eWorldContainerType_Static); + dynamicContainer->UpdateBeforeRendering(); + staticContainer->UpdateBeforeRendering(); + + auto prepareObjectHandler = [&](iRenderable* pObject) { + if (!iRenderable::IsObjectIsVisible(*pObject, eRenderableFlag_VisibleInNonReflection, {})) { + return; + } + + cMaterial* pMaterial = pObject->GetMaterial(); + + if (pObject && pObject->GetRenderFrameCount() != iRenderer::GetRenderFrameCount()) { + pObject->SetRenderFrameCount(iRenderer::GetRenderFrameCount()); + pObject->UpdateGraphicsForFrame(afFrameTime); + } + + if (pMaterial && pMaterial->GetRenderFrameCount() != iRenderer::GetRenderFrameCount()) { + pMaterial->SetRenderFrameCount(iRenderer::GetRenderFrameCount()); + pMaterial->UpdateBeforeRendering(afFrameTime); + } + //////////////////////////////////////// + // Update per viewport specific and set amtrix point + // Skip this for non-decal translucent! This is because the water rendering might mess it up otherwise! + if (pMaterial == NULL || cMaterial::IsTranslucent(pMaterial->Descriptor().m_id) == false || + pMaterial->Descriptor().m_id == MaterialID::Decal) { + // skip rendering if the update return false + if (pObject->UpdateGraphicsForViewport(apFrustum, afFrameTime) == false) { + return; + } + + pObject->SetModelMatrixPtr(pObject->GetModelMatrix(apFrustum)); + } + // Only set a matrix used for sorting. Calculate the proper in the trans rendering! + else { + pObject->SetModelMatrixPtr(pObject->GetModelMatrix(NULL)); + } + auto queryIt = common->m_query.m_coverageQueries.find(pObject); + if(queryIt != common->m_query.m_coverageQueries.end()) { + if (TypeInfo::IsType(*pObject)) { + cBillboard* pBillboard = static_cast(pObject); + QueryData maxSamplesQuery = {0}; + QueryData samplesQuery = {0}; + getQueryData( + frame.m_renderer->Rend(), + common->m_query.m_occlusionQuery.m_handle, + queryIt->second.m_maxQueryIndex, + &maxSamplesQuery); + getQueryData( + frame.m_renderer->Rend(), + common->m_query.m_occlusionQuery.m_handle, + queryIt->second.m_queryIndex, + &samplesQuery); + float billboardCoverage = pBillboard->getAreaOfScreenSpace(apFrustum); + if (maxSamplesQuery.mOcclusionCounts > 0) { + pBillboard->SetHaloAlpha(billboardCoverage * ((double)samplesQuery.mOcclusionCounts / (double)maxSamplesQuery.mOcclusionCounts)); + } else { + pBillboard->SetHaloAlpha(0.0f); + } + } + } + m_rendererList.AddObject(pObject); + }; + iRenderableContainer::WalkRenderableContainer( + *dynamicContainer, apFrustum, prepareObjectHandler, eRenderableFlag_VisibleInNonReflection); + iRenderableContainer::WalkRenderableContainer( + *staticContainer, apFrustum, prepareObjectHandler, eRenderableFlag_VisibleInNonReflection); + m_rendererList.End( + eRenderListCompileFlag_Diffuse | eRenderListCompileFlag_Translucent | eRenderListCompileFlag_Decal | + eRenderListCompileFlag_Illumination | eRenderListCompileFlag_FogArea | eRenderListCompileFlag_Z); + } + + cmdBindRenderTargets(cmd, NULL); + common->m_query.m_coverageQueries.clear(); + if (common->m_query.m_queryIndex > 0) { + cmdResetQuery(cmd, common->m_query.m_occlusionQuery.m_handle, 0, common->m_query.m_queryIndex); + } + common->m_query.m_queryIndex = 0; + cmdPreZ( + cmd, apWorld, - currentGBuffer.m_preZPassRenderables, frame, m_rendererList, afFrameTime, currentGBuffer.m_depthBuffer.m_handle, - currentGBuffer.m_hizDepthBuffer.m_handle, apFrustum, mainFrameIndex, mainFrustumView, mainFrustumProj, - {}); - m_rendererList.End( - eRenderListCompileFlag_Diffuse | eRenderListCompileFlag_Translucent | eRenderListCompileFlag_Decal | - eRenderListCompileFlag_Illumination | eRenderListCompileFlag_FogArea); + { .m_query = &common->m_query }); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ currentGBuffer.m_colorBuffer.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, RenderTargetBarrier{ currentGBuffer.m_normalBuffer.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, @@ -4036,7 +3611,7 @@ namespace hpl { { .m_invert = false }); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ currentGBuffer.m_colorBuffer.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, RenderTargetBarrier{ currentGBuffer.m_normalBuffer.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, @@ -4113,14 +3688,12 @@ namespace hpl { // Render Illumination Pass --> renders to output target // ------------------------------------------------------------------------ { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - std::array targets = { - currentGBuffer.m_outputBuffer.m_handle, - }; - cmdBindRenderTargets( - frame.m_cmd, targets.size(), targets.data(), currentGBuffer.m_depthBuffer.m_handle, &loadActions, nullptr, nullptr, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {0}; + bindRenderTargets.mDepthStencil = { .pDepthStencil = currentGBuffer.m_depthBuffer.m_handle, .mLoadAction = LOAD_ACTION_LOAD }; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { currentGBuffer.m_outputBuffer.m_handle, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); + cmdSetViewport(frame.m_cmd, 0.0f, 0.0f, static_cast(common->m_size.x), static_cast(common->m_size.y), 0.0f, 1.0f); cmdSetScissor(frame.m_cmd, 0, 0, common->m_size.x, common->m_size.y); cmdBindPipeline(frame.m_cmd, m_solidIlluminationPipelineCCW.m_handle); @@ -4133,7 +3706,7 @@ namespace hpl { eVertexBufferElement_Position, eVertexBufferElement_Texture0, }; - DrawPacket packet = illuminationItem->ResolveDrawPacket(frame, targets); + DrawPacket packet = illuminationItem->ResolveDrawPacket(frame); if (pMaterial == nullptr || packet.m_type == DrawPacket::Unknown) { continue; @@ -4143,7 +3716,7 @@ namespace hpl { uint32_t instance = cmdBindMaterialAndObject(frame.m_cmd, frame, pMaterial, illuminationItem); materialConst.objectId = instance; - DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(cmd, frame.m_resourcePool, &packet, targets); cmdBindPushConstants(frame.m_cmd, m_materialRootSignature.m_handle, materialObjectIndex, &materialConst); cmdDrawIndexed(frame.m_cmd, packet.numberOfIndecies(), 0, 0); } @@ -4208,18 +3781,27 @@ namespace hpl { fogIndex * sizeof(UniformFogData) }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = uniformData; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); fogIndex++; } } - std::array targets = { - currentGBuffer.m_outputBuffer.m_handle, - }; - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - cmdBindRenderTargets( - frame.m_cmd, targets.size(), targets.data(), currentGBuffer.m_depthBuffer.m_handle, &loadActions, nullptr, nullptr, -1, -1); + // std::array targets = { + // currentGBuffer.m_outputBuffer.m_handle, + // }; + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + // loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + // cmdBindRenderTargets( + // frame.m_cmd, targets.size(), targets.data(), currentGBuffer.m_depthBuffer.m_handle, &loadActions, nullptr, nullptr, -1, + // -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mDepthStencil = { .pDepthStencil = currentGBuffer.m_depthBuffer.m_handle, .mLoadAction = LOAD_ACTION_LOAD }; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { .pRenderTarget = currentGBuffer.m_outputBuffer.m_handle, + .mLoadAction = LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); + cmdSetViewport(frame.m_cmd, 0.0f, 0.0f, (float)common->m_size.x, (float)common->m_size.y, 0.0f, 1.0f); cmdSetScissor(frame.m_cmd, 0, 0, common->m_size.x, common->m_size.y); @@ -4227,8 +3809,8 @@ namespace hpl { std::array geometryStream = { eVertexBufferElement_Position }; DrawPacket drawPacket = - static_cast(m_box.get())->resolveGeometryBinding(frame.m_currentFrame, geometryStream); - DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &drawPacket); + static_cast(m_box.get())->resolveGeometryBinding(frame.m_currentFrame); + DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &drawPacket, geometryStream); { std::array params = {}; @@ -4254,7 +3836,7 @@ namespace hpl { fogIndex * sizeof(UniformFogData) }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = uniformData; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); fogIndex++; } @@ -4273,7 +3855,7 @@ namespace hpl { fogData->m_fogStart = apWorld->GetFogStart(); fogData->m_fogLength = apWorld->GetFogEnd() - apWorld->GetFogStart(); fogData->m_fogFalloffExp = apWorld->GetFogFalloffExp(); - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); cmdBindDescriptorSet(frame.m_cmd, 0, m_fogPass.m_perFrameSet[frame.m_frameIndex]); cmdBindPipeline(frame.m_cmd, m_fogPass.m_fullScreenPipeline.m_handle); @@ -4283,7 +3865,7 @@ namespace hpl { cmdEndDebugMarker(frame.m_cmd); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); { std::array textureBarriers = { @@ -4338,20 +3920,28 @@ namespace hpl { postSolidEvent.m_debug = m_debug.get(); postSolidEvent.m_renderList = &m_rendererList; viewport.SignalDraw(postSolidEvent); - m_debug->flush(frame, frame.m_cmd, viewport, *apFrustum, currentGBuffer.m_outputBuffer, currentGBuffer.m_depthBuffer); + m_debug->flush(frame, cmd, viewport, *apFrustum, currentGBuffer.m_outputBuffer, currentGBuffer.m_depthBuffer); // ------------------------------------------------------------------------ // Translucency Pass --> output target // ------------------------------------------------------------------------ { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - std::array targets = { - currentGBuffer.m_outputBuffer.m_handle, - }; - cmdBindRenderTargets( - frame.m_cmd, targets.size(), targets.data(), currentGBuffer.m_depthBuffer.m_handle, &loadActions, nullptr, nullptr, -1, -1); + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + // loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + // std::array targets = { + // currentGBuffer.m_outputBuffer.m_handle, + // }; + // cmdBindRenderTargets( + // frame.m_cmd, targets.size(), targets.data(), currentGBuffer.m_depthBuffer.m_handle, &loadActions, nullptr, nullptr, -1, + // -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mDepthStencil = { .pDepthStencil = currentGBuffer.m_depthBuffer.m_handle, .mLoadAction = LOAD_ACTION_LOAD }; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = BindRenderTargetDesc{ currentGBuffer.m_outputBuffer.m_handle, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); + cmdSetViewport(frame.m_cmd, 0.0f, 0.0f, static_cast(common->m_size.x), static_cast(common->m_size.y), 0.0f, 1.0f); cmdSetScissor(frame.m_cmd, 0, 0, common->m_size.x, common->m_size.y); @@ -4470,15 +4060,60 @@ namespace hpl { beginCmd(resolveReflectionBuffer.m_cmd.m_handle); m_reflectionRendererList.BeginAndReset(afFrameTime, &reflectFrustum); - cmdPreAndPostZ( + auto* dynamicContainer = apWorld->GetRenderableContainer(eWorldContainerType_Dynamic); + auto* staticContainer = apWorld->GetRenderableContainer(eWorldContainerType_Static); + dynamicContainer->UpdateBeforeRendering(); + staticContainer->UpdateBeforeRendering(); + auto prepareObjectHandler = [&](iRenderable* pObject) { + if (!iRenderable::IsObjectIsVisible(*pObject, eRenderableFlag_VisibleInReflection, {})) { + return; + } + + cMaterial* pMaterial = pObject->GetMaterial(); + + if (pObject && pObject->GetRenderFrameCount() != iRenderer::GetRenderFrameCount()) { + pObject->SetRenderFrameCount(iRenderer::GetRenderFrameCount()); + pObject->UpdateGraphicsForFrame(afFrameTime); + } + + if (pMaterial && pMaterial->GetRenderFrameCount() != iRenderer::GetRenderFrameCount()) { + pMaterial->SetRenderFrameCount(iRenderer::GetRenderFrameCount()); + pMaterial->UpdateBeforeRendering(afFrameTime); + } + //////////////////////////////////////// + // Update per viewport specific and set amtrix point + // Skip this for non-decal translucent! This is because the water rendering might mess it up otherwise! + if (pMaterial == NULL || cMaterial::IsTranslucent(pMaterial->Descriptor().m_id) == false || + pMaterial->Descriptor().m_id == MaterialID::Decal) { + // skip rendering if the update return false + if (pObject->UpdateGraphicsForViewport(apFrustum, afFrameTime) == false) { + return; + } + + pObject->SetModelMatrixPtr(pObject->GetModelMatrix(apFrustum)); + } + // Only set a matrix used for sorting. Calculate the proper in the trans rendering! + else { + pObject->SetModelMatrixPtr(pObject->GetModelMatrix(NULL)); + } + + m_reflectionRendererList.AddObject(pObject); + }; + iRenderableContainer::WalkRenderableContainer( + *dynamicContainer, apFrustum, prepareObjectHandler, eRenderableFlag_VisibleInNonReflection); + iRenderableContainer::WalkRenderableContainer( + *staticContainer, apFrustum, prepareObjectHandler, eRenderableFlag_VisibleInNonReflection); + m_reflectionRendererList.End( + eRenderListCompileFlag_Diffuse | eRenderListCompileFlag_Translucent | eRenderListCompileFlag_Decal | + eRenderListCompileFlag_Illumination | eRenderListCompileFlag_Z); + + cmdPreZ( resolveReflectionBuffer.m_cmd.m_handle, apWorld, - resolveReflectionBuffer.m_buffer.m_preZPassRenderables, frame, m_reflectionRendererList, afFrameTime, resolveReflectionBuffer.m_buffer.m_depthBuffer.m_handle, - resolveReflectionBuffer.m_buffer.m_hizDepthBuffer.m_handle, &reflectFrustum, reflectionFrameDescIndex, reflectionFrustumView, @@ -4487,14 +4122,10 @@ namespace hpl { .objectVisibilityFlags = eRenderableFlag_VisibleInReflection, .clipPlanes = {}, .m_invert = true, - .m_disableOcclusionQueries = true, }); - m_reflectionRendererList.End( - eRenderListCompileFlag_Diffuse | eRenderListCompileFlag_Translucent | eRenderListCompileFlag_Decal | - eRenderListCompileFlag_Illumination); { - cmdBindRenderTargets(resolveReflectionBuffer.m_cmd.m_handle, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(resolveReflectionBuffer.m_cmd.m_handle, NULL); std::array rtBarriers = { RenderTargetBarrier{ resolveReflectionBuffer.m_buffer.m_colorBuffer.m_handle, RESOURCE_STATE_SHADER_RESOURCE, @@ -4526,7 +4157,7 @@ namespace hpl { { .m_invert = true }); { - cmdBindRenderTargets(resolveReflectionBuffer.m_cmd.m_handle, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(resolveReflectionBuffer.m_cmd.m_handle, NULL); std::array rtBarriers = { RenderTargetBarrier{ resolveReflectionBuffer.m_buffer.m_colorBuffer.m_handle, RESOURCE_STATE_RENDER_TARGET, @@ -4574,7 +4205,7 @@ namespace hpl { resolveReflectionBuffer.m_buffer.m_outputBuffer.m_handle, { .m_invert = true }); { - cmdBindRenderTargets(resolveReflectionBuffer.m_cmd.m_handle, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(resolveReflectionBuffer.m_cmd.m_handle, NULL); std::array rtBarriers = { RenderTargetBarrier{ resolveReflectionBuffer.m_buffer.m_outputBuffer.m_handle, RESOURCE_STATE_RENDER_TARGET, @@ -4605,26 +4236,11 @@ namespace hpl { switch (pMaterial->Descriptor().m_id) { case MaterialID::Translucent: { - DrawPacket drawPacket; - if (isParticleEmitter) { - std::array targets = { eVertexBufferElement_Position, - eVertexBufferElement_Texture0, - eVertexBufferElement_Color0 }; - drawPacket = translucencyItem->ResolveDrawPacket(frame, targets); - } else { - std::array targets = { eVertexBufferElement_Position, - eVertexBufferElement_Texture0, - eVertexBufferElement_Normal, - eVertexBufferElement_Texture1Tangent, - eVertexBufferElement_Color0 }; - drawPacket = translucencyItem->ResolveDrawPacket(frame, targets); - } - if (drawPacket.m_type == DrawPacket::Unknown || - drawPacket.numberOfIndecies() == 0) { + DrawPacket drawPacket = translucencyItem->ResolveDrawPacket(frame); + if (drawPacket.m_type == DrawPacket::Unknown || drawPacket.numberOfIndecies() == 0) { break; } - uint32_t instance = cmdBindMaterialAndObject( frame.m_cmd, frame, pMaterial, translucencyItem, std::optional{ pMatrix ? *pMatrix : cMatrixf::Identity }); materialConst.objectId = instance; @@ -4647,8 +4263,20 @@ namespace hpl { : m_materialTranslucencyPass.m_pipelines[translucencyBlendTable[pMaterial->GetBlendMode()]][key.m_id] .m_handle)); } + if (isParticleEmitter) { + std::array targets = { eVertexBufferElement_Position, + eVertexBufferElement_Texture0, + eVertexBufferElement_Color0 }; + DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &drawPacket, targets); + } else { + std::array targets = { eVertexBufferElement_Position, + eVertexBufferElement_Texture0, + eVertexBufferElement_Normal, + eVertexBufferElement_Texture1Tangent, + eVertexBufferElement_Color0 }; + DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &drawPacket, targets); + } - DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &drawPacket); materialConst.m_options = (isFogActive ? TranslucencyFlags::UseFog : 0) | (isRefraction ? TranslucencyFlags::UseRefractionTrans : 0) | @@ -4677,7 +4305,7 @@ namespace hpl { eVertexBufferElement_Normal, eVertexBufferElement_Texture1Tangent, eVertexBufferElement_Color0 }; - DrawPacket packet = translucencyItem->ResolveDrawPacket(frame, targets); + DrawPacket packet = translucencyItem->ResolveDrawPacket(frame); if (packet.m_type == DrawPacket::Unknown) { break; } @@ -4693,7 +4321,7 @@ namespace hpl { key.m_field.m_hasDepthTest = pMaterial->GetDepthTest(); // LegacyVertexBuffer::cmdBindGeometry(frame.m_cmd, frame.m_resourcePool, binding); - DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &packet, targets); cmdBindPipeline(frame.m_cmd, m_materialTranslucencyPass.m_waterPipeline[key.m_id].m_handle); uint32_t instance = cmdBindMaterialAndObject( frame.m_cmd, frame, pMaterial, translucencyItem, std::optional{ pMatrix ? *pMatrix : cMatrixf::Identity }); @@ -4723,7 +4351,7 @@ namespace hpl { m_debug->flush(frame, frame.m_cmd, viewport, *apFrustum, currentGBuffer.m_outputBuffer, currentGBuffer.m_depthBuffer); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ currentGBuffer.m_outputBuffer.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, }; diff --git a/HPL2/sources/graphics/RendererForwardPlus.cpp b/HPL2/sources/graphics/RendererForwardPlus.cpp deleted file mode 100644 index 342dcc61d..000000000 --- a/HPL2/sources/graphics/RendererForwardPlus.cpp +++ /dev/null @@ -1,876 +0,0 @@ -#include "graphics/RendererForwardPlus.h" - -#include "graphics/Color.h" -#include "graphics/ForgeHandles.h" -#include "graphics/ForgeRenderer.h" -#include "graphics/ForwardResources.h" -#include "graphics/GraphicsAllocator.h" -#include "graphics/GraphicsTypes.h" -#include "graphics/IndexPool.h" -#include "graphics/Material.h" -#include "graphics/Renderable.h" -#include "graphics/Renderer.h" -#include "graphics/TextureDescriptorPool.h" -#include "scene/Light.h" -#include "scene/RenderableContainer.h" - -#include "Common_3/Utilities/Math/MathTypes.h" -#include "Common_3/Resources/ResourceLoader/Interfaces/IResourceLoader.h" -#include "Common_3/Graphics/Interfaces/IGraphics.h" -#include "FixPreprocessor.h" -#include "tinyimageformat_base.h" -#include -#include -#include - -namespace hpl { - - namespace detail { - uint32_t resolveTextureFilterGroup(cMaterial::TextureAntistropy anisotropy, eTextureWrap wrap, eTextureFilter filter) { - const uint32_t anisotropyGroup = - (static_cast(eTextureFilter_LastEnum) * static_cast(eTextureWrap_LastEnum)) * - static_cast(anisotropy); - return anisotropyGroup + - ((static_cast(wrap) * static_cast(eTextureFilter_LastEnum)) + static_cast(filter)); - } - } - - SharedRenderTarget RendererForwardPlus::GetOutputImage(uint32_t frameIndex, cViewport& viewport) { - auto sharedData = m_boundViewportData.resolve(viewport); - if (!sharedData) { - return SharedRenderTarget(); - } - return sharedData->m_outputBuffer[frameIndex]; - } - - RendererForwardPlus::RendererForwardPlus(cGraphics* apGraphics, cResources* apResources, std::shared_ptr debug) - : iRenderer("ForwardPlus", apGraphics, apResources), - m_opaqueMaterialPool(MaxOpaqueCount), - m_sceneDescriptorPool(ForgeRenderer::SwapChainLength, MaxTextureCount) { - auto* forgeRenderer = Interface::Get(); - - - // shaders - m_nearestClampSampler.Load(forgeRenderer->Rend(), [&](Sampler** sampler) { - SamplerDesc samplerDesc = {}; - samplerDesc.mMinFilter = FILTER_NEAREST; - samplerDesc.mMagFilter = FILTER_NEAREST; - samplerDesc.mMipMapMode = MIPMAP_MODE_NEAREST; - samplerDesc.mAddressU = ADDRESS_MODE_CLAMP_TO_BORDER; - samplerDesc.mAddressV = ADDRESS_MODE_CLAMP_TO_BORDER; - samplerDesc.mAddressW = ADDRESS_MODE_CLAMP_TO_BORDER; - addSampler(forgeRenderer->Rend(), &samplerDesc, sampler); - return true; - }); - - m_emptyTexture.Load([&](Texture** texture) { - TextureDesc textureDesc = {}; - textureDesc.mArraySize = 1; - textureDesc.mMipLevels = 1; - textureDesc.mDepth = 1; - textureDesc.mFormat = TinyImageFormat_R8G8B8A8_UNORM; - textureDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; - textureDesc.mWidth = 16; - textureDesc.mHeight = 16; - textureDesc.mSampleCount = SAMPLE_COUNT_1; - textureDesc.mStartState = RESOURCE_STATE_COMMON; - textureDesc.pName = "empty texture"; - TextureLoadDesc loadDesc = {}; - loadDesc.ppTexture = texture; - loadDesc.pDesc = &textureDesc; - addResource(&loadDesc, nullptr); - return true; - }); - - m_pointlightClusterShader.Load(forgeRenderer->Rend(), [&](Shader** shader) { - ShaderLoadDesc loadDesc = {}; - loadDesc.mStages[0].pFileName = "point_light_clusters.comp"; - addShader(forgeRenderer->Rend(), &loadDesc, shader); - return true; - }); - m_clearClusterShader.Load(forgeRenderer->Rend(), [&](Shader** shader) { - ShaderLoadDesc loadDesc = {}; - loadDesc.mStages[0].pFileName = "light_clusters_clear.comp"; - addShader(forgeRenderer->Rend(), &loadDesc, shader); - return true; - }); - m_diffuseShader.Load(forgeRenderer->Rend(), [&](Shader** shader) { - ShaderLoadDesc loadDesc = {}; - loadDesc.mStages[0].pFileName = "forward_diffuse.vert"; - loadDesc.mStages[1].pFileName = "forward_diffuse.frag"; - addShader(forgeRenderer->Rend(), &loadDesc, shader); - return true; - }); - - // Root signautres - m_diffuseRootSignature.Load(forgeRenderer->Rend(), [&](RootSignature** sig) { - ASSERT(m_diffuseShader.IsValid()); - std::array shaders = { m_diffuseShader.m_handle }; - Sampler* vbShadeSceneSamplers[] = { m_nearestClampSampler.m_handle }; - const char* vbShadeSceneSamplersNames[] = { "nearestClampSampler" }; - RootSignatureDesc rootSignatureDesc = {}; - rootSignatureDesc.ppShaders = shaders.data(); - rootSignatureDesc.mShaderCount = shaders.size(); - rootSignatureDesc.mStaticSamplerCount = std::size(vbShadeSceneSamplersNames); - rootSignatureDesc.ppStaticSamplers = vbShadeSceneSamplers; - rootSignatureDesc.ppStaticSamplerNames = vbShadeSceneSamplersNames; - addRootSignature(forgeRenderer->Rend(), &rootSignatureDesc, sig); - return true; - }); - m_lightClusterRootSignature.Load(forgeRenderer->Rend(), [&](RootSignature** sig) { - ASSERT(m_pointlightClusterShader.IsValid()); - ASSERT(m_clearClusterShader.IsValid()); - std::array shaders = { m_pointlightClusterShader.m_handle, m_clearClusterShader.m_handle }; - RootSignatureDesc rootSignatureDesc = {}; - rootSignatureDesc.ppShaders = shaders.data(); - rootSignatureDesc.mShaderCount = shaders.size(); - addRootSignature(forgeRenderer->Rend(), &rootSignatureDesc, sig); - return true; - }); - - // Indirect Argument signature - { - std::array indirectArgs = {}; - { - IndirectArgumentDescriptor arg{}; - arg.mType = INDIRECT_DRAW_INDEX; - indirectArgs[0] = arg; - } - CommandSignatureDesc vbPassDesc = { - m_diffuseRootSignature.m_handle, - indirectArgs.data(), - indirectArgs.size() }; - vbPassDesc.mPacked = true; - addIndirectCommandSignature(forgeRenderer->Rend(), &vbPassDesc, &m_cmdSignatureVBPass); - } - - for(auto& buffer: m_perFrameBuffer) { - buffer.Load([&](Buffer** buffer) { - BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER; - desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mDesc.mElementCount = 1; - desc.mDesc.mStructStride = sizeof(UniformPerFrameData); - desc.mDesc.mSize = sizeof(UniformPerFrameData); - desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; - desc.ppBuffer = buffer; - addResource(&desc, nullptr); - return true; - }); - } - for(size_t swapChainIndex = 0; swapChainIndex < ForgeRenderer::SwapChainLength; swapChainIndex++) { - m_indirectDrawArgsBuffer[swapChainIndex].Load([&](Buffer** buffer) { - BufferLoadDesc indirectBufferDesc = {}; - indirectBufferDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_INDIRECT_BUFFER | DESCRIPTOR_TYPE_BUFFER; - indirectBufferDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_TO_CPU; - indirectBufferDesc.mDesc.mElementCount = MaxIndirectDrawArgs; - indirectBufferDesc.mDesc.mStructStride = sizeof(IndirectDrawIndexArguments); - indirectBufferDesc.mDesc.mStartState = RESOURCE_STATE_SHADER_RESOURCE | RESOURCE_STATE_INDIRECT_ARGUMENT; - indirectBufferDesc.mDesc.mSize = indirectBufferDesc.mDesc.mElementCount * indirectBufferDesc.mDesc.mStructStride; - indirectBufferDesc.mDesc.pName = "Indirect Buffer"; - indirectBufferDesc.ppBuffer = buffer; - addResource(&indirectBufferDesc, NULL); - return true; - }); - m_opaqueMaterialBuffer.Load([&](Buffer** buffer) { - BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER; - desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; - desc.mDesc.mFirstElement = 0; - desc.mDesc.mElementCount = MaxOpaqueCount; - desc.mDesc.mStructStride = sizeof(resource::DiffuseMaterial); - desc.mDesc.mSize = desc.mDesc.mElementCount * desc.mDesc.mStructStride; - desc.ppBuffer = buffer; - addResource(&desc, nullptr); - return true; - }); - - m_objectUniformBuffer[swapChainIndex].Load([&](Buffer** buffer) { - BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER; - desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; - desc.mDesc.mFirstElement = 0; - desc.mDesc.mElementCount = MaxObjectUniforms; - desc.mDesc.mStructStride = sizeof(UniformObject); - desc.mDesc.mSize = desc.mDesc.mElementCount * desc.mDesc.mStructStride; - desc.ppBuffer = buffer; - addResource(&desc, nullptr); - return true; - }); - - m_lightClustersBuffer[swapChainIndex].Load([&](Buffer** buffer) { - BufferLoadDesc bufferDesc = {}; - bufferDesc.mDesc.mElementCount = LightClusterLightCount * LightClusterWidth * LightClusterHeight; - bufferDesc.mDesc.mSize = bufferDesc.mDesc.mElementCount * sizeof(uint32_t); - bufferDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER_RAW | DESCRIPTOR_TYPE_RW_BUFFER; - bufferDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; - bufferDesc.mDesc.mFirstElement = 0; - bufferDesc.mDesc.mStructStride = sizeof(uint32_t); - bufferDesc.mDesc.mStartState = RESOURCE_STATE_UNORDERED_ACCESS; - bufferDesc.mDesc.pName = "Light Cluster"; - bufferDesc.ppBuffer = buffer; - addResource(&bufferDesc, nullptr); - return true; - }); - - m_lightClusterCountBuffer[swapChainIndex].Load([&](Buffer** buffer) { - BufferLoadDesc bufferDesc = {}; - bufferDesc.mDesc.mElementCount = LightClusterWidth * LightClusterHeight; - bufferDesc.mDesc.mSize = bufferDesc.mDesc.mElementCount * sizeof(uint32_t); - bufferDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER_RAW | DESCRIPTOR_TYPE_RW_BUFFER; - bufferDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY; - bufferDesc.mDesc.mFirstElement = 0; - bufferDesc.mDesc.mStructStride = sizeof(uint32_t); - bufferDesc.mDesc.mStartState = RESOURCE_STATE_UNORDERED_ACCESS; - bufferDesc.pData = nullptr; - bufferDesc.mDesc.pName = "Light Cluster Count"; - bufferDesc.ppBuffer = buffer; - addResource(&bufferDesc, nullptr); - return true; - }); - m_pointLightBuffer[swapChainIndex].Load([&](Buffer** buffer) { - BufferLoadDesc bufferDesc = {}; - bufferDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER_RAW | DESCRIPTOR_TYPE_RW_BUFFER; - bufferDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - bufferDesc.mDesc.mFirstElement = 0; - bufferDesc.mDesc.mStructStride = sizeof(PointLightData); - bufferDesc.mDesc.mElementCount = PointLightCount; - bufferDesc.mDesc.mSize = bufferDesc.mDesc.mElementCount * bufferDesc.mDesc.mStructStride; - bufferDesc.mDesc.mStartState = RESOURCE_STATE_UNORDERED_ACCESS; - bufferDesc.pData = nullptr; - bufferDesc.mDesc.pName = "Point Light"; - bufferDesc.ppBuffer = buffer; - addResource(&bufferDesc, nullptr); - return true; - }); - } - - { - RasterizerStateDesc rasterizerStateDesc = {}; - rasterizerStateDesc.mCullMode = CULL_MODE_FRONT; - rasterizerStateDesc.mFrontFace = FRONT_FACE_CCW; - - VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY - vertexLayout.mBindingCount = 4; - vertexLayout.mBindings[0].mStride = sizeof(float3); - vertexLayout.mBindings[1].mStride = sizeof(float2); - vertexLayout.mBindings[2].mStride = sizeof(float3); - vertexLayout.mBindings[3].mStride = sizeof(float3); -#endif - vertexLayout.mAttribCount = 4; - vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; - vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; - vertexLayout.mAttribs[0].mBinding = 0; - vertexLayout.mAttribs[0].mLocation = 0; - vertexLayout.mAttribs[0].mOffset = 0; - - vertexLayout.mAttribs[1].mSemantic = SEMANTIC_TEXCOORD0; - vertexLayout.mAttribs[1].mFormat = TinyImageFormat_R32G32_SFLOAT; - vertexLayout.mAttribs[1].mBinding = 1; - vertexLayout.mAttribs[1].mLocation = 1; - vertexLayout.mAttribs[1].mOffset = 0; - - vertexLayout.mAttribs[2].mSemantic = SEMANTIC_NORMAL; - vertexLayout.mAttribs[2].mFormat = TinyImageFormat_R32G32B32_SFLOAT; - vertexLayout.mAttribs[2].mBinding = 2; - vertexLayout.mAttribs[2].mLocation = 2; - vertexLayout.mAttribs[2].mOffset = 0; - - vertexLayout.mAttribs[3].mSemantic = SEMANTIC_TANGENT; - vertexLayout.mAttribs[3].mFormat = TinyImageFormat_R32G32B32_SFLOAT; - vertexLayout.mAttribs[3].mBinding = 3; - vertexLayout.mAttribs[3].mLocation = 3; - vertexLayout.mAttribs[3].mOffset = 0; - std::array colorFormats = { ColorBufferFormat , TinyImageFormat_R32G32B32A32_SFLOAT}; - - DepthStateDesc depthStateDesc = {}; - depthStateDesc.mDepthTest = true; - depthStateDesc.mDepthWrite = true; - depthStateDesc.mDepthFunc = CMP_LEQUAL; - - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_GRAPHICS; - auto& pipelineSettings = pipelineDesc.mGraphicsDesc; - pipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; - pipelineSettings.mRenderTargetCount = colorFormats.size(); - pipelineSettings.pColorFormats = colorFormats.data(); - pipelineSettings.pDepthState = &depthStateDesc; - pipelineSettings.mSampleCount = SAMPLE_COUNT_1; - pipelineSettings.mDepthStencilFormat = DepthBufferFormat; - pipelineSettings.mSampleQuality = 0; - pipelineSettings.pRootSignature = m_diffuseRootSignature.m_handle; - pipelineSettings.pShaderProgram = m_diffuseShader.m_handle; - pipelineSettings.pRasterizerState = &rasterizerStateDesc; - pipelineSettings.pVertexLayout = &vertexLayout; - pipelineSettings.mSupportIndirectCommandBuffer = true; - - m_diffusePipeline.Load(forgeRenderer->Rend(), [&](Pipeline** pipeline) { - addPipeline(forgeRenderer->Rend(), &pipelineDesc, pipeline); - return true; - }); - } - - m_PointLightClusterPipeline.Load(forgeRenderer->Rend(), [&](Pipeline** pipeline) { - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_COMPUTE; - ComputePipelineDesc& computePipelineDesc = pipelineDesc.mComputeDesc; - computePipelineDesc.pShaderProgram = m_pointlightClusterShader.m_handle; - computePipelineDesc.pRootSignature = m_lightClusterRootSignature.m_handle; - addPipeline(forgeRenderer->Rend(), &pipelineDesc, pipeline); - return true; - }); - m_clearClusterPipeline.Load(forgeRenderer->Rend(), [&](Pipeline** pipeline) { - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_COMPUTE; - ComputePipelineDesc& computePipelineDesc = pipelineDesc.mComputeDesc; - computePipelineDesc.pShaderProgram = m_clearClusterShader.m_handle; - computePipelineDesc.pRootSignature = m_lightClusterRootSignature.m_handle; - addPipeline(forgeRenderer->Rend(), &pipelineDesc, pipeline); - return true; - }); - - m_opaqueBatchSet.Load(forgeRenderer->Rend(), [&](DescriptorSet** descSet) { - DescriptorSetDesc perFrameDescSet{ m_diffuseRootSignature.m_handle, - DESCRIPTOR_UPDATE_FREQ_PER_BATCH, - MaxMaterialSamplers }; - addDescriptorSet(forgeRenderer->Rend(), &perFrameDescSet, descSet); - return true; - }); - for (size_t antistropy = 0; antistropy < cMaterial::Antistropy_Count; antistropy++) { - for (size_t textureWrap = 0; textureWrap < eTextureWrap_LastEnum; textureWrap++) { - for (size_t textureFilter = 0; textureFilter < eTextureFilter_LastEnum; textureFilter++) { - uint32_t batchID = detail::resolveTextureFilterGroup( - static_cast(antistropy), - static_cast(textureWrap), - static_cast(textureFilter)); - m_batchSampler[batchID].Load(forgeRenderer->Rend(), [&](Sampler** sampler) { - SamplerDesc samplerDesc = {}; - switch (textureWrap) { - case eTextureWrap_Repeat: - samplerDesc.mAddressU = ADDRESS_MODE_REPEAT; - samplerDesc.mAddressV = ADDRESS_MODE_REPEAT; - samplerDesc.mAddressW = ADDRESS_MODE_REPEAT; - break; - case eTextureWrap_Clamp: - samplerDesc.mAddressU = ADDRESS_MODE_CLAMP_TO_EDGE; - samplerDesc.mAddressV = ADDRESS_MODE_CLAMP_TO_EDGE; - samplerDesc.mAddressW = ADDRESS_MODE_CLAMP_TO_EDGE; - break; - case eTextureWrap_ClampToBorder: - samplerDesc.mAddressU = ADDRESS_MODE_CLAMP_TO_BORDER; - samplerDesc.mAddressV = ADDRESS_MODE_CLAMP_TO_BORDER; - samplerDesc.mAddressW = ADDRESS_MODE_CLAMP_TO_BORDER; - break; - default: - ASSERT(false && "Invalid wrap mode"); - break; - } - switch (textureFilter) { - case eTextureFilter_Nearest: - samplerDesc.mMinFilter = FilterType::FILTER_NEAREST; - samplerDesc.mMagFilter = FilterType::FILTER_NEAREST; - samplerDesc.mMipMapMode = MipMapMode::MIPMAP_MODE_NEAREST; - break; - case eTextureFilter_Bilinear: - samplerDesc.mMinFilter = FilterType::FILTER_LINEAR; - samplerDesc.mMagFilter = FilterType::FILTER_LINEAR; - samplerDesc.mMipMapMode = MipMapMode::MIPMAP_MODE_NEAREST; - break; - case eTextureFilter_Trilinear: - samplerDesc.mMinFilter = FilterType::FILTER_LINEAR; - samplerDesc.mMagFilter = FilterType::FILTER_LINEAR; - samplerDesc.mMipMapMode = MipMapMode::MIPMAP_MODE_LINEAR; - break; - default: - ASSERT(false && "Invalid filter"); - break; - } - switch (antistropy) { - case cMaterial::Antistropy_8: - samplerDesc.mMaxAnisotropy = 8.0f; - break; - case cMaterial::Antistropy_16: - samplerDesc.mMaxAnisotropy = 16.0f; - break; - default: - break; - } - addSampler(forgeRenderer->Rend(), &samplerDesc, sampler); - return true; - }); - std::array params = { - DescriptorData {.pName = "materialSampler", .ppSamplers = &m_batchSampler[batchID].m_handle}, - }; - updateDescriptorSet( - forgeRenderer->Rend(), batchID, m_opaqueBatchSet.m_handle, params.size(), params.data()); - } - } - } - for (size_t swapChainIndex = 0; swapChainIndex < ForgeRenderer::SwapChainLength; swapChainIndex++) { - m_opaqueFrameSet[swapChainIndex].Load(forgeRenderer->Rend(), [&](DescriptorSet** descSet) { - DescriptorSetDesc perFrameDescSet{ m_diffuseRootSignature.m_handle, - DESCRIPTOR_UPDATE_FREQ_PER_FRAME, - MaxViewportFrameDescriptors }; - addDescriptorSet(forgeRenderer->Rend(), &perFrameDescSet, descSet); - return true; - }); - m_opaqueConstSet[swapChainIndex].Load(forgeRenderer->Rend(), [&](DescriptorSet** descriptorSet) { - DescriptorSetDesc constSetDesc{ m_diffuseRootSignature.m_handle, - DESCRIPTOR_UPDATE_FREQ_NONE, - 1 }; - addDescriptorSet(forgeRenderer->Rend(), &constSetDesc, descriptorSet); - return true; - }); - { - - std::array params = { - DescriptorData {.pName = "sceneObjects", .ppBuffers = &m_objectUniformBuffer[swapChainIndex].m_handle}, - DescriptorData {.pName = "opaqueMaterial", .ppBuffers = &m_opaqueMaterialBuffer.m_handle}, - }; - updateDescriptorSet( - forgeRenderer->Rend(), 0, m_opaqueConstSet[swapChainIndex].m_handle, params.size(), params.data()); - } - - - for (size_t i = 0; i < MaxViewportFrameDescriptors; i++) { - std::array params = { - DescriptorData {.pName = "pointLights", .ppBuffers = &m_pointLightBuffer[swapChainIndex].m_handle}, - DescriptorData {.pName = "lightClustersCount", .ppBuffers = &m_lightClusterCountBuffer[swapChainIndex].m_handle}, - DescriptorData {.pName = "lightClusters", .ppBuffers = &m_lightClustersBuffer[swapChainIndex].m_handle}, - DescriptorData {.pName = "perFrameConstants", .ppBuffers = &m_perFrameBuffer[i].m_handle}, - }; - updateDescriptorSet( - forgeRenderer->Rend(), i, m_opaqueFrameSet[swapChainIndex].m_handle, params.size(), params.data()); - } - - m_perFrameLightCluster[swapChainIndex].Load(forgeRenderer->Rend(), [&](DescriptorSet** descSet) { - DescriptorSetDesc perFrameDescSet{ m_lightClusterRootSignature.m_handle, - DESCRIPTOR_UPDATE_FREQ_PER_FRAME, - MaxViewportFrameDescriptors }; - addDescriptorSet(forgeRenderer->Rend(), &perFrameDescSet, descSet); - return true; - }); - for (size_t i = 0; i < MaxViewportFrameDescriptors; i++) { - std::array params = { - DescriptorData {.pName = "perFrameConstants", .ppBuffers = &m_perFrameBuffer[i].m_handle}, - DescriptorData {.pName = "pointLights", .ppBuffers = &m_pointLightBuffer[swapChainIndex].m_handle}, - DescriptorData {.pName = "lightClustersCount", .ppBuffers = &m_lightClusterCountBuffer[swapChainIndex].m_handle}, - DescriptorData {.pName = "lightClusters", .ppBuffers = &m_lightClustersBuffer[swapChainIndex].m_handle}, - }; - updateDescriptorSet( - forgeRenderer->Rend(), i, m_perFrameLightCluster[swapChainIndex].m_handle, params.size(), params.data()); - } - } - } - RendererForwardPlus::~RendererForwardPlus() { - } - - uint32_t RendererForwardPlus::resolveObjectId( - const ForgeRenderer::Frame& frame, - cMaterial* apMaterial, - iRenderable* apObject, - std::optional modelMatrix) { - uint32_t id = folly::hash::fnv32_buf( - reinterpret_cast(apObject), - sizeof(apObject), - modelMatrix.has_value() ? folly::hash::fnv32_buf(modelMatrix->v, sizeof(modelMatrix->v)) : folly::hash::fnv32_hash_start); - - auto objectLookup = m_objectDescriptorLookup.find(apObject); - auto& materialDesc = apMaterial->Descriptor(); - - - auto metaInfo = std::find_if(cMaterial::MaterialMetaTable.begin(), cMaterial::MaterialMetaTable.end(), [&](auto& info) { - return info.m_id == materialDesc.m_id; - }); - - const bool isFound = objectLookup != m_objectDescriptorLookup.end(); - uint32_t index = isFound ? objectLookup->second : m_objectIndex++; - if (!isFound) { - cMatrixf modelMat = modelMatrix.value_or(apObject->GetModelMatrixPtr() ? *apObject->GetModelMatrixPtr() : cMatrixf::Identity); - - UniformObject uniformObjectData = {}; - uniformObjectData.m_dissolveAmount = apObject->GetCoverageAmount(); - uniformObjectData.m_materialIndex = apMaterial->Index(); - uniformObjectData.m_modelMat = cMath::ToForgeMatrix4(modelMat); - uniformObjectData.m_invModelMat = cMath::ToForgeMatrix4(cMath::MatrixInverse(modelMat)); - uniformObjectData.m_lightLevel = 1.0f; - uniformObjectData.m_illuminationAmount = apObject->GetIlluminationAmount(); - uniformObjectData.m_materialIndex = resolveMaterialID(frame, apMaterial); - if(apMaterial) { - uniformObjectData.m_uvMat = cMath::ToForgeMatrix4(apMaterial->GetUvMatrix().GetTranspose()); - } else { - uniformObjectData.m_uvMat = Matrix4::identity(); - } - BufferUpdateDesc updateDesc = { m_objectUniformBuffer[frame.m_frameIndex].m_handle, - sizeof(UniformObject) * index }; - beginUpdateResource(&updateDesc); - (*reinterpret_cast(updateDesc.pMappedData)) = uniformObjectData; - endUpdateResource(&updateDesc, NULL); - - m_objectDescriptorLookup[apObject] = index; - } - return index; - } - void RendererForwardPlus::Draw( - Cmd* cmd, - const ForgeRenderer::Frame& frame, - cViewport& viewport, - float frameTime, - cFrustum* apFrustum, - cWorld* apWorld, - cRenderSettings* apSettings, - bool abSendFrameBufferToPostEffects) { - auto* forgeRenderer = Interface::Get(); - auto* graphicsAllocator = Interface::Get(); - // keep around for the moment ... - BeginRendering(frameTime, apFrustum, apWorld, apSettings, abSendFrameBufferToPostEffects); - - if (frame.m_currentFrame != m_activeFrame) { - m_objectIndex = 0; - m_sceneDescriptorPool.reset([&](TextureDescriptorPool::Action action, uint32_t slot, SharedTexture& texture) { - std::array params = { - DescriptorData {.pName = "sceneTextures", .mCount = 1, .mArrayOffset = slot, .ppTextures = (action == TextureDescriptorPool::Action::UpdateSlot ? &texture.m_handle: &m_emptyTexture.m_handle ) } - }; - updateDescriptorSet( - forgeRenderer->Rend(), - 0, - m_opaqueConstSet[frame.m_frameIndex].m_handle, - params.size(), - params.data()); - }); - m_objectDescriptorLookup.clear(); - m_activeFrame = frame.m_currentFrame; - } - const Matrix4 mainFrustumViewInvMat = inverse(apFrustum->GetViewMat()); - const Matrix4 mainFrustumViewMat = apFrustum->GetViewMat(); - const Matrix4 mainFrustumProjMat = apFrustum->GetProjectionMat(); - - auto common = m_boundViewportData.resolve(viewport); - if (!common || common->m_size != viewport.GetSizeU2()) { - auto viewportData = std::make_unique(); - viewportData->m_size = viewport.GetSizeU2(); - for (auto& buffer : viewportData->m_outputBuffer) { - buffer.Load(forgeRenderer->Rend(), [&](RenderTarget** target) { - ClearValue optimizedColorClearBlack = { { 0.0f, 0.0f, 0.0f, 0.0f } }; - RenderTargetDesc renderTargetDesc = {}; - renderTargetDesc.mArraySize = 1; - renderTargetDesc.mClearValue = optimizedColorClearBlack; - renderTargetDesc.mDepth = 1; - renderTargetDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; - renderTargetDesc.mWidth = viewportData->m_size.x; - renderTargetDesc.mHeight = viewportData->m_size.y; - renderTargetDesc.mSampleCount = SAMPLE_COUNT_1; - renderTargetDesc.mSampleQuality = 0; - renderTargetDesc.mStartState = RESOURCE_STATE_SHADER_RESOURCE; - renderTargetDesc.mFormat = TinyImageFormat_R8G8B8A8_UNORM; - renderTargetDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; - addRenderTarget(forgeRenderer->Rend(), &renderTargetDesc, target); - return true; - }); - } - for (auto& buffer : viewportData->m_depthBuffer) { - buffer.Load(forgeRenderer->Rend(), [&](RenderTarget** handle) { - RenderTargetDesc renderTargetDesc = {}; - renderTargetDesc.mArraySize = 1; - renderTargetDesc.mClearValue = { .depth = 1.0f, .stencil = 0 }; - renderTargetDesc.mDepth = 1; - renderTargetDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; - renderTargetDesc.mWidth = viewportData->m_size.x; - renderTargetDesc.mHeight = viewportData->m_size.y; - renderTargetDesc.mSampleCount = SAMPLE_COUNT_1; - renderTargetDesc.mSampleQuality = 0; - renderTargetDesc.mFormat = DepthBufferFormat; - renderTargetDesc.mStartState = RESOURCE_STATE_DEPTH_WRITE; - renderTargetDesc.pName = "Depth RT"; - addRenderTarget(forgeRenderer->Rend(), &renderTargetDesc, handle); - return true; - }); - } - for (auto& buffer : viewportData->m_testBuffer) { - buffer.Load(forgeRenderer->Rend(), [&](RenderTarget** handle) { - RenderTargetDesc renderTargetDesc = {}; - renderTargetDesc.mArraySize = 1; - renderTargetDesc.mClearValue = { .depth = 1.0f, .stencil = 0 }; - renderTargetDesc.mDepth = 1; - renderTargetDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; - renderTargetDesc.mWidth = viewportData->m_size.x; - renderTargetDesc.mHeight = viewportData->m_size.y; - renderTargetDesc.mSampleCount = SAMPLE_COUNT_1; - renderTargetDesc.mSampleQuality = 0; - renderTargetDesc.mFormat = TinyImageFormat_R32G32B32A32_SFLOAT; - renderTargetDesc.mStartState = RESOURCE_STATE_RENDER_TARGET; - addRenderTarget(forgeRenderer->Rend(), &renderTargetDesc, handle); - return true; - }); - } - common = m_boundViewportData.update(viewport, std::move(viewportData)); - } - uint32_t mainFrameIndex = updateFrameDescriptor(frame, frame.m_cmd, apWorld, { - .m_size = float2(common->m_size.x, common->m_size.y), - .m_viewMat = mainFrustumViewMat, - .m_projectionMat = mainFrustumProjMat - }); - - { - m_rendererList.BeginAndReset(frameTime, apFrustum); - auto* dynamicContainer = apWorld->GetRenderableContainer(eWorldContainerType_Dynamic); - auto* staticContainer = apWorld->GetRenderableContainer(eWorldContainerType_Static); - dynamicContainer->UpdateBeforeRendering(); - staticContainer->UpdateBeforeRendering(); - - auto prepareObjectHandler = [&](iRenderable* pObject) { - if (!rendering::detail::IsObjectIsVisible(pObject, eRenderableFlag_VisibleInNonReflection, {})) { - return; - } - m_rendererList.AddObject(pObject); - }; - rendering::detail::WalkAndPrepareRenderList(dynamicContainer, apFrustum, prepareObjectHandler, eRenderableFlag_VisibleInNonReflection); - rendering::detail::WalkAndPrepareRenderList(staticContainer, apFrustum, prepareObjectHandler, eRenderableFlag_VisibleInNonReflection); - m_rendererList.End( - eRenderListCompileFlag_Diffuse | eRenderListCompileFlag_Translucent | eRenderListCompileFlag_Decal | - eRenderListCompileFlag_Illumination | eRenderListCompileFlag_FogArea); - } - - // diffuse - struct IndirectDrawGroup { - size_t m_offset; - uint32_t m_count; - uint32_t m_batchID; - }; - std::vector diffuseFilterGroup; - { - std::vector renderables; - renderables.assign(m_rendererList.GetSolidObjects().begin(), m_rendererList.GetSolidObjects().end()); - std::sort(renderables.begin(), renderables.end(), [](iRenderable* objectA, iRenderable* objectB) { - cMaterial* pMatA = objectA->GetMaterial(); - cMaterial* pMatB = objectB->GetMaterial(); - uint32_t filterA = detail::resolveTextureFilterGroup( - pMatA->GetTextureAntistropy(), pMatA->GetTextureWrap(), pMatA->GetTextureFilter()); - - uint32_t filterB = detail::resolveTextureFilterGroup( - pMatB->GetTextureAntistropy(), pMatB->GetTextureWrap(), pMatB->GetTextureFilter()); - return filterA < filterB; - }); - - - auto isSameGroup = [](iRenderable* objectA, iRenderable* objectB) { - cMaterial* pMatA = objectA->GetMaterial(); - cMaterial* pMatB = objectB->GetMaterial(); - return pMatA->GetTextureAntistropy() == pMatB->GetTextureAntistropy() && - pMatA->GetTextureWrap() == pMatB->GetTextureWrap() && - pMatA->GetTextureFilter() == pMatB->GetTextureFilter(); - }; - - BufferUpdateDesc updateDesc = { m_indirectDrawArgsBuffer[frame.m_frameIndex].m_handle, - 0, - sizeof(IndirectDrawIndexArguments) * renderables.size()}; - beginUpdateResource(&updateDesc); - - auto it = renderables.begin(); - auto lastIt = renderables.begin(); - uint32_t index = 0; - uint32_t lastIndex = 0; - uint32_t lastBatchID = 0; - while(it != renderables.end()) { - lastIndex = index; - { - cMaterial* pMaterial = (*it)->GetMaterial(); - lastBatchID = detail::resolveTextureFilterGroup( - pMaterial->GetTextureAntistropy(), pMaterial->GetTextureWrap(), pMaterial->GetTextureFilter()); - } - do { - cMaterial* pMaterial = (*it)->GetMaterial(); - std::array targets = { eVertexBufferElement_Position, - eVertexBufferElement_Texture0, - eVertexBufferElement_Normal, - eVertexBufferElement_Texture1Tangent }; - DrawPacket packet = (*it)->ResolveDrawPacket(frame, targets); - if (pMaterial == nullptr || packet.m_type == DrawPacket::Unknown) { - continue; - } - ASSERT(pMaterial->Descriptor().m_id == MaterialID::SolidDiffuse && "Invalid material type"); - ASSERT(packet.m_type == DrawPacket::DrawPacketType::DrawGeometryset); - ASSERT(packet.m_unified.m_set == GraphicsAllocator::AllocationSet::OpaqueSet); - - auto& args = reinterpret_cast(updateDesc.pMappedData)[index++]; - args.mIndexCount = packet.m_unified.m_numIndices; - args.mStartIndex = packet.m_unified.m_subAllocation->indexOffset(); - args.mVertexOffset = packet.m_unified.m_subAllocation->vertextOffset(); - args.mStartInstance = resolveObjectId(frame, pMaterial, (*it), {}); // for DX12 this won't work - args.mInstanceCount = 1; - lastIt = it; - it++; - } while(it != renderables.end() && isSameGroup(*it, *lastIt)); - diffuseFilterGroup.push_back({lastIndex * sizeof(IndirectDrawArguments), index - lastIndex, lastBatchID}); - } - endUpdateResource(&updateDesc, nullptr); - } - - { - auto lights = m_rendererList.GetLights(); - uint32_t numPointLights = std::count_if(lights.begin(), lights.end(), [&](auto& light) { - return light->GetLightType() == eLightType_Point; - }); - { - uint32_t pointLightIndex = 0; - BufferUpdateDesc pointlightUpdateDesc = { m_pointLightBuffer[frame.m_frameIndex].m_handle, - 0, - sizeof(PointLightData) * numPointLights}; - beginUpdateResource(&pointlightUpdateDesc); - for(auto& light: m_rendererList.GetLights()) { - switch(light->GetLightType()) { - case eLightType_Point: { - m_pointLightAttenutation[frame.m_frameIndex][pointLightIndex] = light->GetFalloffMap()->GetTexture(); - auto& data = reinterpret_cast(pointlightUpdateDesc.pMappedData)[pointLightIndex++]; - const cColor color = light->GetDiffuseColor(); - data.m_radius = light->GetRadius(); - data.m_lightPos = v3ToF3(cMath::ToForgeVec3(light->GetWorldPosition())); - data.m_lightColor = float4(color.r, color.g, color.b, color.a); - break; - } - default: - break; - } - } - endUpdateResource(&pointlightUpdateDesc, nullptr); - } - cmdBindRenderTargets(cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); - - uint32_t rootConstantIndex = getDescriptorIndexFromName(m_lightClusterRootSignature.m_handle, "uRootConstants"); - cmdBindDescriptorSet(cmd, mainFrameIndex, m_perFrameLightCluster[frame.m_frameIndex].m_handle); - cmdBindPushConstants(frame.m_cmd, m_lightClusterRootSignature.m_handle, rootConstantIndex, &common->m_size); - cmdBindPipeline(cmd, m_clearClusterPipeline.m_handle); - cmdDispatch(cmd, 1, 1, 1); - { - std::array barriers = { BufferBarrier{ m_lightClusterCountBuffer[frame.m_frameIndex].m_handle, - RESOURCE_STATE_UNORDERED_ACCESS, - RESOURCE_STATE_UNORDERED_ACCESS } }; - cmdResourceBarrier( - cmd, barriers.size(), barriers.data(), 0, nullptr, 0, nullptr); - } - - cmdBindDescriptorSet(frame.m_cmd, mainFrameIndex, m_perFrameLightCluster[frame.m_frameIndex].m_handle); - cmdBindPipeline(cmd, m_PointLightClusterPipeline.m_handle); - cmdDispatch(cmd, numPointLights, 1, 1); - } - { - cmdBindRenderTargets(cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); - std::array bufferBarrier = { - BufferBarrier{ m_lightClustersBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_SHADER_RESOURCE }, - BufferBarrier{ m_lightClusterCountBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_SHADER_RESOURCE }, - BufferBarrier{ m_pointLightBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_UNORDERED_ACCESS, RESOURCE_STATE_SHADER_RESOURCE }, - }; - std::array rtBarriers = { - RenderTargetBarrier{ common->m_outputBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, - }; - cmdResourceBarrier( - cmd, bufferBarrier.size(), bufferBarrier.data(), 0, NULL, rtBarriers.size(), rtBarriers.data()); - } - { - auto diffuseItems = m_rendererList.GetRenderableItems(eRenderListType_Diffuse); - auto& opaqueSet = graphicsAllocator->resolveSet(GraphicsAllocator::AllocationSet::OpaqueSet); - - std::array semantics = { ShaderSemantic::SEMANTIC_POSITION, - ShaderSemantic::SEMANTIC_TEXCOORD0, - ShaderSemantic::SEMANTIC_NORMAL, - ShaderSemantic::SEMANTIC_NORMAL }; - cmdBeginDebugMarker(cmd, 0, 1, 0, "Forward Diffuse Pass"); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; - loadActions.mLoadActionsColor[1] = LOAD_ACTION_CLEAR; - loadActions.mClearColorValues[0] = { .r = 0.0f, .g = 0.0f, .b = 0.0f, .a = 0.0f }; - loadActions.mClearDepth = { .depth = 1.0f, .stencil = 0 }; - loadActions.mLoadActionDepth = LOAD_ACTION_CLEAR; - std::array targets = { - common->m_outputBuffer[frame.m_frameIndex].m_handle, - common->m_testBuffer[frame.m_frameIndex].m_handle - }; - cmdBindRenderTargets(cmd, targets.size(), targets.data(), common->m_depthBuffer[frame.m_frameIndex].m_handle, &loadActions, NULL, NULL, -1, -1); - cmdSetViewport(cmd, 0.0f, 0.0f, common->m_size.x, common->m_size.y, 0.0f, 1.0f); - cmdSetScissor(cmd, 0, 0, common->m_size.x, common->m_size.y); - - cmdBindPipeline(cmd, m_diffusePipeline.m_handle); - opaqueSet.cmdBindGeometrySet(cmd, semantics); - cmdBindIndexBuffer(cmd, opaqueSet.indexBuffer().m_handle, INDEX_TYPE_UINT32, 0); - cmdBindDescriptorSet(cmd, 0, m_opaqueConstSet[frame.m_frameIndex].m_handle); - cmdBindDescriptorSet(cmd, mainFrameIndex, m_opaqueFrameSet[frame.m_frameIndex].m_handle); - for(auto& group: diffuseFilterGroup) { - cmdBindDescriptorSet(cmd, group.m_batchID, m_opaqueBatchSet.m_handle); - cmdExecuteIndirect( - cmd, m_cmdSignatureVBPass, group.m_count, m_indirectDrawArgsBuffer[frame.m_frameIndex].m_handle, group.m_offset, nullptr, 0); - } - cmdEndDebugMarker(cmd); - } - { - cmdBindRenderTargets(cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); - std::array bufferBarrier = { - BufferBarrier{ m_lightClustersBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_UNORDERED_ACCESS }, - BufferBarrier{ m_lightClusterCountBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_UNORDERED_ACCESS }, - BufferBarrier{ m_pointLightBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_UNORDERED_ACCESS }, - }; - std::array rtBarriers = { - RenderTargetBarrier{ common->m_outputBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_RENDER_TARGET ,RESOURCE_STATE_SHADER_RESOURCE}, - }; - cmdResourceBarrier( - cmd, bufferBarrier.size(), bufferBarrier.data(), 0, NULL, rtBarriers.size(), rtBarriers.data()); - } - - } - - - uint32_t RendererForwardPlus::resolveMaterialID(const ForgeRenderer::Frame& frame,cMaterial* material) { - auto* forgeRenderer = Interface::Get(); - auto& sceneMaterial = m_sceneMaterial[material->Index()]; - if (sceneMaterial.m_material != material || - sceneMaterial.m_version != material->Generation()) { - - auto& descriptor = material->Descriptor(); - sceneMaterial.m_version = material->Generation(); - sceneMaterial.m_material = material; - - resource::visitTextures(sceneMaterial.m_resource, [&](eMaterialTexture texture, uint32_t slot) { - m_sceneDescriptorPool.dispose(slot); - }); - sceneMaterial.m_resource = hpl::resource::createMaterial(m_sceneDescriptorPool, material); - if(resource::DiffuseMaterial* mat = std::get_if(&sceneMaterial.m_resource)) { - sceneMaterial.m_slot = IndexPoolHandle(&m_opaqueMaterialPool); - BufferUpdateDesc updateDesc = { m_opaqueMaterialBuffer.m_handle, - sizeof(resource::DiffuseMaterial) * sceneMaterial.m_slot.get()}; - beginUpdateResource(&updateDesc); - (*reinterpret_cast(updateDesc.pMappedData)) = *mat; - endUpdateResource(&updateDesc, NULL); - } - - } - return sceneMaterial.m_slot.get(); - } - - uint32_t RendererForwardPlus::updateFrameDescriptor( const ForgeRenderer::Frame& frame, Cmd* cmd, cWorld* apWorld, const PerFrameOption& options) { - uint32_t index = m_frameIndex; - BufferUpdateDesc updatePerFrameConstantsDesc = { m_perFrameBuffer[index].m_handle, 0 }; - beginUpdateResource(&updatePerFrameConstantsDesc); - auto* uniformFrameData = reinterpret_cast(updatePerFrameConstantsDesc.pMappedData); - uniformFrameData->m_viewMatrix = options.m_viewMat; - uniformFrameData->m_invViewMatrix = inverse(options.m_viewMat); - uniformFrameData->m_projectionMatrix = options.m_projectionMat; - uniformFrameData->m_viewProjectionMatrix = options.m_projectionMat * options.m_viewMat; - - uniformFrameData->worldFogStart = apWorld->GetFogStart(); - uniformFrameData->worldFogLength = apWorld->GetFogEnd() - apWorld->GetFogStart(); - uniformFrameData->oneMinusFogAlpha = 1.0f - apWorld->GetFogColor().a; - uniformFrameData->fogFalloffExp = apWorld->GetFogFalloffExp(); - - uniformFrameData->m_invViewRotation = Matrix4(Matrix4::identity()).setUpper3x3(transpose(options.m_viewMat).getUpper3x3()); - uniformFrameData->viewTexel = float2(1.0f / options.m_size.x, 1.0f / options.m_size.y); - uniformFrameData->viewportSize = float2(options.m_size.x, options.m_size.y); - uniformFrameData->afT = GetTimeCount(); - const auto fogColor = apWorld->GetFogColor(); - uniformFrameData->fogColor = float4(fogColor.r, fogColor.g, fogColor.b, fogColor.a); - endUpdateResource(&updatePerFrameConstantsDesc, NULL); - m_frameIndex = (m_frameIndex + 1) % MaxViewportFrameDescriptors; - return index; - } -} // namespace hpl diff --git a/HPL2/sources/graphics/RendererWireFrame.cpp b/HPL2/sources/graphics/RendererWireFrame.cpp index 22af198f5..1af9d2409 100644 --- a/HPL2/sources/graphics/RendererWireFrame.cpp +++ b/HPL2/sources/graphics/RendererWireFrame.cpp @@ -82,7 +82,7 @@ namespace hpl { for (auto& buffer : m_frameBufferUniform) { buffer.Load([&](Buffer** buffer) { BufferLoadDesc desc = {}; - desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER; + desc.mDesc.mDescriptors = DESCRIPTOR_TYPE_BUFFER | DESCRIPTOR_TYPE_UNIFORM_BUFFER; desc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; desc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT; desc.mDesc.mFirstElement = 0; @@ -134,10 +134,8 @@ namespace hpl { m_pipeline.Load(forgeRenderer->Rend(), [&](Pipeline** pipline) { std::array colorFormats = { TinyImageFormat_R8G8B8A8_UNORM }; VertexLayout vertexLayout = {}; -#ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 1; vertexLayout.mBindings[0].mStride = sizeof(float3); -#endif vertexLayout.mAttribCount = 1; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -146,7 +144,7 @@ namespace hpl { vertexLayout.mAttribs[0].mOffset = 0; RasterizerStateDesc rasterizerStateDesc = {}; - rasterizerStateDesc.mCullMode = CULL_MODE_BOTH; + //rasterizerStateDesc.mCullMode = CULL_MODE_BOTH; rasterizerStateDesc.mFillMode = FILL_MODE_WIREFRAME; DepthStateDesc depthStateDesc = {}; @@ -160,11 +158,7 @@ namespace hpl { blendStateDesc.mSrcAlphaFactors[0] = BC_ONE; blendStateDesc.mDstAlphaFactors[0] = BC_ZERO; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; -#ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; -#else blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; -#endif blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -204,7 +198,7 @@ namespace hpl { uniformObjectData.m_modelMat = cMath::ToForgeMatrix4(modelMat); beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = uniformObjectData; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); m_objectDescriptorLookup[apObject] = index; } @@ -221,16 +215,15 @@ namespace hpl { void cRendererWireFrame::Draw( Cmd* cmd, - const ForgeRenderer::Frame& frame, + ForgeRenderer::Frame& frame, cViewport& viewport, float afFrameTime, cFrustum* apFrustum, cWorld* apWorld, - cRenderSettings* apSettings, - bool abSendFrameBufferToPostEffects) { + cRenderSettings* apSettings) { auto* forgeRenderer = Interface::Get(); // keep around for the moment ... - BeginRendering(afFrameTime, apFrustum, apWorld, apSettings, abSendFrameBufferToPostEffects); + BeginRendering(afFrameTime, apFrustum, apWorld, apSettings, false); if (frame.m_currentFrame != m_activeFrame) { m_objectIndex = 0; @@ -277,10 +270,10 @@ namespace hpl { m_rendererList.BeginAndReset(afFrameTime, apFrustum); std::array occlusionPlanes = {}; - rendering::detail::UpdateRenderListWalkAllNodesTestFrustumAndVisibility( - &m_rendererList, apFrustum, apWorld->GetRenderableContainer(eWorldContainerType_Static), occlusionPlanes, 0); - rendering::detail::UpdateRenderListWalkAllNodesTestFrustumAndVisibility( - &m_rendererList, apFrustum, apWorld->GetRenderableContainer(eWorldContainerType_Dynamic), occlusionPlanes, 0); + cRenderList::UpdateRenderListWalkAllNodesTestFrustumAndVisibility( + m_rendererList, *apFrustum, *apWorld->GetRenderableContainer(eWorldContainerType_Static)->GetRoot(), occlusionPlanes, 0); + cRenderList::UpdateRenderListWalkAllNodesTestFrustumAndVisibility( + m_rendererList, *apFrustum, *apWorld->GetRenderableContainer(eWorldContainerType_Dynamic)->GetRoot(), occlusionPlanes, 0); m_rendererList.End(eRenderListCompileFlag_Diffuse | eRenderListCompileFlag_Decal | eRenderListCompileFlag_Translucent); @@ -291,11 +284,11 @@ namespace hpl { PerFrameUniform uniformData; uniformData.m_viewProject = ((apFrustum->GetProjectionType() == eProjectionType_Perspective ? Matrix4::identity() : correctionMatrix) * matMainFrustumProj) * matMainFrustumView ; (*reinterpret_cast(updateDesc.pMappedData)) = uniformData; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ common->m_outputBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET, @@ -304,13 +297,19 @@ namespace hpl { cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } uint32_t rootConstantIndex = getDescriptorIndexFromName(m_rootSignature.m_handle, "rootConstant"); - std::array targets = { - common->m_outputBuffer[frame.m_frameIndex].m_handle, - }; - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; - loadActions.mClearColorValues[0] = ClearValue { .r = apSettings->mClearColor.r, .g = apSettings->mClearColor.g, .b = apSettings->mClearColor.b, .a = apSettings->mClearColor.a }; - cmdBindRenderTargets(frame.m_cmd, targets.size(), targets.data(), NULL, &loadActions, NULL, NULL, -1, -1); + // std::array targets = { + // common->m_outputBuffer[frame.m_frameIndex].m_handle, + // }; + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; + // loadActions.mClearColorValues[0] = ClearValue { .r = apSettings->mClearColor.r, .g = apSettings->mClearColor.g, .b = apSettings->mClearColor.b, .a = apSettings->mClearColor.a }; + // cmdBindRenderTargets(frame.m_cmd, targets.size(), targets.data(), NULL, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargetsDesc = {}; + bindRenderTargetsDesc.mRenderTargetCount = 1; + bindRenderTargetsDesc.mRenderTargets[0] = { .pRenderTarget = common->m_outputBuffer[frame.m_frameIndex].m_handle, .mLoadAction = LOAD_ACTION_CLEAR, .mClearValue = { .r = apSettings->mClearColor.r, .g = apSettings->mClearColor.g, .b = apSettings->mClearColor.b, .a = apSettings->mClearColor.a } }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargetsDesc); + cmdSetViewport(frame.m_cmd, 0.0f, 0.0f, static_cast(common->m_size.x), static_cast(common->m_size.y), 0.0f, 1.0f); cmdSetScissor(frame.m_cmd, 0, 0, common->m_size.x, common->m_size.y); @@ -320,13 +319,13 @@ namespace hpl { for (auto& diffuseItem : m_rendererList.GetRenderableItems(eRenderListType_Diffuse)) { cMaterial* pMaterial = diffuseItem->GetMaterial(); std::array targets = { eVertexBufferElement_Position }; - DrawPacket packet = diffuseItem->ResolveDrawPacket(frame, targets); + DrawPacket packet = diffuseItem->ResolveDrawPacket(frame); if (pMaterial == nullptr || packet.m_type == DrawPacket::Unknown) { continue; } ASSERT(pMaterial->Descriptor().m_id == MaterialID::SolidDiffuse && "Invalid material type"); - DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(frame.m_cmd, frame.m_resourcePool, &packet, targets); uint32_t objectIndex = prepareObjectData(frame, diffuseItem); cmdBindPushConstants(frame.m_cmd, m_rootSignature.m_handle, rootConstantIndex, &objectIndex); cmdDrawIndexed(frame.m_cmd, packet.numberOfIndecies(), 0, 0); @@ -354,7 +353,7 @@ namespace hpl { m_debug->flush(frame, frame.m_cmd, viewport, *apFrustum, common->m_outputBuffer[frame.m_frameIndex], invalidTarget); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd,NULL); std::array rtBarriers = { RenderTargetBarrier{ common->m_outputBuffer[frame.m_frameIndex].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE, diff --git a/HPL2/sources/graphics/TextureCreator.cpp b/HPL2/sources/graphics/TextureCreator.cpp index 24100e18c..5b4475450 100644 --- a/HPL2/sources/graphics/TextureCreator.cpp +++ b/HPL2/sources/graphics/TextureCreator.cpp @@ -19,6 +19,7 @@ #include "graphics/TextureCreator.h" +#include "Common_3/Graphics/Interfaces/IGraphics.h" #include "graphics/Image.h" #include "system/LowLevelSystem.h" @@ -78,7 +79,7 @@ namespace hpl { // Generate all the different sample collections TextureUpdateDesc update = {*ppTexture}; beginUpdateResource(&update); - + auto subResource = update.getSubresourceUpdateDesc(0, 0); for (size_t sample_num = 0; sample_num < vOffsetsVec.size(); ++sample_num) { //////////////////////////// // Fills a square "grid" size, and then normalizes each pos to be 0 - 1 @@ -139,13 +140,13 @@ namespace hpl { for (int depth = 0; depth < vTextureSize.z; ++depth) { int lOffset = depth * vTextureSize.x * vTextureSize.y * 4 + (int)sample_num * 4; - update.pMappedData[lOffset + 0] = static_cast(vOffsets[(depth * 2)].x * 255.0f); - update.pMappedData[lOffset + 1] = static_cast(vOffsets[(depth * 2)].y * 255.0f); - update.pMappedData[lOffset + 2] = static_cast(vOffsets[(depth * 2) + 1].x * 255.0f); - update.pMappedData[lOffset + 3] = static_cast(vOffsets[(depth * 2) + 1].y * 255.0f); + subResource.pMappedData[lOffset + 0] = static_cast(vOffsets[(depth * 2)].x * 255.0f); + subResource.pMappedData[lOffset + 1] = static_cast(vOffsets[(depth * 2)].y * 255.0f); + subResource.pMappedData[lOffset + 2] = static_cast(vOffsets[(depth * 2) + 1].x * 255.0f); + subResource.pMappedData[lOffset + 3] = static_cast(vOffsets[(depth * 2) + 1].y * 255.0f); } } - endUpdateResource(&update, nullptr); + endUpdateResource(&update); } void GenerateScatterDiskMap2D(int alSize, int alSamples, bool abSortSamples, Texture** ppTexture) { @@ -182,7 +183,7 @@ namespace hpl { textureLoadDesc.pDesc = &desc; addResource(&textureLoadDesc, nullptr); - TextureUpdateDesc update = {*ppTexture}; + TextureUpdateDesc update = {*ppTexture, 0, 1, 0, 1, RESOURCE_STATE_COMMON}; beginUpdateResource(&update); //////////////////////////// @@ -243,12 +244,13 @@ namespace hpl { /////////////////////////////// // Add the samples to the texture data + auto subResource = update.getSubresourceUpdateDesc(0, 0); for (int depth = 0; depth < vTextureSize.z; ++depth) { size_t lOffset = (depth * vTextureSize.x * vTextureSize.y) * 4 + (sample_num * 4); - update.pMappedData[lOffset + 0] = static_cast(vOffsets[(depth * 2)].x * 255.0f); - update.pMappedData[lOffset + 1] = static_cast(vOffsets[(depth * 2)].y * 255.0f); - update.pMappedData[lOffset + 2] = static_cast(vOffsets[(depth * 2) + 1].x * 255.0f); - update.pMappedData[lOffset + 3] = static_cast(vOffsets[(depth * 2) + 1].y * 255.0f); + subResource.pMappedData[lOffset + 0] = static_cast(vOffsets[(depth * 2)].x * 255.0f); + subResource.pMappedData[lOffset + 1] = static_cast(vOffsets[(depth * 2)].y * 255.0f); + subResource.pMappedData[lOffset + 2] = static_cast(vOffsets[(depth * 2) + 1].x * 255.0f); + subResource.pMappedData[lOffset + 3] = static_cast(vOffsets[(depth * 2) + 1].y * 255.0f); // unsigned char* pPixelData = &vTextureData[lOffset]; @@ -263,7 +265,7 @@ namespace hpl { // pPixelData[3] = (int)(vOffsets[lSample + 1].y * 255.0f); } } - endUpdateResource(&update, nullptr); + endUpdateResource(&update); } diff --git a/HPL2/sources/gui/Gui.cpp b/HPL2/sources/gui/Gui.cpp index cde9dda8d..cd854888b 100644 --- a/HPL2/sources/gui/Gui.cpp +++ b/HPL2/sources/gui/Gui.cpp @@ -377,7 +377,25 @@ namespace hpl { return pGfxElem; } - //----------------------------------------------------------------------- + cGuiGfxElement* cGui::CreateGfxTexture( cViewport* viewport, bool abAutoDestroyTexture, + eGuiMaterial aMaterial, + const cColor& aColor,bool abAddToList, + const cVector2f& avStartUV, const cVector2f& avEndUV, bool flipUVY) { + cGuiGfxElement *pGfxElem = hplNew( cGuiGfxElement, (this) ); + + if(flipUVY) { + pGfxElem->SetFlipUvYAxis(true); + } + pGfxElem->BindViewport(viewport); + pGfxElem->SetColor(aColor); + pGfxElem->SetMaterial(aMaterial); + pGfxElem->SetDestroyTexture(abAutoDestroyTexture); + + if(abAddToList) mlstGfxElements.push_back(pGfxElem); + + return pGfxElem; + + } cGuiGfxElement* cGui::CreateGfxTexture(Image* apTexture, bool abAutoDestroyTexture, eGuiMaterial aMaterial, diff --git a/HPL2/sources/gui/GuiGfxElement.cpp b/HPL2/sources/gui/GuiGfxElement.cpp index fa2b5b25a..f40330b5a 100644 --- a/HPL2/sources/gui/GuiGfxElement.cpp +++ b/HPL2/sources/gui/GuiGfxElement.cpp @@ -248,8 +248,18 @@ namespace hpl { ++mlTextureNum; } - - //--------------------------------------------------- + void cGuiGfxElement::BindViewport(cViewport* viewport, const cVector2f& avStartUV, const cVector2f& avEndUV) { + if(viewport) { + m_viewportHandler = cViewport::ViewportBeforeDraw::Handler([&, viewport, avStartUV, avEndUV](ForgeRenderer::Frame* frame) { + mlTextureNum = 0; + AddTexture(viewport->GetImage(*frame).get(), avStartUV, avEndUV); + }); + viewport->ConnectBeforeDraw(m_viewportHandler); + } else { + m_viewportHandler.Disconnect(); + } + + } void cGuiGfxElement::AddTexture(Image* apTexture, const cVector2f& avStartUV, const cVector2f& avEndUV) { @@ -342,7 +352,6 @@ namespace hpl { for(int i=0; i<4; ++i) mvVtx[i].col = aColor; } - //----------------------------------------------------------------------- void cGuiGfxElement::SetFlipUvYAxis(bool abX) { diff --git a/HPL2/sources/gui/GuiSet.cpp b/HPL2/sources/gui/GuiSet.cpp index 04d43d2b2..a8c5a0fcc 100644 --- a/HPL2/sources/gui/GuiSet.cpp +++ b/HPL2/sources/gui/GuiSet.cpp @@ -22,6 +22,7 @@ #include "Common_3/Graphics/Interfaces/IGraphics.h" #include "graphics/Color.h" #include "graphics/Enum.h" +#include "graphics/GraphicsAllocator.h" #include "graphics/RenderTarget.h" #include "gui/GuiTypes.h" #include "math/Math.h" @@ -29,52 +30,52 @@ #include "system/LowLevelSystem.h" #include "system/String.h" -#include "graphics/LowLevelGraphics.h" -#include "graphics/Graphics.h" #include "graphics/FontData.h" +#include "graphics/Graphics.h" +#include "graphics/LowLevelGraphics.h" -#include "resources/Resources.h" -#include "resources/TextureManager.h" -#include "resources/ImageManager.h" -#include "graphics/FrameSubImage.h" #include "graphics/FrameBitmap.h" +#include "graphics/FrameSubImage.h" #include "resources/FileSearcher.h" +#include "resources/ImageManager.h" +#include "resources/Resources.h" +#include "resources/TextureManager.h" -#include "scene/Scene.h" #include "scene/Camera.h" +#include "scene/Scene.h" #include "input/Input.h" #include "input/Keyboard.h" #include "gui/Gui.h" -#include "gui/GuiSkin.h" -#include "gui/Widget.h" -#include "gui/GuiMaterial.h" #include "gui/GuiGfxElement.h" +#include "gui/GuiMaterial.h" #include "gui/GuiPopUp.h" +#include "gui/GuiSkin.h" +#include "gui/Widget.h" -#include "gui/GuiPopUpMessageBox.h" -#include "gui/GuiPopUpFilePicker.h" #include "gui/GuiPopUpColorPicker.h" +#include "gui/GuiPopUpFilePicker.h" +#include "gui/GuiPopUpMessageBox.h" #include "gui/GuiPopUpUIKeyboard.h" -#include "gui/WidgetWindow.h" -#include "gui/WidgetFrame.h" #include "gui/WidgetButton.h" -#include "gui/WidgetLabel.h" -#include "gui/WidgetSlider.h" -#include "gui/WidgetTextBox.h" #include "gui/WidgetCheckBox.h" -#include "gui/WidgetImage.h" -#include "gui/WidgetListBox.h" -#include "gui/WidgetMultiPropertyListBox.h" #include "gui/WidgetComboBox.h" -#include "gui/WidgetMenuItem.h" #include "gui/WidgetContextMenu.h" +#include "gui/WidgetDummy.h" +#include "gui/WidgetFrame.h" +#include "gui/WidgetGroup.h" +#include "gui/WidgetImage.h" +#include "gui/WidgetLabel.h" +#include "gui/WidgetListBox.h" #include "gui/WidgetMainMenu.h" +#include "gui/WidgetMenuItem.h" +#include "gui/WidgetMultiPropertyListBox.h" +#include "gui/WidgetSlider.h" #include "gui/WidgetTabFrame.h" -#include "gui/WidgetGroup.h" -#include "gui/WidgetDummy.h" +#include "gui/WidgetTextBox.h" +#include "gui/WidgetWindow.h" #include #include @@ -87,46 +88,37 @@ namespace hpl { - namespace gui { - struct UniformBlock { - mat4 mvp; - float4 clipPlanes[4]; + namespace gui { + struct UniformBlock { + mat4 mvp; + float4 clipPlanes[4]; uint32_t textureConfig; - }; - - struct PositionTexColor { - float3 position; - float2 texCoord; - float4 color; - }; - - enum TextureConfiguration { - GUI_TEXTURE_CONFIG_NONE = 0, - GUI_TEXTURE_CONFIG_DIFFUSE = 1 << 0, - GUI_TEXTURE_CONFIG_CLIP = 1 << 1, - }; - - static std::array GuiUniformDescriptorSet{}; - static std::array, ForgeRenderer::SwapChainLength> GuiTextures{}; + }; + + struct PositionTexColor { + float3 position; + float2 texCoord; + float4 color; + }; + + enum TextureConfiguration { + GUI_TEXTURE_CONFIG_NONE = 0, + GUI_TEXTURE_CONFIG_DIFFUSE = 1 << 0, + GUI_TEXTURE_CONFIG_CLIP = 1 << 1, + }; + + static std::array GuiUniformDescriptorSet{}; + static std::array, ForgeRenderer::SwapChainLength> GuiTextures{}; static RootSignature* GuiRootSignatnre = nullptr; - - #ifdef USE_THE_FORGE_LEGACY - static GPURingBuffer* GuiUniformRingBuffer = nullptr; - static GPURingBuffer* GuiVertexRingBuffer = nullptr; - static GPURingBuffer* GuiIndexRingBuffer = nullptr; - #else - static GPURingBuffer GuiUniformRingBuffer {}; - static GPURingBuffer GuiVertexRingBuffer{}; - static GPURingBuffer GuiIndexRingBuffer{}; - #endif + static GPURingBuffer GuiUniformRingBuffer{}; static Sampler* GuiSampler = nullptr; static uint32_t descriptorIndex = 0; - static std::array GuiPipeline = {}; - static std::array GuiPipeline3D = {}; - static Shader* GuiShader = nullptr; + static std::array GuiPipeline = {}; + static std::array GuiPipeline3D = {}; + static Shader* GuiShader = nullptr; - void InitializeGui(ForgeRenderer& pipeline) { + void InitializeGui(ForgeRenderer& pipeline) { { SamplerDesc samplerDesc = {}; samplerDesc.mMinFilter = FILTER_LINEAR; @@ -139,2618 +131,2357 @@ namespace hpl { samplerDesc.mAddressW = ADDRESS_MODE_CLAMP_TO_EDGE; addSampler(pipeline.Rend(), &samplerDesc, &GuiSampler); } - { - BufferDesc desc = {}; - desc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER; - desc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mSize = GUI_STREAM_BUFFER_VB_SIZE * sizeof(PositionTexColor); - desc.pName = "GUI Vertex Buffer"; - - addGPURingBuffer(pipeline.Rend(), &desc, &GuiVertexRingBuffer); - } - { - BufferDesc desc = {}; - desc.mDescriptors = DESCRIPTOR_TYPE_INDEX_BUFFER; - desc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU; - desc.mSize = GUI_STREAM_BUFFER_IB_SIZE * sizeof(uint32_t); - desc.pName = "GUI Index Buffer"; - addGPURingBuffer(pipeline.Rend(), &desc, &GuiIndexRingBuffer); - } - ShaderLoadDesc loadDesc = {}; - loadDesc.mStages[0].pFileName = "gui.vert"; - loadDesc.mStages[1].pFileName = "gui.frag"; - addShader(pipeline.Rend(), &loadDesc, &GuiShader); + ShaderLoadDesc loadDesc = {}; + loadDesc.mStages[0].pFileName = "gui.vert"; + loadDesc.mStages[1].pFileName = "gui.frag"; + addShader(pipeline.Rend(), &loadDesc, &GuiShader); std::array guiSamplersNames = { "diffuseSampler" }; std::array guiSamplers = { GuiSampler }; - std::array guiRootShaders = {GuiShader}; + std::array guiRootShaders = { GuiShader }; - RootSignatureDesc rootSignatureDesc = {}; - rootSignatureDesc.ppShaders = guiRootShaders.data(); - rootSignatureDesc.mShaderCount = guiRootShaders.size(); - rootSignatureDesc.ppStaticSamplers = guiSamplers.data(); + RootSignatureDesc rootSignatureDesc = {}; + rootSignatureDesc.ppShaders = guiRootShaders.data(); + rootSignatureDesc.mShaderCount = guiRootShaders.size(); + rootSignatureDesc.ppStaticSamplers = guiSamplers.data(); rootSignatureDesc.ppStaticSamplerNames = guiSamplersNames.data(); - rootSignatureDesc.mStaticSamplerCount = guiSamplersNames.size(); - addRootSignature(pipeline.Rend(), &rootSignatureDesc, &GuiRootSignatnre); - - for(auto& set: GuiUniformDescriptorSet) { - DescriptorSetDesc setDesc{}; - setDesc.pRootSignature = GuiRootSignatnre; - setDesc.mUpdateFrequency = DESCRIPTOR_UPDATE_FREQ_PER_BATCH; - setDesc.mMaxSets = MAX_GUI_DRAW_CALLS; - addDescriptorSet(pipeline.Rend(), &setDesc, &set); - } - - { - //layout and pipeline for sphere draw - VertexLayout vertexLayout = {}; - vertexLayout.mAttribCount = 3; - #ifndef USE_THE_FORGE_LEGACY - vertexLayout.mBindingCount = 3; - vertexLayout.mBindings[0].mStride = sizeof(float3); - vertexLayout.mBindings[1].mStride = sizeof(float2); - vertexLayout.mBindings[2].mStride = sizeof(float3); - #endif + rootSignatureDesc.mStaticSamplerCount = guiSamplersNames.size(); + addRootSignature(pipeline.Rend(), &rootSignatureDesc, &GuiRootSignatnre); + + for (auto& set : GuiUniformDescriptorSet) { + DescriptorSetDesc setDesc{}; + setDesc.pRootSignature = GuiRootSignatnre; + setDesc.mUpdateFrequency = DESCRIPTOR_UPDATE_FREQ_PER_BATCH; + setDesc.mMaxSets = MAX_GUI_DRAW_CALLS; + addDescriptorSet(pipeline.Rend(), &setDesc, &set); + } + + { + // layout and pipeline for sphere draw + VertexLayout vertexLayout = {}; + vertexLayout.mAttribCount = 3; + vertexLayout.mBindingCount = 1; + vertexLayout.mBindings[0].mStride = sizeof(float3) + sizeof(float2) + sizeof(float4); + vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; - vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; - vertexLayout.mAttribs[0].mBinding = 0; - vertexLayout.mAttribs[0].mLocation = 0; - vertexLayout.mAttribs[0].mOffset = 0; - - vertexLayout.mAttribs[1].mSemantic = SEMANTIC_TEXCOORD0; - vertexLayout.mAttribs[1].mFormat = TinyImageFormat_R32G32_SFLOAT; - vertexLayout.mAttribs[1].mBinding = 0; - vertexLayout.mAttribs[1].mLocation = 1; - vertexLayout.mAttribs[1].mOffset = sizeof(float) * 3; - - vertexLayout.mAttribs[2].mSemantic = SEMANTIC_COLOR; - vertexLayout.mAttribs[2].mFormat = TinyImageFormat_R32G32B32A32_SFLOAT; - vertexLayout.mAttribs[2].mBinding = 0; - vertexLayout.mAttribs[2].mLocation = 2; - vertexLayout.mAttribs[2].mOffset = sizeof(float) * 3 + sizeof(float) * 2; - - RasterizerStateDesc rasterizerStateDesc = {}; - rasterizerStateDesc.mCullMode = CULL_MODE_NONE; - - DepthStateDesc depthStateDesc = {}; - depthStateDesc.mDepthTest = false; - depthStateDesc.mDepthWrite = false; - - TinyImageFormat inputFormat = TinyImageFormat_R8G8B8A8_UNORM; - PipelineDesc pipelineDesc = {}; - pipelineDesc.mType = PIPELINE_TYPE_GRAPHICS; - auto& pipelineSettings = pipelineDesc.mGraphicsDesc; - pipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; - pipelineSettings.mRenderTargetCount = 1; - pipelineSettings.pDepthState = &depthStateDesc; - pipelineSettings.pColorFormats = &inputFormat; - pipelineSettings.mSampleCount = SAMPLE_COUNT_1; - pipelineSettings.mSampleQuality = 0; - pipelineSettings.pRootSignature = GuiRootSignatnre; - pipelineSettings.pShaderProgram = GuiShader; - pipelineSettings.pRasterizerState = &rasterizerStateDesc; - pipelineSettings.pVertexLayout = &vertexLayout; - - auto materialBlendFunc = [](BlendConstant srcColor, BlendConstant destColor, BlendConstant srcAlpha, BlendConstant destAlpha) { - BlendStateDesc blendStateAddDesc = {}; - blendStateAddDesc.mSrcFactors[0] = srcColor; - blendStateAddDesc.mDstFactors[0] = destColor; - blendStateAddDesc.mBlendModes[0] = BM_ADD; - blendStateAddDesc.mSrcAlphaFactors[0] = srcAlpha; - blendStateAddDesc.mDstAlphaFactors[0] = destAlpha; - blendStateAddDesc.mBlendAlphaModes[0] = BM_ADD; - #ifdef USE_THE_FORGE_LEGACY - blendStateAddDesc.mMasks[0] = ALL; - #else - blendStateAddDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; - #endif - blendStateAddDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; - blendStateAddDesc.mIndependentBlend = false; - - return blendStateAddDesc; - }; - - std::array blendStateDesc = {}; - blendStateDesc[eGuiMaterial_Diffuse] = materialBlendFunc(BC_ONE, BC_ZERO, BC_ONE, BC_ZERO); - blendStateDesc[eGuiMaterial_PremulAlpha] = materialBlendFunc(BC_ONE, BC_ONE_MINUS_SRC_ALPHA, BC_ONE, BC_ONE_MINUS_SRC_ALPHA); - blendStateDesc[eGuiMaterial_Modulative] = materialBlendFunc(BC_DST_COLOR, BC_ZERO, BC_DST_ALPHA, BC_ZERO); - blendStateDesc[eGuiMaterial_Additive] = materialBlendFunc(BC_ONE, BC_ONE, BC_ONE, BC_ONE); - blendStateDesc[eGuiMaterial_FontNormal] = materialBlendFunc(BC_SRC_ALPHA, BC_ONE_MINUS_SRC_ALPHA, BC_SRC_ALPHA, BC_ONE_MINUS_SRC_ALPHA); - blendStateDesc[eGuiMaterial_Alpha] = materialBlendFunc(BC_SRC_ALPHA, BC_ONE_MINUS_SRC_ALPHA, BC_SRC_ALPHA, BC_ONE_MINUS_SRC_ALPHA); - - for(size_t i = 0; i < blendStateDesc.size(); i++) { - pipelineSettings.pBlendState = &blendStateDesc[i]; - addPipeline(pipeline.Rend(), &pipelineDesc, &GuiPipeline[i]); - } - - depthStateDesc.mDepthTest = true; - depthStateDesc.mDepthFunc = CMP_LEQUAL; - for(size_t i = 0; i < blendStateDesc.size(); i++) { - pipelineSettings.pBlendState = &blendStateDesc[i]; - addPipeline(pipeline.Rend(), &pipelineDesc, &GuiPipeline3D[i]); - } - - } - - addUniformGPURingBuffer(pipeline.Rend(), sizeof(UniformBlock) * MAX_GUI_DRAW_CALLS, &GuiUniformRingBuffer, true); - } - - void exitGui() { - - } - } - - static bool SortWidget_Z (const iWidget* apWidgetA, const iWidget* apWidgetB) - { - float fAZ, fBZ; - - fAZ = ((iWidget*)apWidgetA)->GetGlobalPosition().z; - fBZ = ((iWidget*)apWidgetB)->GetGlobalPosition().z; - return (fAZ > fBZ); - } - - bool cGuiRenderObjectCompare::operator()( const cGuiRenderObject& aObjectA, - const cGuiRenderObject& aObjectB) const - { - //Z - float fZA = aObjectA.mvPos.z; - float fZB = aObjectB.mvPos.z; - if(fZA != fZB) - { - return fZA < fZB; - } - - //Clip Region - cGuiClipRegion *pClipA = aObjectA.mpClipRegion; - cGuiClipRegion *pClipB = aObjectB.mpClipRegion; - if(pClipA != pClipB) - { - return pClipA > pClipB; - } - - //Material - eGuiMaterial pMaterialA = aObjectA.mpCustomMaterial != eGuiMaterial::eGuiMaterial_LastEnum ? aObjectA.mpCustomMaterial : aObjectA.mpGfx->m_materialType; - eGuiMaterial pMaterialB = aObjectB.mpCustomMaterial != eGuiMaterial::eGuiMaterial_LastEnum ? aObjectB.mpCustomMaterial : aObjectB.mpGfx->m_materialType; - if(pMaterialA != pMaterialB) - { - return pMaterialA > pMaterialB; - } - - //Texture - Image* pTextureA = aObjectA.mpGfx->mvTextures[0]; - Image* pTextureB = aObjectB.mpGfx->mvTextures[0]; - if(pTextureA != pTextureB) - { - return pTextureA > pTextureB; - } - - //Equal - return false; - - } - - cGuiClipRegion::~cGuiClipRegion() - { - Clear(); - } - - void cGuiClipRegion::Clear() - { - STLDeleteAll(mlstChildren); - } - - cGuiClipRegion* cGuiClipRegion::CreateChild(const cVector3f &avPos, const cVector2f &avSize) - { - cGuiClipRegion *pRegion = hplNew( cGuiClipRegion, () ); - - if(mRect.w <0) - { - pRegion->mRect = cRect2f(cVector2f(avPos.x, avPos.y),avSize); - } - else - { - cRect2f t = cRect2f(cVector2f(avPos.x, avPos.y),avSize); - pRegion->mRect = cMath::GetClipRect(t, mRect); - if(pRegion->mRect.w < 0 ) pRegion->mRect.w = 0; - if(pRegion->mRect.h < 0 ) pRegion->mRect.h = 0; - } - - - mlstChildren.push_back(pRegion); - - return pRegion; - } - - - cGuiGlobalShortcut::cGuiGlobalShortcut(int alKeyModifiers, eKey aKey, iWidget* apWidget, eGuiMessage aMessage, bool abBypassVisibility, bool abBypassEnabled) - { - mbEnabled = true; - mbBypassVisibility = abBypassVisibility; - mbBypassEnabled = abBypassEnabled; - - mKey = cKeyPress(aKey, 0, alKeyModifiers); - mpWidget = apWidget; - mMessage = aMessage; - } - - //----------------------------------------------------------------------- - - bool cGuiGlobalShortcut::ProcessKeyPress(const cKeyPress& aKey) - { - if(IsEnabled()==false || - mKey.mlModifier != aKey.mlModifier || - mKey.mKey != aKey.mKey) - return false; - - return Exec(); - } - - //----------------------------------------------------------------------- - - bool cGuiGlobalShortcut::Exec() - { - if(mpWidget) - return mpWidget->ProcessMessage(mMessage, cGuiMessageData(), mbBypassVisibility, mbBypassEnabled); - - return false; - } - - //----------------------------------------------------------------------- - - tString cGuiGlobalShortcut::ToString() - { - tString sText; - - if(mpWidget) - { - iKeyboard* pKB = mpWidget->GetSet()->GetGui()->GetInput()->GetKeyboard(); - for(int i=0;iModifierKeyToString(mod); - } - } - if(mKey.mKey!=eKey_None) - { - if(sText!="") - sText += "+"; - sText += pKB->KeyToString(mKey.mKey); - } - } + vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; + vertexLayout.mAttribs[0].mBinding = 0; + vertexLayout.mAttribs[0].mLocation = 0; + vertexLayout.mAttribs[0].mOffset = 0; + + vertexLayout.mAttribs[1].mSemantic = SEMANTIC_TEXCOORD0; + vertexLayout.mAttribs[1].mFormat = TinyImageFormat_R32G32_SFLOAT; + vertexLayout.mAttribs[1].mBinding = 0; + vertexLayout.mAttribs[1].mLocation = 1; + vertexLayout.mAttribs[1].mOffset = sizeof(float3); + + vertexLayout.mAttribs[2].mSemantic = SEMANTIC_COLOR; + vertexLayout.mAttribs[2].mFormat = TinyImageFormat_R32G32B32A32_SFLOAT; + vertexLayout.mAttribs[2].mBinding = 0; + vertexLayout.mAttribs[2].mLocation = 2; + vertexLayout.mAttribs[2].mOffset = sizeof(float3) + sizeof(float2); + + RasterizerStateDesc rasterizerStateDesc = {}; + rasterizerStateDesc.mCullMode = CULL_MODE_NONE; + + DepthStateDesc depthStateDesc = {}; + depthStateDesc.mDepthTest = false; + depthStateDesc.mDepthWrite = false; + + TinyImageFormat inputFormat = TinyImageFormat_R8G8B8A8_UNORM; + PipelineDesc pipelineDesc = {}; + pipelineDesc.mType = PIPELINE_TYPE_GRAPHICS; + auto& pipelineSettings = pipelineDesc.mGraphicsDesc; + pipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST; + pipelineSettings.mRenderTargetCount = 1; + pipelineSettings.pDepthState = &depthStateDesc; + pipelineSettings.pColorFormats = &inputFormat; + pipelineSettings.mSampleCount = SAMPLE_COUNT_1; + pipelineSettings.mSampleQuality = 0; + pipelineSettings.pRootSignature = GuiRootSignatnre; + pipelineSettings.pShaderProgram = GuiShader; + pipelineSettings.pRasterizerState = &rasterizerStateDesc; + pipelineSettings.pVertexLayout = &vertexLayout; + + auto materialBlendFunc = + [](BlendConstant srcColor, BlendConstant destColor, BlendConstant srcAlpha, BlendConstant destAlpha) { + BlendStateDesc blendStateAddDesc = {}; + blendStateAddDesc.mSrcFactors[0] = srcColor; + blendStateAddDesc.mDstFactors[0] = destColor; + blendStateAddDesc.mBlendModes[0] = BM_ADD; + blendStateAddDesc.mSrcAlphaFactors[0] = srcAlpha; + blendStateAddDesc.mDstAlphaFactors[0] = destAlpha; + blendStateAddDesc.mBlendAlphaModes[0] = BM_ADD; + blendStateAddDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; + blendStateAddDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; + blendStateAddDesc.mIndependentBlend = false; + return blendStateAddDesc; + }; + + std::array blendStateDesc = {}; + blendStateDesc[eGuiMaterial_Diffuse] = materialBlendFunc(BC_ONE, BC_ZERO, BC_ONE, BC_ZERO); + blendStateDesc[eGuiMaterial_PremulAlpha] = + materialBlendFunc(BC_ONE, BC_ONE_MINUS_SRC_ALPHA, BC_ONE, BC_ONE_MINUS_SRC_ALPHA); + blendStateDesc[eGuiMaterial_Modulative] = materialBlendFunc(BC_DST_COLOR, BC_ZERO, BC_DST_ALPHA, BC_ZERO); + blendStateDesc[eGuiMaterial_Additive] = materialBlendFunc(BC_ONE, BC_ONE, BC_ONE, BC_ONE); + blendStateDesc[eGuiMaterial_FontNormal] = + materialBlendFunc(BC_SRC_ALPHA, BC_ONE_MINUS_SRC_ALPHA, BC_SRC_ALPHA, BC_ONE_MINUS_SRC_ALPHA); + blendStateDesc[eGuiMaterial_Alpha] = + materialBlendFunc(BC_SRC_ALPHA, BC_ONE_MINUS_SRC_ALPHA, BC_SRC_ALPHA, BC_ONE_MINUS_SRC_ALPHA); + + for (size_t i = 0; i < blendStateDesc.size(); i++) { + pipelineSettings.pBlendState = &blendStateDesc[i]; + addPipeline(pipeline.Rend(), &pipelineDesc, &GuiPipeline[i]); + } + + depthStateDesc.mDepthTest = true; + depthStateDesc.mDepthFunc = CMP_LEQUAL; + for (size_t i = 0; i < blendStateDesc.size(); i++) { + pipelineSettings.pBlendState = &blendStateDesc[i]; + addPipeline(pipeline.Rend(), &pipelineDesc, &GuiPipeline3D[i]); + } + } + addUniformGPURingBuffer(pipeline.Rend(), sizeof(UniformBlock) * MAX_GUI_DRAW_CALLS, &GuiUniformRingBuffer, true); + } + + void exitGui() { + } + } // namespace gui + + static bool SortWidget_Z(const iWidget* apWidgetA, const iWidget* apWidgetB) { + float fAZ, fBZ; + + fAZ = ((iWidget*)apWidgetA)->GetGlobalPosition().z; + fBZ = ((iWidget*)apWidgetB)->GetGlobalPosition().z; + return (fAZ > fBZ); + } + + bool cGuiRenderObjectCompare::operator()(const cGuiRenderObject& aObjectA, const cGuiRenderObject& aObjectB) const { + // Z + float fZA = aObjectA.mvPos.z; + float fZB = aObjectB.mvPos.z; + if (fZA != fZB) { + return fZA < fZB; + } + + // Clip Region + cGuiClipRegion* pClipA = aObjectA.mpClipRegion; + cGuiClipRegion* pClipB = aObjectB.mpClipRegion; + if (pClipA != pClipB) { + return pClipA > pClipB; + } + + // Material + eGuiMaterial pMaterialA = + aObjectA.mpCustomMaterial != eGuiMaterial::eGuiMaterial_LastEnum ? aObjectA.mpCustomMaterial : aObjectA.mpGfx->m_materialType; + eGuiMaterial pMaterialB = + aObjectB.mpCustomMaterial != eGuiMaterial::eGuiMaterial_LastEnum ? aObjectB.mpCustomMaterial : aObjectB.mpGfx->m_materialType; + if (pMaterialA != pMaterialB) { + return pMaterialA > pMaterialB; + } + + // Texture + Image* pTextureA = aObjectA.mpGfx->mvTextures[0]; + Image* pTextureB = aObjectB.mpGfx->mvTextures[0]; + if (pTextureA != pTextureB) { + return pTextureA > pTextureB; + } + + // Equal + return false; + } + + cGuiClipRegion::~cGuiClipRegion() { + Clear(); + } + + void cGuiClipRegion::Clear() { + STLDeleteAll(mlstChildren); + } + + cGuiClipRegion* cGuiClipRegion::CreateChild(const cVector3f& avPos, const cVector2f& avSize) { + cGuiClipRegion* pRegion = hplNew(cGuiClipRegion, ()); + + if (mRect.w < 0) { + pRegion->mRect = cRect2f(cVector2f(avPos.x, avPos.y), avSize); + } else { + cRect2f t = cRect2f(cVector2f(avPos.x, avPos.y), avSize); + pRegion->mRect = cMath::GetClipRect(t, mRect); + if (pRegion->mRect.w < 0) + pRegion->mRect.w = 0; + if (pRegion->mRect.h < 0) + pRegion->mRect.h = 0; + } + + mlstChildren.push_back(pRegion); + + return pRegion; + } + + cGuiGlobalShortcut::cGuiGlobalShortcut( + int alKeyModifiers, eKey aKey, iWidget* apWidget, eGuiMessage aMessage, bool abBypassVisibility, bool abBypassEnabled) { + mbEnabled = true; + mbBypassVisibility = abBypassVisibility; + mbBypassEnabled = abBypassEnabled; + + mKey = cKeyPress(aKey, 0, alKeyModifiers); + mpWidget = apWidget; + mMessage = aMessage; + } + + //----------------------------------------------------------------------- + + bool cGuiGlobalShortcut::ProcessKeyPress(const cKeyPress& aKey) { + if (IsEnabled() == false || mKey.mlModifier != aKey.mlModifier || mKey.mKey != aKey.mKey) + return false; + + return Exec(); + } + + //----------------------------------------------------------------------- + + bool cGuiGlobalShortcut::Exec() { + if (mpWidget) + return mpWidget->ProcessMessage(mMessage, cGuiMessageData(), mbBypassVisibility, mbBypassEnabled); + + return false; + } + + //----------------------------------------------------------------------- + + tString cGuiGlobalShortcut::ToString() { + tString sText; + + if (mpWidget) { + iKeyboard* pKB = mpWidget->GetSet()->GetGui()->GetInput()->GetKeyboard(); + for (int i = 0; i < eKeyModifier_LastEnum; ++i) { + eKeyModifier mod = (eKeyModifier)cMath::Pow2(i); + if (mKey.mlModifier & mod) { + if (sText != "") + sText += "+"; + sText += pKB->ModifierKeyToString(mod); + } + } + if (mKey.mKey != eKey_None) { + if (sText != "") + sText += "+"; + sText += pKB->KeyToString(mKey.mKey); + } + } + + return sText; + } + + //----------------------------------------------------------------------- - return sText; - } + ////////////////////////////////////////////////////////////////////////// + // CONSTRUCTORS + ////////////////////////////////////////////////////////////////////////// - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- - ////////////////////////////////////////////////////////////////////////// - // CONSTRUCTORS - ////////////////////////////////////////////////////////////////////////// + cGuiSet::cGuiSet( + const tString& asName, + cGui* apGui, + cGuiSkin* apSkin, + cResources* apResources, + cGraphics* apGraphics, + cSound* apSound, + cScene* apScene) { + mpGui = apGui; + mpSkin = NULL; - //----------------------------------------------------------------------- + msName = asName; - cGuiSet::cGuiSet( const tString &asName, cGui *apGui, cGuiSkin *apSkin, - cResources *apResources, cGraphics* apGraphics, - cSound *apSound, cScene *apScene) - { - mpGui = apGui; - mpSkin = NULL; - - msName = asName; + mpResources = apResources; + mpGraphics = apGraphics; + mpSound = apSound; + mpScene = apScene; - mpResources = apResources; - mpGraphics = apGraphics; - mpSound = apSound; - mpScene = apScene; - - mpGfxCurrentPointer = NULL; - - mpFocusedWidget = NULL; + mpGfxCurrentPointer = NULL; - mpAttentionWidget = NULL; + mpFocusedWidget = NULL; - mlPopupCount =0; - mfLastPopUpZ = 20; + mpAttentionWidget = NULL; - mvDrawOffset =0; + mlPopupCount = 0; + mfLastPopUpZ = 20; - mfContextMenuZ = 500; - - mvVirtualSize = mpGraphics->GetLowLevel()->GetScreenSizeFloat(); - mfVirtualMinZ = -1000; - mfVirtualMaxZ = 1000; - mvVirtualSizeOffset = cVector2f(0); - - mbActive = true; - mbDrawMouse = true; - mfMouseZ =mfVirtualMaxZ; - - mbIs3D = false; - mbRendersBeforePostEffects = false; - mv3DSize = 1; - m_mtx3DTransform = cMatrixf::Identity; - mbCullBackface = false; + mvDrawOffset = 0; - mpWidgetRoot = hplNew( iWidget, (eWidgetType_Root,this,mpSkin) ); - mpWidgetRoot->AddCallback(eGuiMessage_OnDraw,this,kGuiCallback(DrawMouse)); - mpWidgetRoot->AddCallback(eGuiMessage_OnDraw,this,kGuiCallback(DrawFocus)); - - mpCurrentClipRegion = &mBaseClipRegion; - - mbDestroyingSet = false; - - mlDrawPrio = 0; - - // 9 mouse buttons defined in InputTypes and GuiTypes - mvMouseDown.resize(9); - for(int i=0; i<(int)mvMouseDown.size(); ++i) mvMouseDown[i] = false; - mbMouseMovementEnabled = true; - - SetSkin(apSkin); - - mfToolTipTimer = 0; - mfToolTipTimeToPopUp = 0.5f; - mpCurrentToolTipWidget = NULL; - - mpFrameToolTip = NULL; - mpFrameBGToolTip = NULL; - mpLabelToolTip = NULL; - - mpTabOrderWidget = NULL; - mfWindowZ = -1; - - if(mpSkin) - { - CreateToolTipWidgets(); - } - - mpTopMostDestroyingWidget = NULL; - - mpDefaultFocusNavWidget = NULL; - mbDrawFocus = false; - mpFocusDrawObject = NULL; - mpFocusDrawCallback = NULL; + mfContextMenuZ = 500; - mbSortWidgets = false; - } + mvVirtualSize = mpGraphics->GetLowLevel()->GetScreenSizeFloat(); + mfVirtualMinZ = -1000; + mfVirtualMaxZ = 1000; + mvVirtualSizeOffset = cVector2f(0); - //----------------------------------------------------------------------- + mbActive = true; + mbDrawMouse = true; + mfMouseZ = mfVirtualMaxZ; - cGuiSet::~cGuiSet() - { - mbDestroyingSet = true; - { - STLDeleteAll(mlstPopUps); - STLDeleteAll(mlstWidgets); - hplDelete(mpWidgetRoot); - } - mbDestroyingSet = false; + mbIs3D = false; + mbRendersBeforePostEffects = false; + mv3DSize = 1; + m_mtx3DTransform = cMatrixf::Identity; + mbCullBackface = false; - ClearGlobalShortcuts(); - } + mpWidgetRoot = hplNew(iWidget, (eWidgetType_Root, this, mpSkin)); + mpWidgetRoot->AddCallback(eGuiMessage_OnDraw, this, kGuiCallback(DrawMouse)); + mpWidgetRoot->AddCallback(eGuiMessage_OnDraw, this, kGuiCallback(DrawFocus)); - void cGuiSet::Update(float afTimeStep) - { - ///////////////////////////// - // Popups - if(mlstPopUps.empty()==false) - { - STLDeleteAll(mlstPopUps); - } + mpCurrentClipRegion = &mBaseClipRegion; - ///////////////////////////// - // Update widgets - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - pWidget->Update(afTimeStep); - } + mbDestroyingSet = false; - ///////////////////////////// - // Update ToolTip - UpdateToolTip(afTimeStep); - } + mlDrawPrio = 0; - //----------------------------------------------------------------------- + // 9 mouse buttons defined in InputTypes and GuiTypes + mvMouseDown.resize(9); + for (int i = 0; i < (int)mvMouseDown.size(); ++i) + mvMouseDown[i] = false; + mbMouseMovementEnabled = true; - void cGuiSet::DrawAll(float afTimeStep) - { - if(mbActive==false) return; + SetSkin(apSkin); - /////////////////////////////// - //Draw all widgets - SetCurrentClipRegion(&mBaseClipRegion); - mpWidgetRoot->Draw(afTimeStep, &mBaseClipRegion); + mfToolTipTimer = 0; + mfToolTipTimeToPopUp = 0.5f; + mpCurrentToolTipWidget = NULL; - SetCurrentClipRegion(&mBaseClipRegion); + mpFrameToolTip = NULL; + mpFrameBGToolTip = NULL; + mpLabelToolTip = NULL; + + mpTabOrderWidget = NULL; + mfWindowZ = -1; + + if (mpSkin) { + CreateToolTipWidgets(); + } + + mpTopMostDestroyingWidget = NULL; - } + mpDefaultFocusNavWidget = NULL; + mbDrawFocus = false; + mpFocusDrawObject = NULL; + mpFocusDrawCallback = NULL; - //----------------------------------------------------------------------- + mbSortWidgets = false; + } - bool cGuiSet::SendMessage(eGuiMessage aMessage, const cGuiMessageData& aData) - { - // Sort widgets so that highest Z value mean first on the list (if needed) - if(mbSortWidgets) - { - mbSortWidgets = false; - mlstWidgets.sort(SortWidget_Z); - } + //----------------------------------------------------------------------- - switch(aMessage) - { - case eGuiMessage_MouseMove: return OnMouseMove(aData); - case eGuiMessage_MouseDown: return OnMouseDown(aData); - case eGuiMessage_MouseUp: return OnMouseUp(aData); - case eGuiMessage_MouseDoubleClick: return OnMouseDoubleClick(aData); + cGuiSet::~cGuiSet() { + mbDestroyingSet = true; + { + STLDeleteAll(mlstPopUps); + STLDeleteAll(mlstWidgets); + hplDelete(mpWidgetRoot); + } + mbDestroyingSet = false; + + ClearGlobalShortcuts(); + } + + void cGuiSet::Update(float afTimeStep) { + ///////////////////////////// + // Popups + if (mlstPopUps.empty() == false) { + STLDeleteAll(mlstPopUps); + } - case eGuiMessage_KeyPress: return OnKeyPress(aData); - case eGuiMessage_KeyRelease: return OnKeyRelease(aData); + ///////////////////////////// + // Update widgets + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + pWidget->Update(afTimeStep); + } - case eGuiMessage_GamepadInput: return OnGamepadInput(aData); - - case eGuiMessage_UIArrowPress: return OnUIArrowPress(aData); - case eGuiMessage_UIArrowRelease: return OnUIArrowRelease(aData); - case eGuiMessage_UIButtonPress: return OnUIButtonPress(aData); - case eGuiMessage_UIButtonRelease: return OnUIButtonRelease(aData); - case eGuiMessage_UIButtonDoublePress: return OnUIButtonDoublePress(aData); - } - - return false; - } - - //----------------------------------------------------------------------- - - cGuiGlobalShortcut* cGuiSet::AddGlobalShortcut(int alKeyModifiers, eKey aKey, iWidget* apWidget, eGuiMessage aMessage, bool abBypassVisibility, bool abBypassEnabled) - { - cGuiGlobalShortcut* pShortcut = hplNew(cGuiGlobalShortcut, (alKeyModifiers, aKey, - apWidget, aMessage, - abBypassVisibility, abBypassEnabled)); - - mlstShortcuts.push_back(pShortcut); - - return pShortcut; - } - - //----------------------------------------------------------------------- - - void cGuiSet::RemoveGlobalShortcut(cGuiGlobalShortcut* apShortcut) - { - if(apShortcut==NULL) - return; - - tShortcutListIt it = find(mlstShortcuts.begin(), mlstShortcuts.end(), apShortcut); - if(it!=mlstShortcuts.end()) - { - cGuiGlobalShortcut* pShortcut = *it; - mlstShortcuts.erase(it); - - hplDelete(pShortcut); - } - } - - - //----------------------------------------------------------------------- - - void cGuiSet::ClearGlobalShortcuts() - { - STLDeleteAll(mlstShortcuts); - } - - //----------------------------------------------------------------------- - - void cGuiSet::DestroyAllWidgets() - { - mbDestroyingSet = true; - - STLDeleteAll(mlstPopUps); - STLDeleteAll(mlstWidgets); - mpWidgetRoot->mlstChildren.clear(); - - mpFocusedWidget = NULL; - mpAttentionWidget = NULL; + ///////////////////////////// + // Update ToolTip + UpdateToolTip(afTimeStep); + } - mbDestroyingSet = false; - - mpCurrentToolTipWidget = NULL; - - CreateToolTipWidgets(); - } + //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - - void cGuiSet::ResetMouseOver() - { - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - pWidget->SetMouseIsOver(false); - } - } - - //----------------------------------------------------------------------- - - - void cGuiSet::Draw(const ForgeRenderer::Frame& frame, cFrustum* apFrustum) { - const bool isSwapChainRead = frame.m_currentFrame > 0; - if(m_setRenderObjects.empty() || !isSwapChainRead) { - return; - } - - iLowLevelGraphics *pLowLevelGraphics = mpGraphics->GetLowLevel(); - - size_t vertexBufferSize = m_setRenderObjects.size() * sizeof(gui::PositionTexColor) * 4; - size_t indexBufferSize = m_setRenderObjects.size() * sizeof(uint32_t) * 6; - #ifdef USE_THE_FORGE_LEGACY - GPURingBufferOffset vb = getGPURingBufferOffset(gui::GuiVertexRingBuffer, vertexBufferSize); - GPURingBufferOffset ib = getGPURingBufferOffset(gui::GuiIndexRingBuffer, indexBufferSize); - #else - GPURingBufferOffset vb = getGPURingBufferOffset(&gui::GuiVertexRingBuffer, vertexBufferSize); - GPURingBufferOffset ib = getGPURingBufferOffset(&gui::GuiIndexRingBuffer, indexBufferSize); - #endif - - - cMatrixf projectionMtx(cMatrixf::Identity); - cMatrixf viewMtx(cMatrixf::Identity); - cMatrixf modelMtx(cMatrixf::Identity); - if(mbIs3D && apFrustum) - { - //Invert the y coordinate: = -y, this also get the gui into the correct position. - //Also scale to size - cVector3f vPreScale = cVector3f(mv3DSize.x / mvVirtualSize.x, - -mv3DSize.y / mvVirtualSize.y, - mv3DSize.z / (mfVirtualMaxZ - mfVirtualMinZ)); - cMatrixf mtxPreMul = cMath::MatrixScale(vPreScale); - //note: Offset needs to be converted to shape coords (done by multiplying with pre scale) - mtxPreMul.SetTranslation(cVector3f(mvVirtualSizeOffset.x*vPreScale.x, mvVirtualSizeOffset.y*vPreScale.y, 0)); + void cGuiSet::DrawAll(float afTimeStep) { + if (mbActive == false) + return; - //Create the final model matrix - modelMtx = cMath::MatrixMul(m_mtx3DTransform, mtxPreMul); - projectionMtx = apFrustum->GetProjectionMatrix().GetTranspose(); - viewMtx = apFrustum->GetViewMatrix().GetTranspose(); - } - //Screen projection - else - { - - //Set up min and max for orth projection - cVector3f vProjMin(-mvVirtualSizeOffset.x, -mvVirtualSizeOffset.y, mfVirtualMinZ); - cVector3f vProjMax(mvVirtualSize.x-mvVirtualSizeOffset.x, mvVirtualSize.y-mvVirtualSizeOffset.y, mfVirtualMaxZ); - - mat4 proj = mat4::orthographic(vProjMin.x, vProjMax.x, vProjMax.y, vProjMin.y, vProjMin.z, vProjMax.z); + /////////////////////////////// + // Draw all widgets + SetCurrentClipRegion(&mBaseClipRegion); + mpWidgetRoot->Draw(afTimeStep, &mBaseClipRegion); + + SetCurrentClipRegion(&mBaseClipRegion); + } + + //----------------------------------------------------------------------- + + bool cGuiSet::SendMessage(eGuiMessage aMessage, const cGuiMessageData& aData) { + // Sort widgets so that highest Z value mean first on the list (if needed) + if (mbSortWidgets) { + mbSortWidgets = false; + mlstWidgets.sort(SortWidget_Z); + } + + switch (aMessage) { + case eGuiMessage_MouseMove: + return OnMouseMove(aData); + case eGuiMessage_MouseDown: + return OnMouseDown(aData); + case eGuiMessage_MouseUp: + return OnMouseUp(aData); + case eGuiMessage_MouseDoubleClick: + return OnMouseDoubleClick(aData); + + case eGuiMessage_KeyPress: + return OnKeyPress(aData); + case eGuiMessage_KeyRelease: + return OnKeyRelease(aData); + + case eGuiMessage_GamepadInput: + return OnGamepadInput(aData); + + case eGuiMessage_UIArrowPress: + return OnUIArrowPress(aData); + case eGuiMessage_UIArrowRelease: + return OnUIArrowRelease(aData); + case eGuiMessage_UIButtonPress: + return OnUIButtonPress(aData); + case eGuiMessage_UIButtonRelease: + return OnUIButtonRelease(aData); + case eGuiMessage_UIButtonDoublePress: + return OnUIButtonDoublePress(aData); + } + + return false; + } + + //----------------------------------------------------------------------- + + cGuiGlobalShortcut* cGuiSet::AddGlobalShortcut( + int alKeyModifiers, eKey aKey, iWidget* apWidget, eGuiMessage aMessage, bool abBypassVisibility, bool abBypassEnabled) { + cGuiGlobalShortcut* pShortcut = + hplNew(cGuiGlobalShortcut, (alKeyModifiers, aKey, apWidget, aMessage, abBypassVisibility, abBypassEnabled)); + + mlstShortcuts.push_back(pShortcut); + + return pShortcut; + } + + //----------------------------------------------------------------------- + + void cGuiSet::RemoveGlobalShortcut(cGuiGlobalShortcut* apShortcut) { + if (apShortcut == NULL) + return; + + tShortcutListIt it = find(mlstShortcuts.begin(), mlstShortcuts.end(), apShortcut); + if (it != mlstShortcuts.end()) { + cGuiGlobalShortcut* pShortcut = *it; + mlstShortcuts.erase(it); + + hplDelete(pShortcut); + } + } + + //----------------------------------------------------------------------- + + void cGuiSet::ClearGlobalShortcuts() { + STLDeleteAll(mlstShortcuts); + } + + //----------------------------------------------------------------------- + + void cGuiSet::DestroyAllWidgets() { + mbDestroyingSet = true; + + STLDeleteAll(mlstPopUps); + STLDeleteAll(mlstWidgets); + mpWidgetRoot->mlstChildren.clear(); + + mpFocusedWidget = NULL; + mpAttentionWidget = NULL; + + mbDestroyingSet = false; + + mpCurrentToolTipWidget = NULL; + + CreateToolTipWidgets(); + } + + //----------------------------------------------------------------------- + + void cGuiSet::ResetMouseOver() { + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + pWidget->SetMouseIsOver(false); + } + } + + //----------------------------------------------------------------------- + + void cGuiSet::Draw(const ForgeRenderer::Frame& frame, cFrustum* apFrustum) { + const bool isSwapChainRead = frame.m_currentFrame > 0; + if (m_setRenderObjects.empty() || !isSwapChainRead) { + return; + } + + iLowLevelGraphics* pLowLevelGraphics = mpGraphics->GetLowLevel(); + + size_t vertexBufferSize = m_setRenderObjects.size() * sizeof(gui::PositionTexColor) * 4; + size_t indexBufferSize = m_setRenderObjects.size() * sizeof(uint32_t) * 6; + GraphicsAllocator* graphicsAllocator = Interface::Get(); + + GPURingBufferOffset vb = graphicsAllocator->allocTransientVertexBuffer(vertexBufferSize); + GPURingBufferOffset ib = graphicsAllocator->allocTransientIndexBuffer(indexBufferSize); + + cMatrixf projectionMtx(cMatrixf::Identity); + cMatrixf viewMtx(cMatrixf::Identity); + cMatrixf modelMtx(cMatrixf::Identity); + if (mbIs3D && apFrustum) { + // Invert the y coordinate: = -y, this also get the gui into the correct position. + // Also scale to size + cVector3f vPreScale = + cVector3f(mv3DSize.x / mvVirtualSize.x, -mv3DSize.y / mvVirtualSize.y, mv3DSize.z / (mfVirtualMaxZ - mfVirtualMinZ)); + cMatrixf mtxPreMul = cMath::MatrixScale(vPreScale); + // note: Offset needs to be converted to shape coords (done by multiplying with pre scale) + mtxPreMul.SetTranslation(cVector3f(mvVirtualSizeOffset.x * vPreScale.x, mvVirtualSizeOffset.y * vPreScale.y, 0)); + + // Create the final model matrix + modelMtx = cMath::MatrixMul(m_mtx3DTransform, mtxPreMul); + projectionMtx = apFrustum->GetProjectionMatrix().GetTranspose(); + viewMtx = apFrustum->GetViewMatrix().GetTranspose(); + } + // Screen projection + else { + // Set up min and max for orth projection + cVector3f vProjMin(-mvVirtualSizeOffset.x, -mvVirtualSizeOffset.y, mfVirtualMinZ); + cVector3f vProjMax(mvVirtualSize.x - mvVirtualSizeOffset.x, mvVirtualSize.y - mvVirtualSizeOffset.y, mfVirtualMaxZ); + + mat4 proj = mat4::orthographicLH(vProjMin.x, vProjMax.x, vProjMax.y, vProjMin.y, vProjMin.z, vProjMax.z); projectionMtx = cMath::FromForgeMat(proj); - } + } - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - cVector2l vSize = pLowLevelGraphics->GetScreenSizeInt(); + cVector2l vSize = pLowLevelGraphics->GetScreenSizeInt(); RenderTarget* target = frame.m_finalRenderTarget; - cmdBindRenderTargets(frame.m_cmd, 1, &target, NULL, &loadActions, NULL, NULL, -1, -1); - cmdSetViewport(frame.m_cmd, 0.0f, 0.0f, (float)vSize.x, (float)vSize.y, 0.0f, 1.0f); - cmdSetScissor(frame.m_cmd, 0, 0, vSize.x, vSize.y); - auto it = m_setRenderObjects.begin(); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { target, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); + + cmdSetViewport(frame.m_cmd, 0.0f, 0.0f, (float)vSize.x, (float)vSize.y, 0.0f, 1.0f); + cmdSetScissor(frame.m_cmd, 0, 0, vSize.x, vSize.y); - eGuiMaterial pLastMaterial = eGuiMaterial::eGuiMaterial_LastEnum; - Image* pLastTexture = NULL; - cGuiClipRegion *pLastClipRegion = NULL; + auto it = m_setRenderObjects.begin(); - cGuiGfxElement *pGfx = it->mpGfx; - eGuiMaterial materialType = it->mpCustomMaterial != eGuiMaterial_LastEnum ? it->mpCustomMaterial : pGfx->m_materialType; - Image* pTexture = pGfx->mvTextures[0]; - cGuiClipRegion *pClipRegion = it->mpClipRegion; + eGuiMaterial pLastMaterial = eGuiMaterial::eGuiMaterial_LastEnum; + Image* pLastTexture = NULL; + cGuiClipRegion* pLastClipRegion = NULL; - BufferUpdateDesc vertexUpdateDesc = { vb.pBuffer, vb.mOffset, vertexBufferSize}; - BufferUpdateDesc indexUpdateDesc = { ib.pBuffer, ib.mOffset, indexBufferSize}; - beginUpdateResource(&vertexUpdateDesc); - beginUpdateResource(&indexUpdateDesc); + cGuiGfxElement* pGfx = it->mpGfx; + eGuiMaterial materialType = it->mpCustomMaterial != eGuiMaterial_LastEnum ? it->mpCustomMaterial : pGfx->m_materialType; + Image* pTexture = pGfx->mvTextures[0]; + cGuiClipRegion* pClipRegion = it->mpClipRegion; - size_t vertexBufferOffset = 0; - size_t indexBufferOffset = 0; - while(it != m_setRenderObjects.end()) { + BufferUpdateDesc vertexUpdateDesc = { vb.pBuffer, vb.mOffset, vertexBufferSize }; + BufferUpdateDesc indexUpdateDesc = { ib.pBuffer, ib.mOffset, indexBufferSize }; + beginUpdateResource(&vertexUpdateDesc); + beginUpdateResource(&indexUpdateDesc); - size_t vertexBufferIndex = 0; - size_t indexBufferIndex = 0; + size_t vertexBufferOffset = 0; + size_t indexBufferOffset = 0; + while (it != m_setRenderObjects.end()) { + size_t vertexBufferIndex = 0; + size_t indexBufferIndex = 0; uint32_t requestSize = round_up(sizeof(gui::UniformBlock), 256); - #ifdef USE_THE_FORGE_LEGACY - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(gui::GuiUniformRingBuffer, requestSize); - #else GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&gui::GuiUniformRingBuffer, requestSize); - #endif - DescriptorData params[10]{}; - uint32_t paramCount = 0; + DescriptorData params[10]{}; + uint32_t paramCount = 0; DescriptorDataRange range = { (uint32_t)uniformBlockOffset.mOffset, requestSize }; - params[paramCount].pName = "uniformBlock"; - params[paramCount].pRanges = ⦥ - params[paramCount++].ppBuffers = &uniformBlockOffset.pBuffer; - - gui::UniformBlock uniformBlock = {}; - if(pTexture) { - uniformBlock.textureConfig |= gui::GUI_TEXTURE_CONFIG_DIFFUSE; - params[paramCount].pName = "diffuseMap"; - gui::GuiTextures[frame.m_frameIndex][gui::descriptorIndex] = pTexture->GetTexture(); - params[paramCount++].ppTextures = &pTexture->GetTexture().m_handle; - } - uniformBlock.mvp = cMath::ToForgeMatrix4(cMath::MatrixMul(cMath::MatrixMul(projectionMtx, viewMtx), modelMtx).GetTranspose()); - auto& descriptorSet = gui::GuiUniformDescriptorSet[frame.m_frameIndex]; - updateDescriptorSet(frame.m_renderer->Rend(), gui::descriptorIndex, descriptorSet, paramCount, params); - - if(mbIs3D) { - cmdBindPipeline(frame.m_cmd, gui::GuiPipeline3D[materialType]); - } else { - cmdBindPipeline(frame.m_cmd, gui::GuiPipeline[materialType]); - } - - const bool hasClip = pClipRegion && pClipRegion->mRect.w > 0.0f; - if(hasClip) - { - uniformBlock.textureConfig |= gui::GUI_TEXTURE_CONFIG_CLIP; - cRect2f& clipRect = pClipRegion->mRect; - cPlanef plane; - //Bottom - plane.FromNormalPoint(cVector3f(0,-1,0),cVector3f(0,clipRect.y+clipRect.h,0)); - uniformBlock.clipPlanes[0] = {plane.a, plane.b, plane.c, plane.d}; - - //Top - plane.FromNormalPoint(cVector3f(0,1,0),cVector3f(0,clipRect.y,0)); - uniformBlock.clipPlanes[1] = {plane.a, plane.b, plane.c, plane.d}; - - //Right - plane.FromNormalPoint(cVector3f(1,0,0),cVector3f(clipRect.x,0,0)); - uniformBlock.clipPlanes[2] = {plane.a, plane.b, plane.c, plane.d}; - - //Left - plane.FromNormalPoint(cVector3f(-1,0,0),cVector3f(clipRect.x+clipRect.w,0,0)); - uniformBlock.clipPlanes[3] = {plane.a, plane.b, plane.c, plane.d}; - } - BufferUpdateDesc updateDesc = { uniformBlockOffset.pBuffer, uniformBlockOffset.mOffset }; - beginUpdateResource(&updateDesc); - (*reinterpret_cast(updateDesc.pMappedData)) = uniformBlock; - endUpdateResource(&updateDesc, NULL); - - uint32_t stride = sizeof(gui::PositionTexColor); - cmdBindDescriptorSet(frame.m_cmd, gui::descriptorIndex, descriptorSet); - gui::descriptorIndex = (gui::descriptorIndex + 1) % gui::MAX_GUI_DRAW_CALLS; - - do - { - const cGuiRenderObject &object = *it; - cGuiGfxElement *pGfx = object.mpGfx; - - if(object.mbRotated) - { - for(int i=0; i<4; ++i) - { - - cVertex &vtx = pGfx->mvVtx[i]; - cVector3f vVtxPos = vtx.pos; - const cVector3f& vPos = object.mvPos; - const cColor color = vtx.col * object.mColor; - - //Scale - vVtxPos.x *= object.mvSize.x; - vVtxPos.y *= object.mvSize.y; - - //Rotate - vVtxPos.x -= object.mvPivot.x; - vVtxPos.y -= object.mvPivot.y; - vVtxPos = cMath::MatrixMul(cMath::MatrixRotateZ(object.mfAngle), vVtxPos); - vVtxPos.x += object.mvPivot.x; - vVtxPos.y += object.mvPivot.y; - - reinterpret_cast(vertexUpdateDesc.pMappedData)[vertexBufferOffset + (vertexBufferIndex++)] = { - {vVtxPos.x + vPos.x, vVtxPos.y + vPos.y, vPos.z}, - { vtx.tex.x, vtx.tex.y}, - {color.r, color.g, color.b, color.a} - }; - - } - } - else - { - for(int i=0; i<4; ++i) - { - cVertex &vtx = pGfx->mvVtx[i]; - cVector3f& vVtxPos = vtx.pos; - const cVector3f& vPos = object.mvPos; - const cColor color = vtx.col * object.mColor; - - reinterpret_cast(vertexUpdateDesc.pMappedData)[vertexBufferOffset + (vertexBufferIndex++)] = { - {vVtxPos.x * object.mvSize.x + vPos.x, vVtxPos.y * object.mvSize.y + vPos.y, vPos.z}, - { vtx.tex.x, vtx.tex.y}, - {color.r, color.g, color.b, color.a} - }; - - } - } - - reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 4; - reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 3; - reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 2; - - reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 4; - reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 2; - reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 1; - - - /////////////////////////// - //Set last texture - pLastMaterial = materialType; - pLastTexture = pTexture; - pLastClipRegion = pClipRegion; - - ///////////////////////////// - //Get next object - ++it; if(it == m_setRenderObjects.end()) break; - - pGfx = it->mpGfx; - materialType = it->mpCustomMaterial != eGuiMaterial_LastEnum ? it->mpCustomMaterial : pGfx->m_materialType; - pTexture = it->mpGfx->mvTextures[0]; - pClipRegion = it->mpClipRegion; - } - while(pTexture == pLastTexture && - materialType == pLastMaterial && - pClipRegion == pLastClipRegion); - - uint64_t vbOffset = vb.mOffset + vertexBufferOffset * sizeof(gui::PositionTexColor); - uint64_t ibOffset = ib.mOffset + indexBufferOffset * sizeof(uint32_t); - - cmdBindVertexBuffer(frame.m_cmd, 1, &vb.pBuffer, &stride, &vbOffset); - cmdBindIndexBuffer(frame.m_cmd, ib.pBuffer, INDEX_TYPE_UINT32, ibOffset); - cmdDrawIndexed(frame.m_cmd, indexBufferIndex, 0, 0); - - vertexBufferOffset += vertexBufferIndex; - indexBufferOffset += indexBufferIndex; - - } - - endUpdateResource(&vertexUpdateDesc, NULL); - endUpdateResource(&indexUpdateDesc, NULL); - - mBaseClipRegion.Clear(); - } - - void cGuiSet::ClearRenderObjects() - { - m_setRenderObjects.clear(); - } - - //----------------------------------------------------------------------- - - void cGuiSet::DrawGfx( cGuiGfxElement* apGfx, const cVector3f &avPos, const cVector2f &avSize, - const cColor& aColor,eGuiMaterial aMaterial, - float afRotationAngle, - bool abUseCustomPivot, const cVector3f& avCustomPivot) - { - if(mpCurrentClipRegion==NULL) return; - if(mpCurrentClipRegion->mRect.w ==0 || mpCurrentClipRegion->mRect.h==0) return; - - //Log("Bug:Drawing gfx: %p\n", apGfx); - - cVector3f vAbsPos = avPos + apGfx->GetOffset() + mvDrawOffset; - if(mpCurrentClipRegion->mRect.w >0) - { - cRect2f gfxRect; - gfxRect.x = vAbsPos.x; - gfxRect.y = vAbsPos.y; - if(avSize.x < 0) - { - gfxRect.w = apGfx->GetImageSize().x; - gfxRect.h = apGfx->GetImageSize().y; - } - else - { - gfxRect.w = avSize.x; - gfxRect.h = avSize.y; - } - - if(cMath::CheckRectIntersection(mpCurrentClipRegion->mRect,gfxRect)==false) return; - } - - apGfx->Flush(); - - cGuiRenderObject object; - - //Log("Clip: %f %f\n",mpCurrentClipRegion->mRect.w,mpCurrentClipRegion->mRect.h); - - ////////////////////////// - //Set Graphics - object.mpGfx = apGfx; - object.mpClipRegion = mpCurrentClipRegion; - - /////////////////////////// - //Position, size and color - object.mvPos = vAbsPos; - if(avSize.x < 0) object.mvSize = apGfx->GetImageSize(); - else object.mvSize = avSize; - object.mColor = aColor; - - /////////////////////////// - //Material - object.mpCustomMaterial = aMaterial; - - /////////////////////////// - //Rotation - if(afRotationAngle !=0) - { - object.mbRotated = true; - object.mfAngle = afRotationAngle; - - if(abUseCustomPivot) - object.mvPivot = avCustomPivot; - else - object.mvPivot = object.mvSize*0.5f; - } - else - { - object.mbRotated = false; - } - - m_setRenderObjects.insert(object); - } - - //----------------------------------------------------------------------- - - void cGuiSet::DrawFont( const tWString &asText, - iFontData *apFont, const cVector3f &avPos, - const cVector2f &avSize, const cColor& aColor, - eFontAlign aAlign, eGuiMaterial aMaterial) - { - DrawTextFromCharArry(asText.c_str(), apFont,avSize,avPos,aColor,aMaterial,aAlign); - } - - //----------------------------------------------------------------------- - - static wchar_t gsTempTextArray[1024]; - void cGuiSet::DrawFont (iFontData *apFont, const cVector3f &avPos, - const cVector2f &avSize, const cColor& aColor, - eFontAlign aAlign,eGuiMaterial aMaterial, - const wchar_t* fmt,...) - { - va_list ap; - if (fmt == NULL) return; - va_start(ap, fmt); - vswprintf(gsTempTextArray, 1023, fmt, ap); - va_end(ap); - - DrawTextFromCharArry(gsTempTextArray, apFont,avSize,avPos,aColor,aMaterial,aAlign); - } - - void cGuiSet::DrawFont ( iFontData *apFont, const cVector3f &avPos, - const cVector2f &avSize, const cColor& aColor, - const wchar_t* fmt,...) - { - va_list ap; - if (fmt == NULL) return; - va_start(ap, fmt); - vswprintf(gsTempTextArray, 1023, fmt, ap); - va_end(ap); - - DrawTextFromCharArry(gsTempTextArray, apFont,avSize,avPos,aColor,eGuiMaterial_FontNormal,eFontAlign_Left); - } - - - //----------------------------------------------------------------------- - - cWidgetWindow* cGuiSet::CreateWidgetWindow( tWidgetWindowButtonFlag alFlags, - const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetWindow *pWindow = hplNew( cWidgetWindow, (this,mpSkin, alFlags) ); - pWindow->SetPosition(avLocalPos); - pWindow->SetSize(avSize); - pWindow->SetText(asText); - pWindow->SetName(asName); - AddWidget(pWindow, apParent); - - mlstWindows.push_back(pWindow); - - return pWindow; - } - - cWidgetFrame* cGuiSet::CreateWidgetFrame( const cVector3f &avLocalPos, - const cVector2f &avSize, - bool abDrawFrame, - iWidget *apParent, - bool abHScrollBar, bool abVScrollBar, - const tString& asName) - { - cWidgetFrame *pFrame = hplNew( cWidgetFrame, (this,mpSkin, abHScrollBar, abVScrollBar) ); - pFrame->SetPosition(avLocalPos); - pFrame->SetSize(avSize); - pFrame->SetDrawFrame(abDrawFrame); - pFrame->SetName(asName); - AddWidget(pFrame,apParent); - return pFrame; - } - - cWidgetButton* cGuiSet::CreateWidgetButton( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - bool abToggleable, - const tString& asName) - { - cWidgetButton *pButton = hplNew( cWidgetButton, (this,mpSkin) ); - pButton->SetPosition(avLocalPos); - pButton->SetSize(avSize); - pButton->SetText(asText); - pButton->SetName(asName); - pButton->SetToggleable(abToggleable); - AddWidget(pButton,apParent); - return pButton; - } - - cWidgetLabel* cGuiSet::CreateWidgetLabel( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetLabel *pLabel = hplNew( cWidgetLabel, (this,mpSkin) ); - pLabel->SetPosition(avLocalPos); - pLabel->SetSize(avSize); - pLabel->SetText(asText); - pLabel->SetName(asName); - - if(avSize == -1) - { - pLabel->SetAutogenerateSize(true); - pLabel->SetAutogenerateSize(false); - } - - AddWidget(pLabel,apParent); - return pLabel; - } - - cWidgetSlider* cGuiSet::CreateWidgetSlider( eWidgetSliderOrientation aOrientation, - const cVector3f &avLocalPos, - const cVector2f &avSize, - int alMaxValue, - iWidget *apParent, - const tString& asName) - { - cWidgetSlider *pSlider = hplNew( cWidgetSlider, (this,mpSkin,aOrientation) ); - pSlider->SetPosition(avLocalPos); - pSlider->SetSize(avSize); - pSlider->SetMaxValue(alMaxValue); - pSlider->SetName(asName); - AddWidget(pSlider,apParent); - return pSlider; - } - - cWidgetTextBox* cGuiSet::CreateWidgetTextBox( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - eWidgetTextBoxInputType aType, - float afNumericAdd, - bool abShowButtons, - const tString& asName) - { - cWidgetTextBox *pTextBox = hplNew( cWidgetTextBox, (this,mpSkin,aType) ); - pTextBox->SetPosition(avLocalPos); - pTextBox->SetSize(avSize); - pTextBox->SetShowButtons(abShowButtons); - pTextBox->SetNumericAdd(afNumericAdd); - pTextBox->SetText(asText); - pTextBox->SetName(asName); - AddWidget(pTextBox,apParent); - return pTextBox; - } - - cWidgetCheckBox* cGuiSet::CreateWidgetCheckBox( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetCheckBox *pCheckBox = hplNew( cWidgetCheckBox, (this,mpSkin) ); - pCheckBox->SetPosition(avLocalPos); - pCheckBox->SetSize(avSize); - pCheckBox->SetText(asText); - pCheckBox->SetName(asName); - AddWidget(pCheckBox,apParent); - return pCheckBox; - } - - cWidgetImage* cGuiSet::CreateWidgetImage(const tString &asFile, - const cVector3f &avLocalPos, - const cVector2f &avSize, - eGuiMaterial aMaterial, - bool abAnimate, - iWidget *apParent, - const tString& asName) - { - cWidgetImage *pImage = hplNew( cWidgetImage, (this,mpSkin) ); - cGuiGfxElement *pGfx = NULL; - if(asFile != "") - { - if(abAnimate) - { - pGfx = mpGui->CreateGfxImageBuffer(asFile,aMaterial,true); - } - else - { - pGfx = mpGui->CreateGfxImage(asFile,aMaterial); - } - } - pImage->SetPosition(avLocalPos); - - if(pGfx && avSize.x <0) - { - pImage->SetSize(pGfx->GetImageSize()); - } - else - { - pImage->SetSize(avSize); - } - - pImage->SetImage(pGfx); - - pImage->SetName(asName); - - AddWidget(pImage,apParent); - return pImage; - } - - cWidgetListBox* cGuiSet::CreateWidgetListBox(const cVector3f &avLocalPos, - const cVector2f &avSize, - iWidget *apParent, - const tString& asName) - { - cWidgetListBox *pListBox = hplNew( cWidgetListBox,(this,mpSkin) ); - pListBox->SetPosition(avLocalPos); - pListBox->SetSize(avSize); - pListBox->SetName(asName); - AddWidget(pListBox,apParent); - return pListBox; - } - - cWidgetMultiPropertyListBox* cGuiSet::CreateWidgetMultiPropertyListBox( const cVector3f& avLocalPos, - const cVector2f& avSize, - iWidget* apParent, - const tString& asName) - { - cWidgetMultiPropertyListBox* pListBox = hplNew( cWidgetMultiPropertyListBox, (this,mpSkin)); - pListBox->SetPosition(avLocalPos); - pListBox->SetSize(avSize); - pListBox->SetName(asName); - AddWidget(pListBox,apParent); - return pListBox; - } - - cWidgetComboBox* cGuiSet::CreateWidgetComboBox( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetComboBox *pComboBox = hplNew( cWidgetComboBox, (this,mpSkin) ); - pComboBox->SetPosition(avLocalPos); - pComboBox->SetSize(avSize); - pComboBox->SetText(asText); - pComboBox->SetName(asName); - AddWidget(pComboBox,apParent); - return pComboBox; - } - - cWidgetMenuItem* cGuiSet::CreateWidgetMenuItem( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetMenuItem *pItem = hplNew( cWidgetMenuItem, ((iWidgetMenu*)apParent) ); - pItem->SetPosition(avLocalPos); - pItem->SetSize(avSize); - pItem->SetText(asText); - pItem->SetName(asName); - AddWidget(pItem,apParent); - return pItem; - } - - cWidgetContextMenu* cGuiSet::CreateWidgetContextMenu( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetContextMenu *pMenu = hplNew( cWidgetContextMenu, (this,mpSkin) ); - pMenu->SetPosition(avLocalPos); - pMenu->SetSize(avSize); - pMenu->SetText(asText); - pMenu->SetName(asName); - AddWidget(pMenu,apParent); - return pMenu; - } - - cWidgetMainMenu* cGuiSet::CreateWidgetMainMenu(iWidget *apParent, - const tString& asName) - { - cWidgetMainMenu *pMenu = hplNew( cWidgetMainMenu, (this,mpSkin) ); - pMenu->SetName(asName); - AddWidget(pMenu,apParent); - return pMenu; - } - - cWidgetTabLabel* cGuiSet::CreateWidgetTabLabel( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetTabLabel *pLabel = hplNew( cWidgetTabLabel, (this,mpSkin) ); - pLabel->SetPosition(avLocalPos); - pLabel->SetSize(avSize); - pLabel->SetText(asText); - pLabel->SetName(asName); - AddWidget(pLabel,apParent); - return pLabel; - } - - cWidgetTab* cGuiSet::CreateWidgetTab( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetTab *pTab = hplNew( cWidgetTab, ((cWidgetTabFrame*)apParent) ); + params[paramCount].pName = "uniformBlock"; + params[paramCount].pRanges = ⦥ + params[paramCount++].ppBuffers = &uniformBlockOffset.pBuffer; + + gui::UniformBlock uniformBlock = {}; + if (pTexture) { + uniformBlock.textureConfig |= gui::GUI_TEXTURE_CONFIG_DIFFUSE; + params[paramCount].pName = "diffuseMap"; + gui::GuiTextures[frame.m_frameIndex][gui::descriptorIndex] = pTexture->GetTexture(); + params[paramCount++].ppTextures = &pTexture->GetTexture().m_handle; + } + uniformBlock.mvp = cMath::ToForgeMatrix4(cMath::MatrixMul(cMath::MatrixMul(projectionMtx, viewMtx), modelMtx).GetTranspose()); + auto& descriptorSet = gui::GuiUniformDescriptorSet[frame.m_frameIndex]; + updateDescriptorSet(frame.m_renderer->Rend(), gui::descriptorIndex, descriptorSet, paramCount, params); + + if (mbIs3D) { + cmdBindPipeline(frame.m_cmd, gui::GuiPipeline3D[materialType]); + } else { + cmdBindPipeline(frame.m_cmd, gui::GuiPipeline[materialType]); + } + + const bool hasClip = pClipRegion && pClipRegion->mRect.w > 0.0f; + if (hasClip) { + uniformBlock.textureConfig |= gui::GUI_TEXTURE_CONFIG_CLIP; + cRect2f& clipRect = pClipRegion->mRect; + cPlanef plane; + // Bottom + plane.FromNormalPoint(cVector3f(0, -1, 0), cVector3f(0, clipRect.y + clipRect.h, 0)); + uniformBlock.clipPlanes[0] = { plane.a, plane.b, plane.c, plane.d }; + + // Top + plane.FromNormalPoint(cVector3f(0, 1, 0), cVector3f(0, clipRect.y, 0)); + uniformBlock.clipPlanes[1] = { plane.a, plane.b, plane.c, plane.d }; + + // Right + plane.FromNormalPoint(cVector3f(1, 0, 0), cVector3f(clipRect.x, 0, 0)); + uniformBlock.clipPlanes[2] = { plane.a, plane.b, plane.c, plane.d }; + + // Left + plane.FromNormalPoint(cVector3f(-1, 0, 0), cVector3f(clipRect.x + clipRect.w, 0, 0)); + uniformBlock.clipPlanes[3] = { plane.a, plane.b, plane.c, plane.d }; + } + BufferUpdateDesc updateDesc = { uniformBlockOffset.pBuffer, uniformBlockOffset.mOffset }; + beginUpdateResource(&updateDesc); + (*reinterpret_cast(updateDesc.pMappedData)) = uniformBlock; + endUpdateResource(&updateDesc); + + uint32_t stride = sizeof(gui::PositionTexColor); + cmdBindDescriptorSet(frame.m_cmd, gui::descriptorIndex, descriptorSet); + gui::descriptorIndex = (gui::descriptorIndex + 1) % gui::MAX_GUI_DRAW_CALLS; + + do { + const cGuiRenderObject& object = *it; + cGuiGfxElement* pGfx = object.mpGfx; + + if (object.mbRotated) { + for (int i = 0; i < 4; ++i) { + cVertex& vtx = pGfx->mvVtx[i]; + cVector3f vVtxPos = vtx.pos; + const cVector3f& vPos = object.mvPos; + const cColor color = vtx.col * object.mColor; + + // Scale + vVtxPos.x *= object.mvSize.x; + vVtxPos.y *= object.mvSize.y; + + // Rotate + vVtxPos.x -= object.mvPivot.x; + vVtxPos.y -= object.mvPivot.y; + vVtxPos = cMath::MatrixMul(cMath::MatrixRotateZ(object.mfAngle), vVtxPos); + vVtxPos.x += object.mvPivot.x; + vVtxPos.y += object.mvPivot.y; + + reinterpret_cast( + vertexUpdateDesc.pMappedData)[vertexBufferOffset + (vertexBufferIndex++)] = { + { vVtxPos.x + vPos.x, vVtxPos.y + vPos.y, vPos.z }, + { vtx.tex.x, vtx.tex.y }, + { color.r, color.g, color.b, color.a } + }; + } + } else { + for (int i = 0; i < 4; ++i) { + cVertex& vtx = pGfx->mvVtx[i]; + cVector3f& vVtxPos = vtx.pos; + const cVector3f& vPos = object.mvPos; + const cColor color = vtx.col * object.mColor; + + reinterpret_cast( + vertexUpdateDesc.pMappedData)[vertexBufferOffset + (vertexBufferIndex++)] = { + { vVtxPos.x * object.mvSize.x + vPos.x, vVtxPos.y * object.mvSize.y + vPos.y, vPos.z }, + { vtx.tex.x, vtx.tex.y }, + { color.r, color.g, color.b, color.a } + }; + } + } + + reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 4; + reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 3; + reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 2; + + reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 4; + reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 2; + reinterpret_cast(indexUpdateDesc.pMappedData)[indexBufferOffset + (indexBufferIndex++)] = vertexBufferIndex - 1; + + /////////////////////////// + // Set last texture + pLastMaterial = materialType; + pLastTexture = pTexture; + pLastClipRegion = pClipRegion; + + ///////////////////////////// + // Get next object + ++it; + if (it == m_setRenderObjects.end()) + break; + + pGfx = it->mpGfx; + materialType = it->mpCustomMaterial != eGuiMaterial_LastEnum ? it->mpCustomMaterial : pGfx->m_materialType; + pTexture = it->mpGfx->mvTextures[0]; + pClipRegion = it->mpClipRegion; + } while (pTexture == pLastTexture && materialType == pLastMaterial && pClipRegion == pLastClipRegion); + + uint64_t vbOffset = vb.mOffset + vertexBufferOffset * sizeof(gui::PositionTexColor); + uint64_t ibOffset = ib.mOffset + indexBufferOffset * sizeof(uint32_t); + + cmdBindVertexBuffer(frame.m_cmd, 1, &vb.pBuffer, &stride, &vbOffset); + cmdBindIndexBuffer(frame.m_cmd, ib.pBuffer, INDEX_TYPE_UINT32, ibOffset); + cmdDrawIndexed(frame.m_cmd, indexBufferIndex, 0, 0); + + vertexBufferOffset += vertexBufferIndex; + indexBufferOffset += indexBufferIndex; + } + + endUpdateResource(&vertexUpdateDesc); + endUpdateResource(&indexUpdateDesc); + + mBaseClipRegion.Clear(); + } + + void cGuiSet::ClearRenderObjects() { + m_setRenderObjects.clear(); + } + + //----------------------------------------------------------------------- + + void cGuiSet::DrawGfx( + cGuiGfxElement* apGfx, + const cVector3f& avPos, + const cVector2f& avSize, + const cColor& aColor, + eGuiMaterial aMaterial, + float afRotationAngle, + bool abUseCustomPivot, + const cVector3f& avCustomPivot) { + if (mpCurrentClipRegion == NULL) + return; + if (mpCurrentClipRegion->mRect.w == 0 || mpCurrentClipRegion->mRect.h == 0) + return; + + // Log("Bug:Drawing gfx: %p\n", apGfx); + + cVector3f vAbsPos = avPos + apGfx->GetOffset() + mvDrawOffset; + if (mpCurrentClipRegion->mRect.w > 0) { + cRect2f gfxRect; + gfxRect.x = vAbsPos.x; + gfxRect.y = vAbsPos.y; + if (avSize.x < 0) { + gfxRect.w = apGfx->GetImageSize().x; + gfxRect.h = apGfx->GetImageSize().y; + } else { + gfxRect.w = avSize.x; + gfxRect.h = avSize.y; + } + + if (cMath::CheckRectIntersection(mpCurrentClipRegion->mRect, gfxRect) == false) + return; + } + + apGfx->Flush(); + + cGuiRenderObject object; + + // Log("Clip: %f %f\n",mpCurrentClipRegion->mRect.w,mpCurrentClipRegion->mRect.h); + + ////////////////////////// + // Set Graphics + object.mpGfx = apGfx; + object.mpClipRegion = mpCurrentClipRegion; + + /////////////////////////// + // Position, size and color + object.mvPos = vAbsPos; + if (avSize.x < 0) + object.mvSize = apGfx->GetImageSize(); + else + object.mvSize = avSize; + object.mColor = aColor; + + /////////////////////////// + // Material + object.mpCustomMaterial = aMaterial; + + /////////////////////////// + // Rotation + if (afRotationAngle != 0) { + object.mbRotated = true; + object.mfAngle = afRotationAngle; + + if (abUseCustomPivot) + object.mvPivot = avCustomPivot; + else + object.mvPivot = object.mvSize * 0.5f; + } else { + object.mbRotated = false; + } + + m_setRenderObjects.insert(object); + } + + //----------------------------------------------------------------------- + + void cGuiSet::DrawFont( + const tWString& asText, + iFontData* apFont, + const cVector3f& avPos, + const cVector2f& avSize, + const cColor& aColor, + eFontAlign aAlign, + eGuiMaterial aMaterial) { + DrawTextFromCharArry(asText.c_str(), apFont, avSize, avPos, aColor, aMaterial, aAlign); + } + + //----------------------------------------------------------------------- + + static wchar_t gsTempTextArray[1024]; + void cGuiSet::DrawFont( + iFontData* apFont, + const cVector3f& avPos, + const cVector2f& avSize, + const cColor& aColor, + eFontAlign aAlign, + eGuiMaterial aMaterial, + const wchar_t* fmt, + ...) { + va_list ap; + if (fmt == NULL) + return; + va_start(ap, fmt); + vswprintf(gsTempTextArray, 1023, fmt, ap); + va_end(ap); + + DrawTextFromCharArry(gsTempTextArray, apFont, avSize, avPos, aColor, aMaterial, aAlign); + } + + void cGuiSet::DrawFont( + iFontData* apFont, const cVector3f& avPos, const cVector2f& avSize, const cColor& aColor, const wchar_t* fmt, ...) { + va_list ap; + if (fmt == NULL) + return; + va_start(ap, fmt); + vswprintf(gsTempTextArray, 1023, fmt, ap); + va_end(ap); + + DrawTextFromCharArry(gsTempTextArray, apFont, avSize, avPos, aColor, eGuiMaterial_FontNormal, eFontAlign_Left); + } + + //----------------------------------------------------------------------- + + cWidgetWindow* cGuiSet::CreateWidgetWindow( + tWidgetWindowButtonFlag alFlags, + const cVector3f& avLocalPos, + const cVector2f& avSize, + const tWString& asText, + iWidget* apParent, + const tString& asName) { + cWidgetWindow* pWindow = hplNew(cWidgetWindow, (this, mpSkin, alFlags)); + pWindow->SetPosition(avLocalPos); + pWindow->SetSize(avSize); + pWindow->SetText(asText); + pWindow->SetName(asName); + AddWidget(pWindow, apParent); + + mlstWindows.push_back(pWindow); + + return pWindow; + } + + cWidgetFrame* cGuiSet::CreateWidgetFrame( + const cVector3f& avLocalPos, + const cVector2f& avSize, + bool abDrawFrame, + iWidget* apParent, + bool abHScrollBar, + bool abVScrollBar, + const tString& asName) { + cWidgetFrame* pFrame = hplNew(cWidgetFrame, (this, mpSkin, abHScrollBar, abVScrollBar)); + pFrame->SetPosition(avLocalPos); + pFrame->SetSize(avSize); + pFrame->SetDrawFrame(abDrawFrame); + pFrame->SetName(asName); + AddWidget(pFrame, apParent); + return pFrame; + } + + cWidgetButton* cGuiSet::CreateWidgetButton( + const cVector3f& avLocalPos, + const cVector2f& avSize, + const tWString& asText, + iWidget* apParent, + bool abToggleable, + const tString& asName) { + cWidgetButton* pButton = hplNew(cWidgetButton, (this, mpSkin)); + pButton->SetPosition(avLocalPos); + pButton->SetSize(avSize); + pButton->SetText(asText); + pButton->SetName(asName); + pButton->SetToggleable(abToggleable); + AddWidget(pButton, apParent); + return pButton; + } + + cWidgetLabel* cGuiSet::CreateWidgetLabel( + const cVector3f& avLocalPos, const cVector2f& avSize, const tWString& asText, iWidget* apParent, const tString& asName) { + cWidgetLabel* pLabel = hplNew(cWidgetLabel, (this, mpSkin)); + pLabel->SetPosition(avLocalPos); + pLabel->SetSize(avSize); + pLabel->SetText(asText); + pLabel->SetName(asName); + + if (avSize == -1) { + pLabel->SetAutogenerateSize(true); + pLabel->SetAutogenerateSize(false); + } + + AddWidget(pLabel, apParent); + return pLabel; + } + + cWidgetSlider* cGuiSet::CreateWidgetSlider( + eWidgetSliderOrientation aOrientation, + const cVector3f& avLocalPos, + const cVector2f& avSize, + int alMaxValue, + iWidget* apParent, + const tString& asName) { + cWidgetSlider* pSlider = hplNew(cWidgetSlider, (this, mpSkin, aOrientation)); + pSlider->SetPosition(avLocalPos); + pSlider->SetSize(avSize); + pSlider->SetMaxValue(alMaxValue); + pSlider->SetName(asName); + AddWidget(pSlider, apParent); + return pSlider; + } + + cWidgetTextBox* cGuiSet::CreateWidgetTextBox( + const cVector3f& avLocalPos, + const cVector2f& avSize, + const tWString& asText, + iWidget* apParent, + eWidgetTextBoxInputType aType, + float afNumericAdd, + bool abShowButtons, + const tString& asName) { + cWidgetTextBox* pTextBox = hplNew(cWidgetTextBox, (this, mpSkin, aType)); + pTextBox->SetPosition(avLocalPos); + pTextBox->SetSize(avSize); + pTextBox->SetShowButtons(abShowButtons); + pTextBox->SetNumericAdd(afNumericAdd); + pTextBox->SetText(asText); + pTextBox->SetName(asName); + AddWidget(pTextBox, apParent); + return pTextBox; + } + + cWidgetCheckBox* cGuiSet::CreateWidgetCheckBox( + const cVector3f& avLocalPos, const cVector2f& avSize, const tWString& asText, iWidget* apParent, const tString& asName) { + cWidgetCheckBox* pCheckBox = hplNew(cWidgetCheckBox, (this, mpSkin)); + pCheckBox->SetPosition(avLocalPos); + pCheckBox->SetSize(avSize); + pCheckBox->SetText(asText); + pCheckBox->SetName(asName); + AddWidget(pCheckBox, apParent); + return pCheckBox; + } + + cWidgetImage* cGuiSet::CreateWidgetImage( + const tString& asFile, + const cVector3f& avLocalPos, + const cVector2f& avSize, + eGuiMaterial aMaterial, + bool abAnimate, + iWidget* apParent, + const tString& asName) { + cWidgetImage* pImage = hplNew(cWidgetImage, (this, mpSkin)); + cGuiGfxElement* pGfx = NULL; + if (asFile != "") { + if (abAnimate) { + pGfx = mpGui->CreateGfxImageBuffer(asFile, aMaterial, true); + } else { + pGfx = mpGui->CreateGfxImage(asFile, aMaterial); + } + } + pImage->SetPosition(avLocalPos); + + if (pGfx && avSize.x < 0) { + pImage->SetSize(pGfx->GetImageSize()); + } else { + pImage->SetSize(avSize); + } + + pImage->SetImage(pGfx); + + pImage->SetName(asName); + + AddWidget(pImage, apParent); + return pImage; + } + + cWidgetListBox* cGuiSet::CreateWidgetListBox( + const cVector3f& avLocalPos, const cVector2f& avSize, iWidget* apParent, const tString& asName) { + cWidgetListBox* pListBox = hplNew(cWidgetListBox, (this, mpSkin)); + pListBox->SetPosition(avLocalPos); + pListBox->SetSize(avSize); + pListBox->SetName(asName); + AddWidget(pListBox, apParent); + return pListBox; + } + + cWidgetMultiPropertyListBox* cGuiSet::CreateWidgetMultiPropertyListBox( + const cVector3f& avLocalPos, const cVector2f& avSize, iWidget* apParent, const tString& asName) { + cWidgetMultiPropertyListBox* pListBox = hplNew(cWidgetMultiPropertyListBox, (this, mpSkin)); + pListBox->SetPosition(avLocalPos); + pListBox->SetSize(avSize); + pListBox->SetName(asName); + AddWidget(pListBox, apParent); + return pListBox; + } + + cWidgetComboBox* cGuiSet::CreateWidgetComboBox( + const cVector3f& avLocalPos, const cVector2f& avSize, const tWString& asText, iWidget* apParent, const tString& asName) { + cWidgetComboBox* pComboBox = hplNew(cWidgetComboBox, (this, mpSkin)); + pComboBox->SetPosition(avLocalPos); + pComboBox->SetSize(avSize); + pComboBox->SetText(asText); + pComboBox->SetName(asName); + AddWidget(pComboBox, apParent); + return pComboBox; + } + + cWidgetMenuItem* cGuiSet::CreateWidgetMenuItem( + const cVector3f& avLocalPos, const cVector2f& avSize, const tWString& asText, iWidget* apParent, const tString& asName) { + cWidgetMenuItem* pItem = hplNew(cWidgetMenuItem, ((iWidgetMenu*)apParent)); + pItem->SetPosition(avLocalPos); + pItem->SetSize(avSize); + pItem->SetText(asText); + pItem->SetName(asName); + AddWidget(pItem, apParent); + return pItem; + } + + cWidgetContextMenu* cGuiSet::CreateWidgetContextMenu( + const cVector3f& avLocalPos, const cVector2f& avSize, const tWString& asText, iWidget* apParent, const tString& asName) { + cWidgetContextMenu* pMenu = hplNew(cWidgetContextMenu, (this, mpSkin)); + pMenu->SetPosition(avLocalPos); + pMenu->SetSize(avSize); + pMenu->SetText(asText); + pMenu->SetName(asName); + AddWidget(pMenu, apParent); + return pMenu; + } + + cWidgetMainMenu* cGuiSet::CreateWidgetMainMenu(iWidget* apParent, const tString& asName) { + cWidgetMainMenu* pMenu = hplNew(cWidgetMainMenu, (this, mpSkin)); + pMenu->SetName(asName); + AddWidget(pMenu, apParent); + return pMenu; + } + + cWidgetTabLabel* cGuiSet::CreateWidgetTabLabel( + const cVector3f& avLocalPos, const cVector2f& avSize, const tWString& asText, iWidget* apParent, const tString& asName) { + cWidgetTabLabel* pLabel = hplNew(cWidgetTabLabel, (this, mpSkin)); + pLabel->SetPosition(avLocalPos); + pLabel->SetSize(avSize); + pLabel->SetText(asText); + pLabel->SetName(asName); + AddWidget(pLabel, apParent); + return pLabel; + } + + cWidgetTab* cGuiSet::CreateWidgetTab( + const cVector3f& avLocalPos, const cVector2f& avSize, const tWString& asText, iWidget* apParent, const tString& asName) { + cWidgetTab* pTab = hplNew(cWidgetTab, ((cWidgetTabFrame*)apParent)); pTab->SetPosition(avLocalPos); - pTab->SetSize(avSize); - pTab->SetText(asText); - pTab->SetName(asName); - - AddWidget(pTab,apParent); - return pTab; - } - - cWidgetTabFrame* cGuiSet::CreateWidgetTabFrame( const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - bool abAllowHScroll, - bool abAllowVScroll, - const tString& asName) - { - cWidgetTabFrame *pFrame = hplNew( cWidgetTabFrame, (this,mpSkin) ); + pTab->SetSize(avSize); + pTab->SetText(asText); + pTab->SetName(asName); + + AddWidget(pTab, apParent); + return pTab; + } + + cWidgetTabFrame* cGuiSet::CreateWidgetTabFrame( + const cVector3f& avLocalPos, + const cVector2f& avSize, + const tWString& asText, + iWidget* apParent, + bool abAllowHScroll, + bool abAllowVScroll, + const tString& asName) { + cWidgetTabFrame* pFrame = hplNew(cWidgetTabFrame, (this, mpSkin)); pFrame->SetPosition(avLocalPos); - pFrame->SetSize(avSize); - pFrame->SetText(asText); - pFrame->SetName(asName); - pFrame->SetHorizontalScrollEnabled(abAllowHScroll); - pFrame->SetVerticalScrollEnabled(abAllowVScroll); - AddWidget(pFrame,apParent); - return pFrame; - } - - cWidgetGroup* cGuiSet::CreateWidgetGroup(const cVector3f &avLocalPos, - const cVector2f &avSize, - const tWString &asText, - iWidget *apParent, - const tString& asName) - { - cWidgetGroup* pGroup = hplNew( cWidgetGroup, (this,mpSkin) ); - pGroup->SetPosition(avLocalPos); - pGroup->SetSize(avSize); - pGroup->SetText(asText); - pGroup->SetName(asName); - AddWidget(pGroup,apParent); - return pGroup; - } - - cWidgetDummy* cGuiSet::CreateWidgetDummy(const cVector3f &avLocalPos, - iWidget* apParent, - const tString &asName) - { - cWidgetDummy* pDummy = hplNew( cWidgetDummy, (this,mpSkin) ); - pDummy->SetPosition(avLocalPos); - pDummy->SetName(asName); - AddWidget(pDummy,apParent); - return pDummy; - } - - //----------------------------------------------------------------------- - - iWidget * cGuiSet::GetWidgetFromName(const tString& asName) - { - return (iWidget*)STLFindByName(mlstWidgets, asName); - } - - //----------------------------------------------------------------------- - - void cGuiSet::DestroyWidget(iWidget *apWidget, bool abDestroyChildren) - { - if(apWidget == mpFocusedWidget) mpFocusedWidget = NULL; - mlstTabOrderWidgets.remove(apWidget); - mpTabOrderWidget = NULL; - - if(apWidget==mpCurrentToolTipWidget) - SetToolTipWidget(NULL); - - if(apWidget==mpDefaultFocusNavWidget) - mpDefaultFocusNavWidget = NULL; - - tWidgetList& lstChildren = apWidget->GetChildren(); - if(abDestroyChildren && lstChildren.empty()==false) - { - if(mpTopMostDestroyingWidget==NULL) - { - mpTopMostDestroyingWidget = apWidget; - mbOldDestroyingSet = mbDestroyingSet; - mbDestroyingSet = true; - } - - tWidgetList& lstChildren = apWidget->GetChildren(); - tWidgetListIt it = lstChildren.begin(); - while(it!=lstChildren.end()) - { - iWidget* pWidget = *it; - DestroyWidget(pWidget, true); - - it = lstChildren.begin(); - } - } - - STLFindAndDelete(mlstWidgets, apWidget); - - if(mpTopMostDestroyingWidget==apWidget) - { - mpTopMostDestroyingWidget = NULL; - mbDestroyingSet = mbOldDestroyingSet; - } - } - - //----------------------------------------------------------------------- - - bool cGuiSet::IsValidWidget(iWidget* apWidget) - { - if(apWidget==NULL) - return true; - - tWidgetListIt it = find(mlstWidgets.begin(), mlstWidgets.end(), apWidget); - return (it!=mlstWidgets.end()); - } - - //----------------------------------------------------------------------- - - cGuiPopUpMessageBox* cGuiSet::CreatePopUpMessageBox( const tWString& asLabel, const tWString& asText, - const tWString& asButton1, const tWString& asButton2, - void *apCallbackObject, tGuiCallbackFunc apCallback) - { - cGuiPopUpMessageBox* pMessageBox = hplNew( cGuiPopUpMessageBox, (this, asLabel,asText, - asButton1,asButton2, - apCallbackObject,apCallback) ); - - return pMessageBox; - } - - //----------------------------------------------------------------------- - - cGuiPopUpFilePicker* cGuiSet::CreatePopUpSaveFilePicker( tWString &asFileName, const tWString &asCategory, - const tWString &asFilter, const tWString &asStartPath, bool abShowHidden, - void *apCallbackObject, tGuiCallbackFunc apCallback, const tWString& asStartFilename) - { - cGuiPopUpFilePicker* pPicker = hplNew( cGuiPopUpFilePicker, (this, mpSkin, eFilePickerType_Save, asStartPath, abShowHidden, apCallbackObject, apCallback, asStartFilename) ); - pPicker->Init(); - pPicker->SetSaveFileDest( asFileName ); - - pPicker->AddCategory( asCategory, asFilter ); - - return pPicker; - } - - //----------------------------------------------------------------------- - - /** Returns a handle to the Load file popup, so new filters can be added outside. This handle doesn't need to be destroyed. - * - * \param &avFileList Reference to the destination file name string list - * \param abAddAllFilesFilter If the "all files" (*.*) filter should be added - * \param &asStartPath Where the popup should start browsing - * \param *apCallbackObject - * \param apCallback - * \return - */ - cGuiPopUpFilePicker* cGuiSet::CreatePopUpLoadFilePicker( tWStringVec &avFileList, bool abAddAllFilesFilter, - const tWString &asStartPath, bool abShowHidden, - void *apCallbackObject, tGuiCallbackFunc apCallback) - { - cGuiPopUpFilePicker* pPicker = hplNew( cGuiPopUpFilePicker, (this, mpSkin, eFilePickerType_Load, asStartPath, abShowHidden, apCallbackObject, apCallback) ); - pPicker->Init(); - pPicker->SetLoadFileListDest( avFileList ); - - if(abAddAllFilesFilter) - pPicker->AddCategory(_W("All files"), _W("*.*")); - - return pPicker; - } - - //----------------------------------------------------------------------- - - cGuiPopUpColorPicker* cGuiSet::CreatePopUpColorPicker( cColor* apDestColor, const cVector3f& avPos, void *apCallbackObject, tGuiCallbackFunc apCallback) - { - cGuiPopUpColorPicker* pPicker = hplNew( cGuiPopUpColorPicker,(this, mpSkin, avPos, apDestColor, apCallbackObject, apCallback)); - - return pPicker; - } - - //----------------------------------------------------------------------- - - cGuiPopUpUIKeyboard* cGuiSet::CreatePopUpUIKeyboard(cWidgetTextBox* apTarget) - { - cGuiPopUpUIKeyboard* pKB = hplNew(cGuiPopUpUIKeyboard,(apTarget, NULL, NULL)); + pFrame->SetSize(avSize); + pFrame->SetText(asText); + pFrame->SetName(asName); + pFrame->SetHorizontalScrollEnabled(abAllowHScroll); + pFrame->SetVerticalScrollEnabled(abAllowVScroll); + AddWidget(pFrame, apParent); + return pFrame; + } + + cWidgetGroup* cGuiSet::CreateWidgetGroup( + const cVector3f& avLocalPos, const cVector2f& avSize, const tWString& asText, iWidget* apParent, const tString& asName) { + cWidgetGroup* pGroup = hplNew(cWidgetGroup, (this, mpSkin)); + pGroup->SetPosition(avLocalPos); + pGroup->SetSize(avSize); + pGroup->SetText(asText); + pGroup->SetName(asName); + AddWidget(pGroup, apParent); + return pGroup; + } + + cWidgetDummy* cGuiSet::CreateWidgetDummy(const cVector3f& avLocalPos, iWidget* apParent, const tString& asName) { + cWidgetDummy* pDummy = hplNew(cWidgetDummy, (this, mpSkin)); + pDummy->SetPosition(avLocalPos); + pDummy->SetName(asName); + AddWidget(pDummy, apParent); + return pDummy; + } + + //----------------------------------------------------------------------- + + iWidget* cGuiSet::GetWidgetFromName(const tString& asName) { + return (iWidget*)STLFindByName(mlstWidgets, asName); + } + + //----------------------------------------------------------------------- + + void cGuiSet::DestroyWidget(iWidget* apWidget, bool abDestroyChildren) { + if (apWidget == mpFocusedWidget) + mpFocusedWidget = NULL; + mlstTabOrderWidgets.remove(apWidget); + mpTabOrderWidget = NULL; + + if (apWidget == mpCurrentToolTipWidget) + SetToolTipWidget(NULL); + + if (apWidget == mpDefaultFocusNavWidget) + mpDefaultFocusNavWidget = NULL; + + tWidgetList& lstChildren = apWidget->GetChildren(); + if (abDestroyChildren && lstChildren.empty() == false) { + if (mpTopMostDestroyingWidget == NULL) { + mpTopMostDestroyingWidget = apWidget; + mbOldDestroyingSet = mbDestroyingSet; + mbDestroyingSet = true; + } + + tWidgetList& lstChildren = apWidget->GetChildren(); + tWidgetListIt it = lstChildren.begin(); + while (it != lstChildren.end()) { + iWidget* pWidget = *it; + DestroyWidget(pWidget, true); + + it = lstChildren.begin(); + } + } + + STLFindAndDelete(mlstWidgets, apWidget); + + if (mpTopMostDestroyingWidget == apWidget) { + mpTopMostDestroyingWidget = NULL; + mbDestroyingSet = mbOldDestroyingSet; + } + } + + //----------------------------------------------------------------------- + + bool cGuiSet::IsValidWidget(iWidget* apWidget) { + if (apWidget == NULL) + return true; + + tWidgetListIt it = find(mlstWidgets.begin(), mlstWidgets.end(), apWidget); + return (it != mlstWidgets.end()); + } + + //----------------------------------------------------------------------- + + cGuiPopUpMessageBox* cGuiSet::CreatePopUpMessageBox( + const tWString& asLabel, + const tWString& asText, + const tWString& asButton1, + const tWString& asButton2, + void* apCallbackObject, + tGuiCallbackFunc apCallback) { + cGuiPopUpMessageBox* pMessageBox = + hplNew(cGuiPopUpMessageBox, (this, asLabel, asText, asButton1, asButton2, apCallbackObject, apCallback)); + + return pMessageBox; + } + + //----------------------------------------------------------------------- + + cGuiPopUpFilePicker* cGuiSet::CreatePopUpSaveFilePicker( + tWString& asFileName, + const tWString& asCategory, + const tWString& asFilter, + const tWString& asStartPath, + bool abShowHidden, + void* apCallbackObject, + tGuiCallbackFunc apCallback, + const tWString& asStartFilename) { + cGuiPopUpFilePicker* pPicker = hplNew( + cGuiPopUpFilePicker, + (this, mpSkin, eFilePickerType_Save, asStartPath, abShowHidden, apCallbackObject, apCallback, asStartFilename)); + pPicker->Init(); + pPicker->SetSaveFileDest(asFileName); + + pPicker->AddCategory(asCategory, asFilter); + + return pPicker; + } + + //----------------------------------------------------------------------- + + /** Returns a handle to the Load file popup, so new filters can be added outside. This handle doesn't need to be destroyed. + * + * \param &avFileList Reference to the destination file name string list + * \param abAddAllFilesFilter If the "all files" (*.*) filter should be added + * \param &asStartPath Where the popup should start browsing + * \param *apCallbackObject + * \param apCallback + * \return + */ + cGuiPopUpFilePicker* cGuiSet::CreatePopUpLoadFilePicker( + tWStringVec& avFileList, + bool abAddAllFilesFilter, + const tWString& asStartPath, + bool abShowHidden, + void* apCallbackObject, + tGuiCallbackFunc apCallback) { + cGuiPopUpFilePicker* pPicker = + hplNew(cGuiPopUpFilePicker, (this, mpSkin, eFilePickerType_Load, asStartPath, abShowHidden, apCallbackObject, apCallback)); + pPicker->Init(); + pPicker->SetLoadFileListDest(avFileList); + + if (abAddAllFilesFilter) + pPicker->AddCategory(_W("All files"), _W("*.*")); + + return pPicker; + } + + //----------------------------------------------------------------------- + + cGuiPopUpColorPicker* cGuiSet::CreatePopUpColorPicker( + cColor* apDestColor, const cVector3f& avPos, void* apCallbackObject, tGuiCallbackFunc apCallback) { + cGuiPopUpColorPicker* pPicker = hplNew(cGuiPopUpColorPicker, (this, mpSkin, avPos, apDestColor, apCallbackObject, apCallback)); + + return pPicker; + } + + //----------------------------------------------------------------------- - return pKB; - } + cGuiPopUpUIKeyboard* cGuiSet::CreatePopUpUIKeyboard(cWidgetTextBox* apTarget) { + cGuiPopUpUIKeyboard* pKB = hplNew(cGuiPopUpUIKeyboard, (apTarget, NULL, NULL)); + + return pKB; + } + + //----------------------------------------------------------------------- + + void cGuiSet::DestroyPopUp(iGuiPopUp* apPopUp) { + // mlstPopUps.push_back(apPopUp); + mlstPopUps.push_front(apPopUp); + } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- + + bool cGuiSet::PopUpIsActive() { + return mlPopupCount > 0; + } + + //----------------------------------------------------------------------- + + void cGuiSet::ShowContextMenu(cWidgetContextMenu* apMenu, const cVector3f& avPosition) { + if (apMenu == NULL) + return; + + cVector3f vPos = avPosition; + + if (avPosition.x + apMenu->GetSize().x > mvVirtualSize.x) + vPos.x = mvVirtualSize.x - apMenu->GetSize().x; + if (avPosition.y + apMenu->GetSize().y > mvVirtualSize.y) + vPos.y = mvVirtualSize.y - apMenu->GetSize().y; + apMenu->SetVisible(true); + apMenu->SetEnabled(true); - void cGuiSet::DestroyPopUp(iGuiPopUp *apPopUp) - { - //mlstPopUps.push_back(apPopUp); - mlstPopUps.push_front(apPopUp); - } + apMenu->SetHighlightedItem(NULL); - //----------------------------------------------------------------------- + if (apMenu->GetParentItem() == NULL || apMenu->GetParentMenu()->GetType() == eWidgetType_MainMenu) { + vPos.z = mfContextMenuZ; + IncContextMenuZ(); + } else + vPos.z = apMenu->GetParentMenu()->GetGlobalPosition().z; - bool cGuiSet::PopUpIsActive() - { - return mlPopupCount > 0; - } + SetAttentionWidget(apMenu->GetTopMostMenu()); - //----------------------------------------------------------------------- + apMenu->SetGlobalPosition(vPos); + SetFocusedWidget(apMenu); + } - void cGuiSet::ShowContextMenu( cWidgetContextMenu* apMenu, const cVector3f& avPosition ) - { - if(apMenu==NULL) return; + //----------------------------------------------------------------------- - cVector3f vPos = avPosition; + void cGuiSet::RemoveWindow(cWidgetWindow* apWin) { + mlstWindows.remove(apWin); + } - if(avPosition.x + apMenu->GetSize().x > mvVirtualSize.x) - vPos.x = mvVirtualSize.x - apMenu->GetSize().x; - if(avPosition.y + apMenu->GetSize().y > mvVirtualSize.y) - vPos.y = mvVirtualSize.y - apMenu->GetSize().y; + void cGuiSet::SetLastWindowZ(float afX) { + mfWindowZ = afX; + } - apMenu->SetVisible(true); - apMenu->SetEnabled(true); - - apMenu->SetHighlightedItem(NULL); + void cGuiSet::SetWindowOnTop(cWidgetWindow* apWin) { + tWidgetListIt it = find(mlstWindows.begin(), mlstWindows.end(), apWin); + if (it == mlstWindows.end()) + return; + RemoveWindow(apWin); + mlstWindows.push_back(apWin); - if( apMenu->GetParentItem()==NULL || - apMenu->GetParentMenu()->GetType()==eWidgetType_MainMenu) - { - vPos.z = mfContextMenuZ; - IncContextMenuZ(); - } - else - vPos.z = apMenu->GetParentMenu()->GetGlobalPosition().z; + it = mlstWindows.begin(); + float fHeight = 20.0f; + for (; it != mlstWindows.end(); ++it) { + iWidget* pWin = *it; + cVector3f vPos = pWin->GetGlobalPosition(); + vPos.z = fHeight; + pWin->SetGlobalPosition(vPos); + fHeight += 10.0f; + } + } - SetAttentionWidget(apMenu->GetTopMostMenu()); + //----------------------------------------------------------------------- - apMenu->SetGlobalPosition(vPos); - SetFocusedWidget(apMenu); - } + void cGuiSet::SetActive(bool abX) { + if (mbActive == abX) + return; - //----------------------------------------------------------------------- + mbActive = abX; + } - void cGuiSet::RemoveWindow(cWidgetWindow* apWin) - { - mlstWindows.remove(apWin); - } + //----------------------------------------------------------------------- - void cGuiSet::SetLastWindowZ(float afX) - { - mfWindowZ = afX; - } + void cGuiSet::SetDrawMouse(bool abX) { + if (mbDrawMouse == abX) + return; - void cGuiSet::SetWindowOnTop(cWidgetWindow* apWin) - { - tWidgetListIt it = find(mlstWindows.begin(), mlstWindows.end(), apWin); - if(it==mlstWindows.end()) - return; - RemoveWindow(apWin); - mlstWindows.push_back(apWin); + mbDrawMouse = abX; + } - it = mlstWindows.begin(); - float fHeight = 20.0f; - for(;it!=mlstWindows.end();++it) - { - iWidget* pWin = *it; - cVector3f vPos = pWin->GetGlobalPosition(); - vPos.z = fHeight; + //----------------------------------------------------------------------- - pWin->SetGlobalPosition(vPos); - fHeight+=10.0f; - } - } + void cGuiSet::SetRootWidgetClips(bool abX) { + mpWidgetRoot->SetClipActive(abX); + if (abX) + mpWidgetRoot->SetSize(mvVirtualSize); + else + mpWidgetRoot->SetSize(0); + } - //----------------------------------------------------------------------- + bool cGuiSet::GetRootWidgetClips() { + return mpWidgetRoot->GetClipActive(); + } - void cGuiSet::SetActive(bool abX) - { - if(mbActive == abX) return; + //----------------------------------------------------------------------- - mbActive = abX; - } + void cGuiSet::SetVirtualSize(const cVector2f& avSize, float afMinZ, float afMaxZ, const cVector2f& avOffset) { + mvVirtualSize = avSize; + mfVirtualMinZ = afMinZ; + mfVirtualMaxZ = afMaxZ; + mvVirtualSizeOffset = avOffset; + } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- - void cGuiSet::SetDrawMouse(bool abX) - { - if(mbDrawMouse == abX) return; + void cGuiSet::SetFocusedWidget(iWidget* apWidget, bool abCheckForValidity) { + if (mpFocusedWidget == apWidget) + return; - mbDrawMouse = abX; - } + if (abCheckForValidity && IsValidWidget(apWidget) == false) + apWidget = NULL; - //----------------------------------------------------------------------- + iWidget* pOldFocus = mpFocusedWidget; + cGuiMessageData data = cGuiMessageData(mvMousePos, 0); - void cGuiSet::SetRootWidgetClips(bool abX) - { - mpWidgetRoot->SetClipActive(abX); - if(abX) - mpWidgetRoot->SetSize(mvVirtualSize); - else - mpWidgetRoot->SetSize(0); - } + mpFocusedWidget = apWidget; - bool cGuiSet::GetRootWidgetClips() - { - return mpWidgetRoot->GetClipActive(); - } + if (mpFocusedWidget) + mpFocusedWidget->GetFocus(data); - //----------------------------------------------------------------------- + if (pOldFocus) + pOldFocus->ProcessMessage(eGuiMessage_LostFocus, data); + } - void cGuiSet::SetVirtualSize(const cVector2f& avSize, float afMinZ, float afMaxZ, const cVector2f& avOffset) - { - mvVirtualSize = avSize; - mfVirtualMinZ = afMinZ; - mfVirtualMaxZ = afMaxZ; - mvVirtualSizeOffset = avOffset; - } + //----------------------------------------------------------------------- - //----------------------------------------------------------------------- + void cGuiSet::PushFocusedWidget() { + mlstFocusedStack.push_back(mpFocusedWidget); + } - void cGuiSet::SetFocusedWidget(iWidget* apWidget, bool abCheckForValidity) - { - if(mpFocusedWidget==apWidget) - return; + void cGuiSet::PopFocusedWidget() { + if (mlstFocusedStack.empty()) + return; - if(abCheckForValidity && IsValidWidget(apWidget)==false) - apWidget = NULL; + SetFocusedWidget(mlstFocusedStack.back(), true); + mlstFocusedStack.pop_back(); + } - iWidget* pOldFocus = mpFocusedWidget; - cGuiMessageData data = cGuiMessageData(mvMousePos,0); + //----------------------------------------------------------------------- - mpFocusedWidget = apWidget; + void cGuiSet::SetAttentionWidget(iWidget* apWidget, bool abClearFocus, bool abCheckForValidity) { + if (mpAttentionWidget == apWidget) + return; - if(mpFocusedWidget) - mpFocusedWidget->GetFocus(data); + if (abCheckForValidity && IsValidWidget(apWidget) == false) + apWidget = NULL; - if(pOldFocus) - pOldFocus->ProcessMessage(eGuiMessage_LostFocus, data); - } - - //----------------------------------------------------------------------- - - void cGuiSet::PushFocusedWidget() - { - mlstFocusedStack.push_back(mpFocusedWidget); - } - - void cGuiSet::PopFocusedWidget() - { - if(mlstFocusedStack.empty()) return; - - SetFocusedWidget(mlstFocusedStack.back(), true); - mlstFocusedStack.pop_back(); - } - - //----------------------------------------------------------------------- - - void cGuiSet::SetAttentionWidget(iWidget *apWidget, bool abClearFocus, bool abCheckForValidity) - { - if(mpAttentionWidget == apWidget) return; + mpAttentionWidget = apWidget; + cGuiMessageData data = cGuiMessageData(mvMousePos, 0); - if(abCheckForValidity && IsValidWidget(apWidget)==false) - apWidget = NULL; + // Log("Sett attn: %d\n",mpAttentionWidget); + iWidget* pOldFocus = mpFocusedWidget; - mpAttentionWidget = apWidget; - cGuiMessageData data = cGuiMessageData(mvMousePos, 0); + if (mpFocusedWidget && mpFocusedWidget->IsConnectedTo(mpAttentionWidget) == false) { + // Log("Lost focus %d\n",mpFocusedWidget); - //Log("Sett attn: %d\n",mpAttentionWidget); - iWidget* pOldFocus = mpFocusedWidget; + if (mpAttentionWidget != NULL || abClearFocus) + mpFocusedWidget = NULL; + } - if(mpFocusedWidget && mpFocusedWidget->IsConnectedTo(mpAttentionWidget)==false) - { - //Log("Lost focus %d\n",mpFocusedWidget); + if (mpAttentionWidget && mpFocusedWidget == NULL) { + // Log("Got focus %d\n",apWidget); + mpFocusedWidget = apWidget; + if (mpFocusedWidget) + mpFocusedWidget->ProcessMessage(eGuiMessage_GotFocus, data); + } - if(mpAttentionWidget!= NULL || abClearFocus) - mpFocusedWidget = NULL; - } + if (pOldFocus && pOldFocus != mpFocusedWidget) + pOldFocus->ProcessMessage(eGuiMessage_LostFocus, data); + } - if(mpAttentionWidget && mpFocusedWidget == NULL) - { - //Log("Got focus %d\n",apWidget); - mpFocusedWidget = apWidget; - if(mpFocusedWidget) mpFocusedWidget->ProcessMessage(eGuiMessage_GotFocus, data); - } + //----------------------------------------------------------------------- - if(pOldFocus && pOldFocus != mpFocusedWidget) - pOldFocus->ProcessMessage(eGuiMessage_LostFocus, data); - } + void cGuiSet::PushAttentionWidget() { + mlstAttentionStack.push_back(mpAttentionWidget); + } - //----------------------------------------------------------------------- - - void cGuiSet::PushAttentionWidget() - { - mlstAttentionStack.push_back(mpAttentionWidget); - } - - void cGuiSet::PopAttentionWidget(bool abClearFocus) - { - if(mlstAttentionStack.empty()) return; - - SetAttentionWidget(mlstAttentionStack.back(), abClearFocus, true); - - mlstAttentionStack.pop_back(); - } - - void cGuiSet::SetRendersBeforePostEffects(bool abX) - { - mbRendersBeforePostEffects = abX; - } - - void cGuiSet::SetIs3D(bool abX) - { - mbIs3D = abX; - } - - void cGuiSet::Set3DSize(const cVector3f& avSize) - { - mv3DSize = avSize; - } - - void cGuiSet::Set3DTransform(const cMatrixf& a_mtxTransform) - { - m_mtx3DTransform = a_mtxTransform; - } - - void cGuiSet::SetCurrentPointer(cGuiGfxElement *apGfx) - { - mpGfxCurrentPointer = apGfx; - } - - bool cGuiSet::HasFocus() - { - return mpGui->GetFocusedSet() == this; - } - - void cGuiSet::PositionWidgetInsideBounds(iWidget* apWidget) - { - cVector3f vPos = apWidget->GetGlobalPosition(); - const cVector2f& vSize = apWidget->GetSize(); - const cVector2f& vSetSize = GetVirtualSize(); - - for(int i=0; i<2; ++i) - { - if(vPos.v[i] < 0) - vPos.v[i]=0; - if(vPos.v[i]+vSize.v[i] > vSetSize.v[i]) - vPos.v[i] = vSetSize.v[i]-vSize.v[i]; - } - - apWidget->SetGlobalPosition(vPos); - } - - //----------------------------------------------------------------------- - - void cGuiSet::SetSkin(cGuiSkin* apSkin) - { - //if(mpSkin == apSkin) return; Remove til there is a real skin - - mpSkin = apSkin; - - if(mpSkin) - { - mpGfxCurrentPointer = mpSkin->GetGfx(eGuiSkinGfx_PointerNormal); - } - else - { - mpGfxCurrentPointer = NULL; - } - - } - - void cGuiSet::IncPopUpZ() - { - mfLastPopUpZ += 5.0f; - if(mfLastPopUpZ>=500) - mfLastPopUpZ = 20; - } - - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // PRIVATE METHODS - ////////////////////////////////////////////////////////////////////////// - - //-------------------------------------------------------------- - - void cGuiSet::DrawTextFromCharArry( const wchar_t* apString, iFontData *apFont, - const cVector2f& avSize, const cVector3f& avPosition, - const cColor& aColor, eGuiMaterial aMaterial, - eFontAlign aAlign) - { - int lCount =0; - cVector3f vPos = avPosition; - - ////////////////////////////////////////////////////// - // Change position depending on the alignment - if(aAlign == eFontAlign_Center){ - vPos.x -= apFont->GetLength(avSize, apString)/2; - } - else if(aAlign == eFontAlign_Right) - { - vPos.x -= apFont->GetLength(avSize, apString); - } - - ////////////////////////////////////////////////////// - // Iterate the characters in string until NULL is found - while(apString[lCount] != 0) - { - wchar_t lGlyphNum = ((wchar_t)apString[lCount]); - - //Check if the glyph is valid (in range) - if( lGlyphNum < apFont->GetFirstChar() || - lGlyphNum > apFont->GetLastChar()) - { - lCount++; - continue; - } - //Get actual number of the glyph in the font. - lGlyphNum -= apFont->GetFirstChar(); - - //Get glyph data and draw. - cGlyph *pGlyph = apFont->GetGlyph(lGlyphNum); - if(pGlyph) - { - cVector2f vOffset(pGlyph->mvOffset * avSize); - cVector2f vSize(pGlyph->mvSize * avSize);// *apFont->GetSizeRatio()); - - DrawGfx(pGlyph->mpGuiGfx,vPos + vOffset,vSize,aColor,aMaterial); - - vPos.x += pGlyph->mfAdvance*avSize.x; - } - lCount++; - } - } - - //-------------------------------------------------------------- + void cGuiSet::PopAttentionWidget(bool abClearFocus) { + if (mlstAttentionStack.empty()) + return; + + SetAttentionWidget(mlstAttentionStack.back(), abClearFocus, true); + + mlstAttentionStack.pop_back(); + } + + void cGuiSet::SetRendersBeforePostEffects(bool abX) { + mbRendersBeforePostEffects = abX; + } + + void cGuiSet::SetIs3D(bool abX) { + mbIs3D = abX; + } + + void cGuiSet::Set3DSize(const cVector3f& avSize) { + mv3DSize = avSize; + } + + void cGuiSet::Set3DTransform(const cMatrixf& a_mtxTransform) { + m_mtx3DTransform = a_mtxTransform; + } + + void cGuiSet::SetCurrentPointer(cGuiGfxElement* apGfx) { + mpGfxCurrentPointer = apGfx; + } + + bool cGuiSet::HasFocus() { + return mpGui->GetFocusedSet() == this; + } + + void cGuiSet::PositionWidgetInsideBounds(iWidget* apWidget) { + cVector3f vPos = apWidget->GetGlobalPosition(); + const cVector2f& vSize = apWidget->GetSize(); + const cVector2f& vSetSize = GetVirtualSize(); + + for (int i = 0; i < 2; ++i) { + if (vPos.v[i] < 0) + vPos.v[i] = 0; + if (vPos.v[i] + vSize.v[i] > vSetSize.v[i]) + vPos.v[i] = vSetSize.v[i] - vSize.v[i]; + } + + apWidget->SetGlobalPosition(vPos); + } + + //----------------------------------------------------------------------- + + void cGuiSet::SetSkin(cGuiSkin* apSkin) { + // if(mpSkin == apSkin) return; Remove til there is a real skin + + mpSkin = apSkin; + + if (mpSkin) { + mpGfxCurrentPointer = mpSkin->GetGfx(eGuiSkinGfx_PointerNormal); + } else { + mpGfxCurrentPointer = NULL; + } + } + + void cGuiSet::IncPopUpZ() { + mfLastPopUpZ += 5.0f; + if (mfLastPopUpZ >= 500) + mfLastPopUpZ = 20; + } + + //----------------------------------------------------------------------- + + ////////////////////////////////////////////////////////////////////////// + // PRIVATE METHODS + ////////////////////////////////////////////////////////////////////////// + + //-------------------------------------------------------------- + + void cGuiSet::DrawTextFromCharArry( + const wchar_t* apString, + iFontData* apFont, + const cVector2f& avSize, + const cVector3f& avPosition, + const cColor& aColor, + eGuiMaterial aMaterial, + eFontAlign aAlign) { + int lCount = 0; + cVector3f vPos = avPosition; + + ////////////////////////////////////////////////////// + // Change position depending on the alignment + if (aAlign == eFontAlign_Center) { + vPos.x -= apFont->GetLength(avSize, apString) / 2; + } else if (aAlign == eFontAlign_Right) { + vPos.x -= apFont->GetLength(avSize, apString); + } + + ////////////////////////////////////////////////////// + // Iterate the characters in string until NULL is found + while (apString[lCount] != 0) { + wchar_t lGlyphNum = ((wchar_t)apString[lCount]); + + // Check if the glyph is valid (in range) + if (lGlyphNum < apFont->GetFirstChar() || lGlyphNum > apFont->GetLastChar()) { + lCount++; + continue; + } + // Get actual number of the glyph in the font. + lGlyphNum -= apFont->GetFirstChar(); + + // Get glyph data and draw. + cGlyph* pGlyph = apFont->GetGlyph(lGlyphNum); + if (pGlyph) { + cVector2f vOffset(pGlyph->mvOffset * avSize); + cVector2f vSize(pGlyph->mvSize * avSize); // *apFont->GetSizeRatio()); + + DrawGfx(pGlyph->mpGuiGfx, vPos + vOffset, vSize, aColor, aMaterial); + + vPos.x += pGlyph->mfAdvance * avSize.x; + } + lCount++; + } + } + + //-------------------------------------------------------------- #define kLogRender (false) - void cGuiSet::AddWidget(iWidget *apWidget,iWidget *apParent) - { - mlstWidgets.push_front(apWidget); - - if(apParent) - apParent->AttachChild(apWidget); - else - mpWidgetRoot->AttachChild(apWidget); - - apWidget->Init(); - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnMouseMove(const cGuiMessageData &aData) - { - if(GetMouseMovementEnabled()==false) - return false; - - /////////////////////////// - //Set up variables - mvMousePos = aData.mvPos; - - iWidget* pOldToolTipWidget = mpCurrentToolTipWidget; - iWidget* pNewToolTipWidget = NULL; - - cGuiMessageData tData = aData; - tData.mlVal = 0; - if(mvMouseDown[0]) tData.mlVal |= eGuiMouseButton_Left; - if(mvMouseDown[1]) tData.mlVal |= eGuiMouseButton_Middle; - if(mvMouseDown[2]) tData.mlVal |= eGuiMouseButton_Right; - if(mvMouseDown[3]) tData.mlVal |= eGuiMouseButton_WheelUp; - if(mvMouseDown[4]) tData.mlVal |= eGuiMouseButton_WheelDown; - - /////////////////////////// - //Call widgets - bool bRet = false; - bool bPointerSet = false; - bool bToolTipWidgetSet = false; - bool bToolTipWidgetLeft = false; - iWidget* pWidgetUnderMouse=NULL; - - /////////////////////////// - // Widgets should be sorted by z value, so the first check must be the widget that is right under the mouse - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - if(pWidget->IsVisible()==false) - continue; - - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - continue; - - if(pWidget->PointIsInside(mvMousePos,false)) - { - if(pWidgetUnderMouse==NULL || - pWidgetUnderMouse->IsConnectedTo(pWidget) || - pWidget->IsConnectedTo(pWidgetUnderMouse)) - { - if(pWidgetUnderMouse==NULL) - pWidgetUnderMouse=pWidget; - - //////////////////////////// - //Mouse enter event - if(pWidget->GetMouseIsOver()==false) - { - pWidget->SetMouseIsOver(true); - if(pWidget->ProcessMessage(eGuiMessage_MouseEnter, tData)) - { - bRet = true; - } - - //////////////////////////// - //Set up tooltips on mouse enter - if(pWidget->IsToolTipEnabled()) - { - if(bToolTipWidgetSet==false) - { - bToolTipWidgetSet = true; - pNewToolTipWidget = pWidget; - - if(pNewToolTipWidget!=pOldToolTipWidget) - mfToolTipTimer = 0; - } - } - - if(pWidget->HasFocusNavigation() && pWidget->IsVisible() && pWidget->IsEnabled()) - { - iWidget *pOldFocus = mpFocusedWidget; - - if(pOldFocus==NULL || (pOldFocus->GetParent() == pWidget->GetParent() - && pOldFocus->GetSet() == pWidget->GetSet())) - { - SetFocusedWidget(pWidget); - } - } - } - - //////////////////////////// - //Set pointer - if(bPointerSet==false && pWidget->GetPointerGfx()) - { - if( mpAttentionWidget && - pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - } - else - { - if(pWidget->IsEnabled()) - { - if(mpGfxCurrentPointer != pWidget->GetPointerGfx()) - SetCurrentPointer(pWidget->GetPointerGfx()); - } - else - { - SetCurrentPointer(mpSkin->GetGfx(eGuiSkinGfx_PointerNormal)); - } - bPointerSet = true; - } - } - } - } - else - { - //////////////////////////// - //Mouse leave event - if(pWidget->GetMouseIsOver()) - { - pWidget->SetMouseIsOver(false); - pWidget->ProcessMessage(eGuiMessage_MouseLeave, tData); - - //In case the widget is moved under the mouse again, check: - if(mpFocusedWidget == pWidget && pWidget->PointIsInside(mvMousePos, false)) - { - pWidget->SetMouseIsOver(true); - if(pWidget->ProcessMessage(eGuiMessage_MouseEnter, tData)) bRet = true; - } - else - { - if(pOldToolTipWidget==pWidget) - bToolTipWidgetLeft = true; - } - } - } - - //////////////////////////// - //Mouse move event - if(pWidget->GetMouseIsOver() || mpFocusedWidget == pWidget) - { - if(pWidget->ProcessMessage(eGuiMessage_MouseMove, tData)) bRet = true; - } - } - - if(bToolTipWidgetSet) - { - mpCurrentToolTipWidget = pNewToolTipWidget; - } - else if(bToolTipWidgetLeft) - { - mpCurrentToolTipWidget=NULL; - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnMouseDown(const cGuiMessageData& aData) - { - /////////////////////////// - //Set up variables - mvMouseDown[cMath::Log2ToInt(aData.mlVal)] = true; - - cGuiMessageData tData = aData; - tData.mvPos = mvMousePos; - - iWidget *pOldFocus = mpFocusedWidget; - - /////////////////////////// - //Call widgets - bool bRet = false; - - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - //If widget is not visible, skip it - if(pWidget->IsVisible()==false) - continue; - - //If there is an attention set, do not send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - if(pWidget->GetMouseIsOver()) - { - if(mpFocusedWidget != pWidget) - { - if(pWidget->GetFocus(tData)) - { - mpFocusedWidget = pWidget; - } - } - //else - //{ - // mpFocusedWidget = pWidget; - //} - - //Log("Got focus %d\n",pWidget); - - if(pWidget->ProcessMessage(eGuiMessage_MouseDown, tData)) - { - bRet = true; - break; - } - } - } - - //Se if anything was clicked - if(bRet == false) - mpFocusedWidget = NULL; - - //Lost focus callback - if(mpFocusedWidget != pOldFocus) - { - //Log("Lost focus %d\n",pOldFocus); - if(pOldFocus && IsValidWidget(pOldFocus)) pOldFocus->ProcessMessage(eGuiMessage_LostFocus, tData, true, true); - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnMouseUp(const cGuiMessageData& aData) - { - /////////////////////////// - //Set up variables - mvMouseDown[cMath::Log2ToInt(aData.mlVal)] = false; - - cGuiMessageData tData = aData; - tData.mvPos = mvMousePos; - - //mlstWidgets.sort(SortWidget_Z); - - /////////////////////////// - //Call widgets - bool bRet = false; - - if(mpFocusedWidget) - { - bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_MouseUp, tData); - } - - if(bRet == false) - { - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - //If these is an attention set, do send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - if(pWidget != mpFocusedWidget && pWidget->GetMouseIsOver()) - { - if(pWidget->ProcessMessage(eGuiMessage_MouseUp, tData)) - { - bRet = true; - break; - } - } - } - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnMouseDoubleClick(const cGuiMessageData& aData) - { - /////////////////////////// - //Set up variables - cGuiMessageData tData = aData; - tData.mvPos = mvMousePos; - - /////////////////////////// - //Call widgets + void cGuiSet::AddWidget(iWidget* apWidget, iWidget* apParent) { + mlstWidgets.push_front(apWidget); + + if (apParent) + apParent->AttachChild(apWidget); + else + mpWidgetRoot->AttachChild(apWidget); + + apWidget->Init(); + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnMouseMove(const cGuiMessageData& aData) { + if (GetMouseMovementEnabled() == false) + return false; + + /////////////////////////// + // Set up variables + mvMousePos = aData.mvPos; + + iWidget* pOldToolTipWidget = mpCurrentToolTipWidget; + iWidget* pNewToolTipWidget = NULL; + + cGuiMessageData tData = aData; + tData.mlVal = 0; + if (mvMouseDown[0]) + tData.mlVal |= eGuiMouseButton_Left; + if (mvMouseDown[1]) + tData.mlVal |= eGuiMouseButton_Middle; + if (mvMouseDown[2]) + tData.mlVal |= eGuiMouseButton_Right; + if (mvMouseDown[3]) + tData.mlVal |= eGuiMouseButton_WheelUp; + if (mvMouseDown[4]) + tData.mlVal |= eGuiMouseButton_WheelDown; + + /////////////////////////// + // Call widgets + bool bRet = false; + bool bPointerSet = false; + bool bToolTipWidgetSet = false; + bool bToolTipWidgetLeft = false; + iWidget* pWidgetUnderMouse = NULL; + + /////////////////////////// + // Widgets should be sorted by z value, so the first check must be the widget that is right under the mouse + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + if (pWidget->IsVisible() == false) + continue; + + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) + continue; + + if (pWidget->PointIsInside(mvMousePos, false)) { + if (pWidgetUnderMouse == NULL || pWidgetUnderMouse->IsConnectedTo(pWidget) || pWidget->IsConnectedTo(pWidgetUnderMouse)) { + if (pWidgetUnderMouse == NULL) + pWidgetUnderMouse = pWidget; + + //////////////////////////// + // Mouse enter event + if (pWidget->GetMouseIsOver() == false) { + pWidget->SetMouseIsOver(true); + if (pWidget->ProcessMessage(eGuiMessage_MouseEnter, tData)) { + bRet = true; + } + + //////////////////////////// + // Set up tooltips on mouse enter + if (pWidget->IsToolTipEnabled()) { + if (bToolTipWidgetSet == false) { + bToolTipWidgetSet = true; + pNewToolTipWidget = pWidget; + + if (pNewToolTipWidget != pOldToolTipWidget) + mfToolTipTimer = 0; + } + } + + if (pWidget->HasFocusNavigation() && pWidget->IsVisible() && pWidget->IsEnabled()) { + iWidget* pOldFocus = mpFocusedWidget; + + if (pOldFocus == NULL || + (pOldFocus->GetParent() == pWidget->GetParent() && pOldFocus->GetSet() == pWidget->GetSet())) { + SetFocusedWidget(pWidget); + } + } + } + + //////////////////////////// + // Set pointer + if (bPointerSet == false && pWidget->GetPointerGfx()) { + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + } else { + if (pWidget->IsEnabled()) { + if (mpGfxCurrentPointer != pWidget->GetPointerGfx()) + SetCurrentPointer(pWidget->GetPointerGfx()); + } else { + SetCurrentPointer(mpSkin->GetGfx(eGuiSkinGfx_PointerNormal)); + } + bPointerSet = true; + } + } + } + } else { + //////////////////////////// + // Mouse leave event + if (pWidget->GetMouseIsOver()) { + pWidget->SetMouseIsOver(false); + pWidget->ProcessMessage(eGuiMessage_MouseLeave, tData); + + // In case the widget is moved under the mouse again, check: + if (mpFocusedWidget == pWidget && pWidget->PointIsInside(mvMousePos, false)) { + pWidget->SetMouseIsOver(true); + if (pWidget->ProcessMessage(eGuiMessage_MouseEnter, tData)) + bRet = true; + } else { + if (pOldToolTipWidget == pWidget) + bToolTipWidgetLeft = true; + } + } + } + + //////////////////////////// + // Mouse move event + if (pWidget->GetMouseIsOver() || mpFocusedWidget == pWidget) { + if (pWidget->ProcessMessage(eGuiMessage_MouseMove, tData)) + bRet = true; + } + } + + if (bToolTipWidgetSet) { + mpCurrentToolTipWidget = pNewToolTipWidget; + } else if (bToolTipWidgetLeft) { + mpCurrentToolTipWidget = NULL; + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnMouseDown(const cGuiMessageData& aData) { + /////////////////////////// + // Set up variables + mvMouseDown[cMath::Log2ToInt(aData.mlVal)] = true; + + cGuiMessageData tData = aData; + tData.mvPos = mvMousePos; + + iWidget* pOldFocus = mpFocusedWidget; + + /////////////////////////// + // Call widgets bool bRet = false; - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - //If these is an attention set, do send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - if(pWidget->GetMouseIsOver()) - { - if(pWidget->ProcessMessage(eGuiMessage_MouseDoubleClick, tData)) - { - bRet = true; - break; - } - } - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnKeyPress(const cGuiMessageData& aData) - { - /////////////////////////// - //Set up variables - cGuiMessageData tData = aData; - tData.mvPos = mvMousePos; - - /////////////////////////// - //Call widgets - bool bRet = false; - - /////////////////////////// - // Check tab order (temporary - this should be handled by iWidget, for widgets capable of containing other widgets) - if(bRet==false && tData.mKeyPress.mKey==eKey_Tab && mlstTabOrderWidgets.empty()==false) - { - iWidget* pOldWidgetToFocus = mpTabOrderWidget; - iWidget* pNewWidgetToFocus=NULL; - - tWidgetListIt it = find(mlstTabOrderWidgets.begin(), mlstTabOrderWidgets.end(), mpFocusedWidget); - if(it==mlstTabOrderWidgets.end()) - it = find(mlstTabOrderWidgets.begin(), mlstTabOrderWidgets.end(), pOldWidgetToFocus); - - if(it!=mlstTabOrderWidgets.end()) - { - do - { - if(tData.mKeyPress.mlModifier==eKeyModifier_Shift) - { - if(it==mlstTabOrderWidgets.begin()) - it=mlstTabOrderWidgets.end(); - --it; - } - else if(tData.mKeyPress.mlModifier==eKeyModifier_None) - { - ++it; - if(it==mlstTabOrderWidgets.end()) - it=mlstTabOrderWidgets.begin(); - } - - pNewWidgetToFocus = *it; - } - while(pNewWidgetToFocus->IsVisible()==false && pNewWidgetToFocus->IsEnabled()==false); - } - - if(pNewWidgetToFocus && pNewWidgetToFocus->IsVisible() && pNewWidgetToFocus->IsEnabled()) - { - mpTabOrderWidget = pNewWidgetToFocus; - SetFocusedWidget(mpTabOrderWidget); - mpTabOrderWidget->OnGotTabFocus(tData); - bRet = true; - } - } - - - if(bRet==false) - { - if(mpFocusedWidget) - bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_KeyPress, tData); - - if(bRet==false) - { - eKey key = tData.mKeyPress.mKey; - eUIArrow dir = TranslateKeyToUIArrow(key); - - if(dir!=eUIArrow_LastEnum) - bRet = SendMessage(eGuiMessage_UIArrowPress, dir); - } - } - - - - if(bRet==false) - { - // Steal focus from current widget - iWidget* pFocusedWidget = mpFocusedWidget; - SetFocusedWidget(NULL); - - bRet = ExecShortcut(tData.mKeyPress); - - // Restore focus if shortcut did not set own - if(mpFocusedWidget==NULL) + + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If widget is not visible, skip it + if (pWidget->IsVisible() == false) + continue; + + // If there is an attention set, do not send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + if (pWidget->GetMouseIsOver()) { + if (mpFocusedWidget != pWidget) { + if (pWidget->GetFocus(tData)) { + mpFocusedWidget = pWidget; + } + } + // else + //{ + // mpFocusedWidget = pWidget; + // } + + // Log("Got focus %d\n",pWidget); + + if (pWidget->ProcessMessage(eGuiMessage_MouseDown, tData)) { + bRet = true; + break; + } + } + } + + // Se if anything was clicked + if (bRet == false) + mpFocusedWidget = NULL; + + // Lost focus callback + if (mpFocusedWidget != pOldFocus) { + // Log("Lost focus %d\n",pOldFocus); + if (pOldFocus && IsValidWidget(pOldFocus)) + pOldFocus->ProcessMessage(eGuiMessage_LostFocus, tData, true, true); + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnMouseUp(const cGuiMessageData& aData) { + /////////////////////////// + // Set up variables + mvMouseDown[cMath::Log2ToInt(aData.mlVal)] = false; + + cGuiMessageData tData = aData; + tData.mvPos = mvMousePos; + + // mlstWidgets.sort(SortWidget_Z); + + /////////////////////////// + // Call widgets + bool bRet = false; + + if (mpFocusedWidget) { + bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_MouseUp, tData); + } + + if (bRet == false) { + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If these is an attention set, do send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + if (pWidget != mpFocusedWidget && pWidget->GetMouseIsOver()) { + if (pWidget->ProcessMessage(eGuiMessage_MouseUp, tData)) { + bRet = true; + break; + } + } + } + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnMouseDoubleClick(const cGuiMessageData& aData) { + /////////////////////////// + // Set up variables + cGuiMessageData tData = aData; + tData.mvPos = mvMousePos; + + /////////////////////////// + // Call widgets + bool bRet = false; + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If these is an attention set, do send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + if (pWidget->GetMouseIsOver()) { + if (pWidget->ProcessMessage(eGuiMessage_MouseDoubleClick, tData)) { + bRet = true; + break; + } + } + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnKeyPress(const cGuiMessageData& aData) { + /////////////////////////// + // Set up variables + cGuiMessageData tData = aData; + tData.mvPos = mvMousePos; + + /////////////////////////// + // Call widgets + bool bRet = false; + + /////////////////////////// + // Check tab order (temporary - this should be handled by iWidget, for widgets capable of containing other widgets) + if (bRet == false && tData.mKeyPress.mKey == eKey_Tab && mlstTabOrderWidgets.empty() == false) { + iWidget* pOldWidgetToFocus = mpTabOrderWidget; + iWidget* pNewWidgetToFocus = NULL; + + tWidgetListIt it = find(mlstTabOrderWidgets.begin(), mlstTabOrderWidgets.end(), mpFocusedWidget); + if (it == mlstTabOrderWidgets.end()) + it = find(mlstTabOrderWidgets.begin(), mlstTabOrderWidgets.end(), pOldWidgetToFocus); + + if (it != mlstTabOrderWidgets.end()) { + do { + if (tData.mKeyPress.mlModifier == eKeyModifier_Shift) { + if (it == mlstTabOrderWidgets.begin()) + it = mlstTabOrderWidgets.end(); + --it; + } else if (tData.mKeyPress.mlModifier == eKeyModifier_None) { + ++it; + if (it == mlstTabOrderWidgets.end()) + it = mlstTabOrderWidgets.begin(); + } + + pNewWidgetToFocus = *it; + } while (pNewWidgetToFocus->IsVisible() == false && pNewWidgetToFocus->IsEnabled() == false); + } + + if (pNewWidgetToFocus && pNewWidgetToFocus->IsVisible() && pNewWidgetToFocus->IsEnabled()) { + mpTabOrderWidget = pNewWidgetToFocus; + SetFocusedWidget(mpTabOrderWidget); + mpTabOrderWidget->OnGotTabFocus(tData); + bRet = true; + } + } + + if (bRet == false) { + if (mpFocusedWidget) + bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_KeyPress, tData); + + if (bRet == false) { + eKey key = tData.mKeyPress.mKey; + eUIArrow dir = TranslateKeyToUIArrow(key); + + if (dir != eUIArrow_LastEnum) + bRet = SendMessage(eGuiMessage_UIArrowPress, dir); + } + } + + if (bRet == false) { + // Steal focus from current widget + iWidget* pFocusedWidget = mpFocusedWidget; + SetFocusedWidget(NULL); + + bRet = ExecShortcut(tData.mKeyPress); + + // Restore focus if shortcut did not set own + if (mpFocusedWidget == NULL) SetFocusedWidget(pFocusedWidget); - } - - if(bRet==false) - { - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - //If these is an attention set, do send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - if(pWidget->GetMouseIsOver() || pWidget->IsGlobalKeyPressListener() && mpFocusedWidget != pWidget) - { - if(pWidget->ProcessMessage(eGuiMessage_KeyPress, tData)) - { - bRet = true; - break; - } - } - } - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnKeyRelease(const cGuiMessageData& aData) - { - /////////////////////////// - //Set up variables - cGuiMessageData tData = aData; - tData.mvPos = mvMousePos; - - /////////////////////////// - //Call widgets - bool bRet = false; - - if(mpFocusedWidget) - { - bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_KeyRelease, tData); - if(bRet==false) - { - eKey key = tData.mKeyPress.mKey; - eUIArrow dir = TranslateKeyToUIArrow(key); - - if(dir!=eUIArrow_LastEnum) - bRet = SendMessage(eGuiMessage_UIArrowRelease, dir); - } - } - - if(bRet==false) - { - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - //If these is an attention set, do send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - if(pWidget->GetMouseIsOver() && mpFocusedWidget != pWidget) - { - if(pWidget->ProcessMessage(eGuiMessage_KeyRelease, tData)) - { - bRet = true; - break; - } - } - } - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnGamepadInput(const cGuiMessageData& aData) - { - /////////////////////////// - //Set up variables - cGuiMessageData tData = aData; - - /////////////////////////// - //Call widgets - bool bRet = false; - - if(mpFocusedWidget) - { - bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_GamepadInput, tData); - } - - if(bRet==false) - { - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - //If these is an attention set, do send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - if(pWidget->GetMouseIsOver() && mpFocusedWidget != pWidget) - { - if(pWidget->ProcessMessage(eGuiMessage_GamepadInput, tData)) - { - bRet = true; - break; - } - } - } - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnUIArrowPress(const cGuiMessageData& aData) - { - /////////////////////////////////////////////////////////////////////////////////////////////// - // First check if we have a proper start point, if we are not and cannot set one, just skip - if(mpFocusedWidget==NULL || - mpFocusedWidget->HasFocusNavigation()==false && mpFocusedWidget!=mpDefaultFocusNavWidget) - { - if(mpDefaultFocusNavWidget==NULL) - { - return false; - } - else - { - if(mpAttentionWidget==NULL || mpDefaultFocusNavWidget->IsConnectedTo(mpAttentionWidget)) - { - SetFocusedWidget(mpDefaultFocusNavWidget); - mpFocusedWidget->ProcessMessage(eGuiMessage_GetUINavFocus, cGuiMessageData()); - - return true; - } - return false; - } - } - - bool bRet = false; - - /////////////////////////////////////////////////////////////////////////////////////////////// - // Check if widget likes the arrow press for anything else other than moving away, - // if not the case, just get next widget and check for validity - if(mpFocusedWidget) bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_UIArrowPress, aData); - - if(bRet==false) - { - iWidget* pNextWidget = mpFocusedWidget->GetFocusNavigation((eUIArrow)aData.mlVal); - - if(pNextWidget && - pNextWidget->IsEnabled() && - pNextWidget->IsVisible() && - (mpAttentionWidget==NULL || pNextWidget->IsConnectedTo(mpAttentionWidget))) - { - iWidget *pOldFocus = mpFocusedWidget; - SetFocusedWidget(pNextWidget); - - // Do whatever stuff the widget wants to do when getting the focus through arrows - mpFocusedWidget->ProcessMessage(eGuiMessage_GetUINavFocus, cGuiMessageData()); - pOldFocus->ProcessMessage(eGuiMessage_LoseUINavFocus, cGuiMessageData()); - bRet = true; - } - } - - /////////////////////////////////////////////////////////////////////////// - // If we still haven't consumed the input, check for global listeners - if(bRet==false) - { - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - // If widget is not eligible for input check, skip it (or if it's the focused one, we already checked that) - if(pWidget->IsGlobalUIInputListener()==false || pWidget==mpFocusedWidget || pWidget->IsVisible()==false) - continue; - - //If there is an attention set, do not send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - bRet = pWidget->ProcessMessage(eGuiMessage_UIArrowPress, aData); - if(bRet) - break; - } - } - - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnUIArrowRelease(const cGuiMessageData& aData) - { - if(mpFocusedWidget==NULL) - { - return false; - } - - bool bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_UIArrowRelease, aData); - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnUIButtonPress(const cGuiMessageData& aData) - { - /////////////////////////// - //Call widgets - bool bRet = false; - if(mpFocusedWidget) - bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_UIButtonPress, aData); - - if(bRet==false) - { - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - // If widget is not eligible for input check, skip it (or if it's the focused one, we already checked that) - if(pWidget->IsGlobalUIInputListener()==false || pWidget==mpFocusedWidget || pWidget->IsVisible()==false) - continue; - - //If there is an attention set, do not send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - bRet = pWidget->ProcessMessage(eGuiMessage_UIButtonPress, aData); - if(bRet) - break; - } - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnUIButtonRelease(const cGuiMessageData& aData) - { - /////////////////////////// - //Call widgets - bool bRet = false; - if(mpFocusedWidget) - bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_UIButtonRelease, aData); - - if(bRet==false) - { - tWidgetListIt it = mlstWidgets.begin(); - for(; it != mlstWidgets.end(); ++it) - { - iWidget *pWidget = *it; - - // If widget is not eligible for input check, skip it (or if it's the focused one, we already checked that) - if(pWidget->IsGlobalUIInputListener()==false || pWidget==mpFocusedWidget || pWidget->IsVisible()==false) - continue; - - //If there is an attention set, do not send clicks to any other widgets - if(mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget)==false) - { - continue; - } - - bRet = pWidget->ProcessMessage(eGuiMessage_UIButtonRelease, aData); - if(bRet) - break; - } - } - - return bRet; - } - - //----------------------------------------------------------------------- - - bool cGuiSet::OnUIButtonDoublePress(const cGuiMessageData& aData) - { - if(mpFocusedWidget==NULL) return false; - - return mpFocusedWidget->ProcessMessage(eGuiMessage_UIButtonDoublePress, aData); - } - - //----------------------------------------------------------------------- - - bool cGuiSet::DrawMouse(iWidget* apWidget, const cGuiMessageData& aData) - { - if(HasFocus() && mbDrawMouse && mpGfxCurrentPointer) - { - DrawGfx(mpGfxCurrentPointer,cVector3f(mvMousePos.x,mvMousePos.y, mfMouseZ), - mpGfxCurrentPointer->GetImageSize(),cColor(1,1)); - } - - return true; - } - kGuiCallbackDeclaredFuncEnd(cGuiSet,DrawMouse) - - //----------------------------------------------------------------------- - - bool cGuiSet::DrawFocus(iWidget* apWidget, const cGuiMessageData& aData) - { - if(HasFocus() && mpFocusedWidget && mbDrawFocus && - (mpFocusedWidget==mpDefaultFocusNavWidget || mpFocusedWidget->HasFocusNavigation())) - { - if(mpFocusDrawObject && mpFocusDrawCallback) - mpFocusDrawCallback(mpFocusDrawObject, mpFocusedWidget, aData); - else - { - cVector3f vPos = mpFocusedWidget->GetGlobalPosition(); - vPos.z = mfMouseZ-1.0f; - DrawGfx(cGui::mpGfxRect, vPos, mpFocusedWidget->GetSize(), cColor(0.8f,0.2f)); - } - } - - return true; - } - kGuiCallbackDeclaredFuncEnd(cGuiSet,DrawFocus) - - //----------------------------------------------------------------------- - - bool cGuiSet::ExecShortcut(const cKeyPress& aKeyPress) - { - bool bRet = false; - tShortcutListIt it = mlstShortcuts.begin(); - for(;it!=mlstShortcuts.end();++it) - { - cGuiGlobalShortcut* pShortcut = *it; - bRet = pShortcut->ProcessKeyPress(aKeyPress); - if(bRet) - break; - } - - return bRet; - } - - //----------------------------------------------------------------------- - - void cGuiSet::UpdateToolTip(float afTimeStep) - { - if(mpSkin==NULL || mpFrameToolTip==NULL) return; - - if(mpCurrentToolTipWidget==NULL || mpCurrentToolTipWidget->IsVisible()==false) - { - if(mpFrameToolTip->IsVisible()) - { - mpFrameToolTip->SetEnabled(false); - mpFrameToolTip->SetVisible(false); - } - } - else - { - if(mfToolTipTimer>=mfToolTipTimeToPopUp) - { - if(mpFrameToolTip->IsVisible()==false) - { - const tWString& sTipText = mpCurrentToolTipWidget->GetToolTip().c_str(); - const cVector2f& mvFontSize = mpLabelToolTip->GetDefaultFontSize(); - - float fTextLength = mpLabelToolTip->GetDefaultFontType()->GetLength(mvFontSize, - sTipText.c_str()) + 3 + 3; - float fMaxTextLength = GetVirtualSize().x*0.4f; - iFontData* pFont = mpLabelToolTip->GetDefaultFontType(); - - tWStringVec vRows; - pFont->GetWordWrapRows(fMaxTextLength, mvFontSize.y+2, mvFontSize, sTipText, &vRows); - int lRows = (int)vRows.size(); - - cVector3f vPos = mvMousePos + mpGfxCurrentPointer->GetImageSize(); - vPos.z = mfMouseZ - 2; - - cVector2f vToolTipSize = cVector2f( cMath::Min(fTextLength, fMaxTextLength), - lRows*(mvFontSize.y+2) -2 +3 +3); - - mpLabelToolTip->SetText(sTipText); - mpLabelToolTip->SetSize(vToolTipSize); - - if(vPos.x + vToolTipSize.x > mvVirtualSize.x) - vPos.x = mvVirtualSize.x-vToolTipSize.x; - if(vPos.y + vToolTipSize.y > mvVirtualSize.y) - vPos.y = mvVirtualSize.y-vToolTipSize.y; - - mpFrameToolTip->SetGlobalPosition(vPos); - mpFrameToolTip->SetSize(vToolTipSize); - - mpFrameBGToolTip->SetSize(vToolTipSize-2); - - mpFrameToolTip->SetEnabled(true); - mpFrameToolTip->SetVisible(true); - } - } - else - { - mfToolTipTimer+=afTimeStep; - - if(mpFrameToolTip->IsVisible()) - { - mpFrameToolTip->SetEnabled(false); - mpFrameToolTip->SetVisible(false); - } - } - } - } - - //----------------------------------------------------------------------- - - void cGuiSet::CreateToolTipWidgets() - { - mpFrameToolTip = CreateWidgetFrame(0,0,false); - mpFrameToolTip->SetBackGroundColor(cColor(0,1)); - mpFrameToolTip->SetDrawBackground(true); - mpFrameToolTip->SetEnabled(false); - mpFrameToolTip->SetVisible(false); - - mpFrameBGToolTip = CreateWidgetFrame(cVector3f(1,1,0.1f),0,false,mpFrameToolTip); - mpFrameBGToolTip->SetBackGroundColor(cColor(1,1,0.882f,1)); - mpFrameBGToolTip->SetDrawBackground(true); - - mpLabelToolTip = CreateWidgetLabel(cVector3f(3,2,0.1f),0,_W(""), mpFrameToolTip); - mpLabelToolTip->SetDefaultFontSize(12); - mpLabelToolTip->SetWordWrap(true); - } - - //----------------------------------------------------------------------- - - eUIArrow cGuiSet::TranslateKeyToUIArrow(eKey aKey) - { - switch(aKey) - { - case eKey_Up: return eUIArrow_Up; - case eKey_Right: return eUIArrow_Right; - case eKey_Down: return eUIArrow_Down; - case eKey_Left: return eUIArrow_Left; - default: return eUIArrow_LastEnum; - } - } - - //----------------------------------------------------------------------- - - void cGuiSet::AddToTabOrder(iWidget* apWidget) - { - if(apWidget && find(mlstTabOrderWidgets.begin(), mlstTabOrderWidgets.end(), apWidget)==mlstTabOrderWidgets.end()) - mlstTabOrderWidgets.push_back(apWidget); - - mpTabOrderWidget = mlstTabOrderWidgets.front(); - } - - //----------------------------------------------------------------------- - - void cGuiSet::ClearTabOrder() - { - mlstTabOrderWidgets.clear(); + } + + if (bRet == false) { + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If these is an attention set, do send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + if (pWidget->GetMouseIsOver() || pWidget->IsGlobalKeyPressListener() && mpFocusedWidget != pWidget) { + if (pWidget->ProcessMessage(eGuiMessage_KeyPress, tData)) { + bRet = true; + break; + } + } + } + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnKeyRelease(const cGuiMessageData& aData) { + /////////////////////////// + // Set up variables + cGuiMessageData tData = aData; + tData.mvPos = mvMousePos; + + /////////////////////////// + // Call widgets + bool bRet = false; + + if (mpFocusedWidget) { + bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_KeyRelease, tData); + if (bRet == false) { + eKey key = tData.mKeyPress.mKey; + eUIArrow dir = TranslateKeyToUIArrow(key); + + if (dir != eUIArrow_LastEnum) + bRet = SendMessage(eGuiMessage_UIArrowRelease, dir); + } + } + + if (bRet == false) { + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If these is an attention set, do send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + if (pWidget->GetMouseIsOver() && mpFocusedWidget != pWidget) { + if (pWidget->ProcessMessage(eGuiMessage_KeyRelease, tData)) { + bRet = true; + break; + } + } + } + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnGamepadInput(const cGuiMessageData& aData) { + /////////////////////////// + // Set up variables + cGuiMessageData tData = aData; + + /////////////////////////// + // Call widgets + bool bRet = false; + + if (mpFocusedWidget) { + bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_GamepadInput, tData); + } + + if (bRet == false) { + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If these is an attention set, do send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + if (pWidget->GetMouseIsOver() && mpFocusedWidget != pWidget) { + if (pWidget->ProcessMessage(eGuiMessage_GamepadInput, tData)) { + bRet = true; + break; + } + } + } + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnUIArrowPress(const cGuiMessageData& aData) { + /////////////////////////////////////////////////////////////////////////////////////////////// + // First check if we have a proper start point, if we are not and cannot set one, just skip + if (mpFocusedWidget == NULL || mpFocusedWidget->HasFocusNavigation() == false && mpFocusedWidget != mpDefaultFocusNavWidget) { + if (mpDefaultFocusNavWidget == NULL) { + return false; + } else { + if (mpAttentionWidget == NULL || mpDefaultFocusNavWidget->IsConnectedTo(mpAttentionWidget)) { + SetFocusedWidget(mpDefaultFocusNavWidget); + mpFocusedWidget->ProcessMessage(eGuiMessage_GetUINavFocus, cGuiMessageData()); + + return true; + } + return false; + } + } + + bool bRet = false; + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Check if widget likes the arrow press for anything else other than moving away, + // if not the case, just get next widget and check for validity + if (mpFocusedWidget) + bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_UIArrowPress, aData); + + if (bRet == false) { + iWidget* pNextWidget = mpFocusedWidget->GetFocusNavigation((eUIArrow)aData.mlVal); + + if (pNextWidget && pNextWidget->IsEnabled() && pNextWidget->IsVisible() && + (mpAttentionWidget == NULL || pNextWidget->IsConnectedTo(mpAttentionWidget))) { + iWidget* pOldFocus = mpFocusedWidget; + SetFocusedWidget(pNextWidget); + + // Do whatever stuff the widget wants to do when getting the focus through arrows + mpFocusedWidget->ProcessMessage(eGuiMessage_GetUINavFocus, cGuiMessageData()); + pOldFocus->ProcessMessage(eGuiMessage_LoseUINavFocus, cGuiMessageData()); + bRet = true; + } + } + + /////////////////////////////////////////////////////////////////////////// + // If we still haven't consumed the input, check for global listeners + if (bRet == false) { + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If widget is not eligible for input check, skip it (or if it's the focused one, we already checked that) + if (pWidget->IsGlobalUIInputListener() == false || pWidget == mpFocusedWidget || pWidget->IsVisible() == false) + continue; + + // If there is an attention set, do not send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + bRet = pWidget->ProcessMessage(eGuiMessage_UIArrowPress, aData); + if (bRet) + break; + } + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnUIArrowRelease(const cGuiMessageData& aData) { + if (mpFocusedWidget == NULL) { + return false; + } + + bool bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_UIArrowRelease, aData); + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnUIButtonPress(const cGuiMessageData& aData) { + /////////////////////////// + // Call widgets + bool bRet = false; + if (mpFocusedWidget) + bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_UIButtonPress, aData); + + if (bRet == false) { + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If widget is not eligible for input check, skip it (or if it's the focused one, we already checked that) + if (pWidget->IsGlobalUIInputListener() == false || pWidget == mpFocusedWidget || pWidget->IsVisible() == false) + continue; + + // If there is an attention set, do not send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + bRet = pWidget->ProcessMessage(eGuiMessage_UIButtonPress, aData); + if (bRet) + break; + } + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnUIButtonRelease(const cGuiMessageData& aData) { + /////////////////////////// + // Call widgets + bool bRet = false; + if (mpFocusedWidget) + bRet = mpFocusedWidget->ProcessMessage(eGuiMessage_UIButtonRelease, aData); + + if (bRet == false) { + tWidgetListIt it = mlstWidgets.begin(); + for (; it != mlstWidgets.end(); ++it) { + iWidget* pWidget = *it; + + // If widget is not eligible for input check, skip it (or if it's the focused one, we already checked that) + if (pWidget->IsGlobalUIInputListener() == false || pWidget == mpFocusedWidget || pWidget->IsVisible() == false) + continue; + + // If there is an attention set, do not send clicks to any other widgets + if (mpAttentionWidget && pWidget->IsConnectedTo(mpAttentionWidget) == false) { + continue; + } + + bRet = pWidget->ProcessMessage(eGuiMessage_UIButtonRelease, aData); + if (bRet) + break; + } + } + + return bRet; + } + + //----------------------------------------------------------------------- + + bool cGuiSet::OnUIButtonDoublePress(const cGuiMessageData& aData) { + if (mpFocusedWidget == NULL) + return false; + + return mpFocusedWidget->ProcessMessage(eGuiMessage_UIButtonDoublePress, aData); + } + + //----------------------------------------------------------------------- + + bool cGuiSet::DrawMouse(iWidget* apWidget, const cGuiMessageData& aData) { + if (HasFocus() && mbDrawMouse && mpGfxCurrentPointer) { + DrawGfx( + mpGfxCurrentPointer, cVector3f(mvMousePos.x, mvMousePos.y, mfMouseZ), mpGfxCurrentPointer->GetImageSize(), cColor(1, 1)); + } + + return true; + } + kGuiCallbackDeclaredFuncEnd(cGuiSet, DrawMouse) + + //----------------------------------------------------------------------- + + bool cGuiSet::DrawFocus(iWidget* apWidget, const cGuiMessageData& aData) { + if (HasFocus() && mpFocusedWidget && mbDrawFocus && + (mpFocusedWidget == mpDefaultFocusNavWidget || mpFocusedWidget->HasFocusNavigation())) { + if (mpFocusDrawObject && mpFocusDrawCallback) + mpFocusDrawCallback(mpFocusDrawObject, mpFocusedWidget, aData); + else { + cVector3f vPos = mpFocusedWidget->GetGlobalPosition(); + vPos.z = mfMouseZ - 1.0f; + DrawGfx(cGui::mpGfxRect, vPos, mpFocusedWidget->GetSize(), cColor(0.8f, 0.2f)); + } + } + + return true; + } + kGuiCallbackDeclaredFuncEnd(cGuiSet, DrawFocus) + + //----------------------------------------------------------------------- + + bool cGuiSet::ExecShortcut(const cKeyPress& aKeyPress) { + bool bRet = false; + tShortcutListIt it = mlstShortcuts.begin(); + for (; it != mlstShortcuts.end(); ++it) { + cGuiGlobalShortcut* pShortcut = *it; + bRet = pShortcut->ProcessKeyPress(aKeyPress); + if (bRet) + break; + } + + return bRet; + } + + //----------------------------------------------------------------------- + + void cGuiSet::UpdateToolTip(float afTimeStep) { + if (mpSkin == NULL || mpFrameToolTip == NULL) + return; + + if (mpCurrentToolTipWidget == NULL || mpCurrentToolTipWidget->IsVisible() == false) { + if (mpFrameToolTip->IsVisible()) { + mpFrameToolTip->SetEnabled(false); + mpFrameToolTip->SetVisible(false); + } + } else { + if (mfToolTipTimer >= mfToolTipTimeToPopUp) { + if (mpFrameToolTip->IsVisible() == false) { + const tWString& sTipText = mpCurrentToolTipWidget->GetToolTip().c_str(); + const cVector2f& mvFontSize = mpLabelToolTip->GetDefaultFontSize(); + + float fTextLength = mpLabelToolTip->GetDefaultFontType()->GetLength(mvFontSize, sTipText.c_str()) + 3 + 3; + float fMaxTextLength = GetVirtualSize().x * 0.4f; + iFontData* pFont = mpLabelToolTip->GetDefaultFontType(); + + tWStringVec vRows; + pFont->GetWordWrapRows(fMaxTextLength, mvFontSize.y + 2, mvFontSize, sTipText, &vRows); + int lRows = (int)vRows.size(); + + cVector3f vPos = mvMousePos + mpGfxCurrentPointer->GetImageSize(); + vPos.z = mfMouseZ - 2; + + cVector2f vToolTipSize = cVector2f(cMath::Min(fTextLength, fMaxTextLength), lRows * (mvFontSize.y + 2) - 2 + 3 + 3); + + mpLabelToolTip->SetText(sTipText); + mpLabelToolTip->SetSize(vToolTipSize); + + if (vPos.x + vToolTipSize.x > mvVirtualSize.x) + vPos.x = mvVirtualSize.x - vToolTipSize.x; + if (vPos.y + vToolTipSize.y > mvVirtualSize.y) + vPos.y = mvVirtualSize.y - vToolTipSize.y; + + mpFrameToolTip->SetGlobalPosition(vPos); + mpFrameToolTip->SetSize(vToolTipSize); + + mpFrameBGToolTip->SetSize(vToolTipSize - 2); + + mpFrameToolTip->SetEnabled(true); + mpFrameToolTip->SetVisible(true); + } + } else { + mfToolTipTimer += afTimeStep; + + if (mpFrameToolTip->IsVisible()) { + mpFrameToolTip->SetEnabled(false); + mpFrameToolTip->SetVisible(false); + } + } + } + } + + //----------------------------------------------------------------------- + + void cGuiSet::CreateToolTipWidgets() { + mpFrameToolTip = CreateWidgetFrame(0, 0, false); + mpFrameToolTip->SetBackGroundColor(cColor(0, 1)); + mpFrameToolTip->SetDrawBackground(true); + mpFrameToolTip->SetEnabled(false); + mpFrameToolTip->SetVisible(false); + + mpFrameBGToolTip = CreateWidgetFrame(cVector3f(1, 1, 0.1f), 0, false, mpFrameToolTip); + mpFrameBGToolTip->SetBackGroundColor(cColor(1, 1, 0.882f, 1)); + mpFrameBGToolTip->SetDrawBackground(true); + + mpLabelToolTip = CreateWidgetLabel(cVector3f(3, 2, 0.1f), 0, _W(""), mpFrameToolTip); + mpLabelToolTip->SetDefaultFontSize(12); + mpLabelToolTip->SetWordWrap(true); + } + + //----------------------------------------------------------------------- + + eUIArrow cGuiSet::TranslateKeyToUIArrow(eKey aKey) { + switch (aKey) { + case eKey_Up: + return eUIArrow_Up; + case eKey_Right: + return eUIArrow_Right; + case eKey_Down: + return eUIArrow_Down; + case eKey_Left: + return eUIArrow_Left; + default: + return eUIArrow_LastEnum; + } + } + + //----------------------------------------------------------------------- + + void cGuiSet::AddToTabOrder(iWidget* apWidget) { + if (apWidget && find(mlstTabOrderWidgets.begin(), mlstTabOrderWidgets.end(), apWidget) == mlstTabOrderWidgets.end()) + mlstTabOrderWidgets.push_back(apWidget); + + mpTabOrderWidget = mlstTabOrderWidgets.front(); + } + + //----------------------------------------------------------------------- + + void cGuiSet::ClearTabOrder() { + mlstTabOrderWidgets.clear(); - mpTabOrderWidget = NULL; - } + mpTabOrderWidget = NULL; + } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- - void cGuiSet::SetDefaultFocusNavWidget(iWidget* apWidget, bool abCheckForValidity) - { - if(mpDefaultFocusNavWidget==apWidget) return; + void cGuiSet::SetDefaultFocusNavWidget(iWidget* apWidget, bool abCheckForValidity) { + if (mpDefaultFocusNavWidget == apWidget) + return; - if(abCheckForValidity && IsValidWidget(apWidget)==false) - apWidget = NULL; + if (abCheckForValidity && IsValidWidget(apWidget) == false) + apWidget = NULL; - mpDefaultFocusNavWidget = apWidget; - } + mpDefaultFocusNavWidget = apWidget; + } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- - void cGuiSet::PushDefaultFocusNavWidget() - { - mlstDefaultFocusStack.push_back(mpDefaultFocusNavWidget); - } + void cGuiSet::PushDefaultFocusNavWidget() { + mlstDefaultFocusStack.push_back(mpDefaultFocusNavWidget); + } - void cGuiSet::PopDefaultFocusNavWidget() - { - if(mlstDefaultFocusStack.empty()) return; + void cGuiSet::PopDefaultFocusNavWidget() { + if (mlstDefaultFocusStack.empty()) + return; - SetDefaultFocusNavWidget(mlstDefaultFocusStack.back(), true); + SetDefaultFocusNavWidget(mlstDefaultFocusStack.back(), true); - mlstDefaultFocusStack.pop_back(); - } + mlstDefaultFocusStack.pop_back(); + } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- -} +} // namespace hpl diff --git a/HPL2/sources/impl/LegacyVertexBuffer.cpp b/HPL2/sources/impl/LegacyVertexBuffer.cpp index fe9c3b55f..f4d719e76 100644 --- a/HPL2/sources/impl/LegacyVertexBuffer.cpp +++ b/HPL2/sources/impl/LegacyVertexBuffer.cpp @@ -452,8 +452,7 @@ namespace hpl { void LegacyVertexBuffer::Draw(eVertexBufferDrawType aDrawType) { } - DrawPacket LegacyVertexBuffer::resolveGeometryBinding( - uint32_t frameIndex, std::span elements) { + DrawPacket LegacyVertexBuffer::resolveGeometryBinding(uint32_t frameIndex) { DrawPacket packet; packet.m_type = DrawPacket::DrawIndvidualBuffers; if(m_updateFlags) { @@ -488,7 +487,7 @@ namespace hpl { updateDesc.mDstOffset = element.m_activeCopy * updateDesc.mSize; beginUpdateResource(&updateDesc); std::copy(element.m_shadowData.begin(), element.m_shadowData.end(), reinterpret_cast(updateDesc.pMappedData)); - endUpdateResource(&updateDesc, &m_bufferSync); + endUpdateResource(&updateDesc); } } } @@ -523,22 +522,19 @@ namespace hpl { updateDesc.mDstOffset = m_indexBufferActiveCopy * updateDesc.mSize; beginUpdateResource(&updateDesc); std::copy(m_indices.begin(), m_indices.end(), reinterpret_cast(updateDesc.pMappedData)); - endUpdateResource(&updateDesc, &m_bufferSync); + endUpdateResource(&updateDesc); } m_updateIndices = false; } // GeometryBinding binding = {}; packet.m_indvidual.m_numStreams = 0; - for (auto& targetEle : elements) { - auto found = std::find_if(m_vertexElements.begin(), m_vertexElements.end(), [&](auto& element) { - return element.m_type == targetEle; - }); - ASSERT(found != m_vertexElements.end() && "Element not found"); + for(auto& element: m_vertexElements) { auto& stream = packet.m_indvidual.m_vertexStream[packet.m_indvidual.m_numStreams++]; - stream.m_buffer = &found->m_buffer; - stream.m_offset = found->m_activeCopy * found->m_shadowData.size(); - stream.m_stride = found->Stride(); + stream.m_buffer = &element.m_buffer; + stream.m_element = element.m_type; + stream.m_offset = element.m_activeCopy * element.m_shadowData.size(); + stream.m_stride = element.Stride(); } const int requestNumIndecies = GetRequestNumberIndecies(); const uint32_t numIndecies = (requestNumIndecies >= 0) ? requestNumIndecies : static_cast(m_indices.size()) ; diff --git a/HPL2/sources/impl/SqScript.cpp b/HPL2/sources/impl/SqScript.cpp index b3510065f..fda3831b8 100644 --- a/HPL2/sources/impl/SqScript.cpp +++ b/HPL2/sources/impl/SqScript.cpp @@ -27,6 +27,8 @@ #include "resources/BinaryBuffer.h" #include "resources/Resources.h" +#undef GetMessage + namespace hpl { ////////////////////////////////////////////////////////////////////////// diff --git a/HPL2/sources/platform/sdl2/SDL2NativeWindow.cpp b/HPL2/sources/platform/sdl2/SDL2NativeWindow.cpp index 8da8d9b16..c26e96687 100644 --- a/HPL2/sources/platform/sdl2/SDL2NativeWindow.cpp +++ b/HPL2/sources/platform/sdl2/SDL2NativeWindow.cpp @@ -99,17 +99,20 @@ namespace hpl::window::internal { } #if defined(VK_USE_PLATFORM_XLIB_KHR) + handle.type = WINDOW_HANDLE_TYPE_XLIB; handle.display = wmi.info.x11.display; handle.window = wmi.info.x11.window; // handle.colormap = wmi.info.x11.colormap; //handle.xlib_wm_delete_window = XInternAtom(wmi.info.x11.display, "WM_DELETE_WINDOW", False); #elif defined(VK_USE_PLATFORM_XCB_KHR) + handle.type = WINDOW_HANDLE_TYPE_XCB; handle.connection = wmi.info.x11.display; handle.screen = wmi.info.x11.screen; handle.window = wmi.info.x11.window; handle.atom_wm_delete_window = xcb_intern_atom_reply(handle.connection, xcb_intern_atom( handle.connection, 0, strlen("WM_DELETE_WINDOW"), "WM_DELETE_WINDOW"), 0); #elif defined(__ANDROID__) + handle.type = WINDOW_HANDLE_TYPE_ANDROID; handle.window = wmi.info.android.window; handle.activity = wmi.info.android.activity; handle.configuration = wmi.info.android.config; diff --git a/HPL2/sources/resources/MaterialManager.cpp b/HPL2/sources/resources/MaterialManager.cpp index f720284e4..5c4f98907 100644 --- a/HPL2/sources/resources/MaterialManager.cpp +++ b/HPL2/sources/resources/MaterialManager.cpp @@ -106,7 +106,9 @@ namespace hpl { } void cMaterialManager::Update(float afTimeStep) { - } + + +} void cMaterialManager::Unload(iResourceBase* apResource) { } diff --git a/HPL2/sources/resources/ResourceLoader.cpp b/HPL2/sources/resources/ResourceLoader.cpp index 45b23916b..411541592 100644 --- a/HPL2/sources/resources/ResourceLoader.cpp +++ b/HPL2/sources/resources/ResourceLoader.cpp @@ -21,20 +21,6 @@ namespace hpl { - ////////////////////////////////////////////////////////////////////////// - // CONSTRUCTORS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // PUBLIC METHODS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - bool iResourceLoader::IsSupported(const tString& asFileExt) { tStringListIt it = mlstExtensions.begin(); diff --git a/HPL2/sources/resources/WorldLoaderHplMap.cpp b/HPL2/sources/resources/WorldLoaderHplMap.cpp index 8ae5f64f2..795d7a0ab 100644 --- a/HPL2/sources/resources/WorldLoaderHplMap.cpp +++ b/HPL2/sources/resources/WorldLoaderHplMap.cpp @@ -225,7 +225,8 @@ namespace hpl { //////////////////////////////////// // Try loading cache - LoadCacheFile(asFile); + // TODO: profile and work out if the cache is necessary + //LoadCacheFile(asFile); //////////////////////////////////// @@ -297,7 +298,8 @@ namespace hpl { ////////////////////////////// // Save cache - SaveCacheFile(asFile); + // TODO: profile and work out if the cache is necessary this is current broken ... + //SaveCacheFile(asFile); ////////////////////////////// // Final clean up diff --git a/HPL2/sources/scene/Beam.cpp b/HPL2/sources/scene/Beam.cpp index 4c494ee43..b0eb9f687 100644 --- a/HPL2/sources/scene/Beam.cpp +++ b/HPL2/sources/scene/Beam.cpp @@ -35,6 +35,9 @@ #include "graphics/Material.h" #include "graphics/MaterialType.h" #include "graphics/LowLevelGraphics.h" +#include "graphics/GraphicsBuffer.h" +#include "graphics/GeometrySet.h" +#include "graphics/MeshUtility.h" #include "scene/Camera.h" #include "scene/World.h" @@ -42,7 +45,10 @@ #include "engine/Engine.h" +#include "Common_3/Utilities/Math/MathTypes.h" + namespace hpl { + const uint32_t BeamNumberVerts = 4; cBeam::cBeam(const tString asName, cResources *apResources,cGraphics *apGraphics) : iRenderable(asName) @@ -63,37 +69,83 @@ namespace hpl { mlLastRenderCount = -1; - - mpVtxBuffer = mpLowLevelGraphics->CreateVertexBuffer( - eVertexBufferType_Hardware, - eVertexBufferDrawType_Tri, eVertexBufferUsageType_Dynamic,4,6); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Position,eVertexBufferElementFormat_Float,4); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Normal,eVertexBufferElementFormat_Float,3); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Color0,eVertexBufferElementFormat_Float,4); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Texture0,eVertexBufferElementFormat_Float,3); - - cVector3f vCoords[4] = {cVector3f((mvSize.x/2),-(mvSize.y/2),0), - cVector3f(-(mvSize.x/2),-(mvSize.y/2),0), - cVector3f(-(mvSize.x/2),(mvSize.y/2),0), - cVector3f((mvSize.x/2),(mvSize.y/2),0)}; - - cVector3f vTexCoords[4] = {cVector3f(1,1,0), //Bottom left - cVector3f(-1,1,0), //Bottom right - cVector3f(-1,-1,0), //Top left - cVector3f(1,-1,0)}; //Top right - - for(int i=0;i<4;i++) - { - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Position, vCoords[i]); - mpVtxBuffer->AddVertexColor(eVertexBufferElement_Color0, cColor(1,1,1,1)); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Texture0, (vTexCoords[i] + cVector2f(1,1))/2); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Normal,cVector3f(0,0,1)); - } - - for(int i=0;i<3;i++) mpVtxBuffer->AddIndex(i); - for(int i=2;i<5;i++) mpVtxBuffer->AddIndex(i==4?0:i); - - mpVtxBuffer->Compile(eVertexCompileFlag_CreateTangents); + auto* graphicsAllocator = Interface::Get(); + auto& opaqueSet = graphicsAllocator->resolveSet(GraphicsAllocator::AllocationSet::OpaqueSet); + m_geometry = opaqueSet.allocate(4 * 2, 6); + + std::array positionCoords = { float3((mvSize.x / 2), -(mvSize.y / 2), 0.0f), + float3(-(mvSize.x / 2), -(mvSize.y / 2), 0.0f), + float3(-(mvSize.x / 2), (mvSize.y / 2), 0.0f), + float3((mvSize.x / 2), (mvSize.y / 2), 0.0f) }; + + std::array texcoords = { (float2(1.0f, 1.0f) + float2(1,1)) / 2.0f, // Bottom left + (float2(-1.0f, 1.0f) + float2(1, 1)) / 2.0f, // Bottom right + (float2(-1.0f, -1.0f) + float2(1, 1)) / 2.0f, // Top left + (float2(1.0f, -1.0f) + float2(1, 1)) / 2.0f }; // Top right + { + auto& indexStream = m_geometry->indexBuffer(); + auto positionStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_POSITION); + auto normalStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_NORMAL); + auto colorStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_COLOR); + auto textureStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TEXCOORD0); + auto tangentStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TANGENT); + + BufferUpdateDesc indexUpdateDesc = { indexStream.m_handle, m_geometry->indexOffset() * GeometrySet::IndexBufferStride, GeometrySet::IndexBufferStride * 6 }; + BufferUpdateDesc positionUpdateDesc = { positionStream->buffer().m_handle, m_geometry->vertexOffset() * positionStream->stride(), positionStream->stride() * BeamNumberVerts * 2 }; + BufferUpdateDesc normalUpdateDesc = { normalStream->buffer().m_handle, m_geometry->vertexOffset() * normalStream->stride(), normalStream->stride() * BeamNumberVerts * 2}; + BufferUpdateDesc colorUpdateDesc = { colorStream->buffer().m_handle, m_geometry->vertexOffset() * colorStream->stride(), colorStream->stride() * BeamNumberVerts * 2}; + BufferUpdateDesc textureUpdateDesc = { textureStream->buffer().m_handle, m_geometry->vertexOffset() * textureStream->stride(), textureStream->stride() * BeamNumberVerts * 2}; + BufferUpdateDesc tangentUpdateDesc = { tangentStream->buffer().m_handle, m_geometry->vertexOffset() * tangentStream->stride(), tangentStream->stride() * BeamNumberVerts * 2}; + + beginUpdateResource(&indexUpdateDesc); + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&normalUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + beginUpdateResource(&textureUpdateDesc); + beginUpdateResource(&tangentUpdateDesc); + + GraphicsBuffer gpuIndexBuffer(indexUpdateDesc); + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuNormalBuffer(normalUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + GraphicsBuffer gpuTextureBuffer(textureUpdateDesc); + GraphicsBuffer gpuTangentBuffer(tangentUpdateDesc); + + auto indexView = gpuIndexBuffer.CreateIndexView(); + { + uint32_t index = 0; + for (int i = 0; i < 3; i++) { + indexView.Write(index++, i); + } + for (int i = 2; i < 5; i++) { + indexView.Write(index++, i == 4 ? 0 : i); + } + } + for(size_t copyIdx = 0; copyIdx < 2; copyIdx++) { + auto positionView = gpuPositionBuffer.CreateStructuredView(positionStream->stride() * copyIdx * 4) ; + auto normalView = gpuNormalBuffer.CreateStructuredView(normalStream->stride() * copyIdx * 4); + auto colorView = gpuColorBuffer.CreateStructuredView(colorStream->stride() * copyIdx * 4); + auto textureView = gpuTextureBuffer.CreateStructuredView(textureStream->stride() * copyIdx * 4); + auto tangentView = gpuTangentBuffer.CreateStructuredView(tangentStream->stride() * copyIdx * 4); + for (size_t i = 0; i < 4; i++) { + positionView.Write(i, positionCoords[i]); + normalView.Write(i, float3(0.0f, 0.0f, 1.0f)); + colorView.Write(i, float4(1,1,1,1)); + textureView.Write(i, texcoords[i]); + } + Matrix4 trans = Matrix4::identity(); + hpl::MeshUtility::MikkTSpaceGenerate(4, 6, &indexView, &positionView, &textureView, &normalView, &tangentView); + } + + endUpdateResource(&indexUpdateDesc); + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&normalUpdateDesc); + endUpdateResource(&colorUpdateDesc); + endUpdateResource(&textureUpdateDesc); + endUpdateResource(&tangentUpdateDesc); + } + + //mpVtxBuffer->Compile(eVertexCompileFlag_CreateTangents); mpEnd = hplNew( cBeamEnd, (asName + "_end",this)); mpEnd->AddCallback(&mEndCallback); @@ -110,12 +162,21 @@ namespace hpl { { hplDelete(mpEnd); if(mpMaterial) mpMaterialManager->Destroy(mpMaterial); - if(mpVtxBuffer) hplDelete(mpVtxBuffer); } - DrawPacket cBeam::ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) { + DrawPacket cBeam::ResolveDrawPacket(const ForgeRenderer::Frame& frame) { - return static_cast(mpVtxBuffer)->resolveGeometryBinding(frame.m_currentFrame, elements); + DrawPacket packet; + + DrawPacket::GeometrySetBinding binding{}; + packet.m_type = DrawPacket::DrawGeometryset; + binding.m_subAllocation = m_geometry.get(); + binding.m_indexOffset = 0; + binding.m_set = GraphicsAllocator::AllocationSet::OpaqueSet; + binding.m_numIndices = 6; + binding.m_vertexOffset = (m_activeCopy * 4); + packet.m_unified = binding; + return packet; } void cBeam::SetSize(const cVector2f& avSize) @@ -153,44 +214,13 @@ namespace hpl { if(mColor == aColor) return; mColor = aColor; - - float *pColors = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Color0); - - //Change "lower colors" - if(mbMultiplyAlphaWithColor) - { - for(int i=0; i<2;++i) - { - pColors[0] = mColor.r * mColor.a; - pColors[1] = mColor.g * mColor.a; - pColors[2] = mColor.b * mColor.a; - pColors[3] = mColor.a; - pColors+=4; - } - } - else - { - for(int i=0; i<2;++i) - { - pColors[0] = mColor.r; - pColors[1] = mColor.g; - pColors[2] = mColor.b; - pColors[3] = mColor.a; - pColors+=4; - } - } - mpVtxBuffer->UpdateData(eVertexElementFlag_Color0,false); } - //----------------------------------------------------------------------- - void cBeam::SetMaterial(cMaterial * apMaterial) { mpMaterial = apMaterial; } - //----------------------------------------------------------------------- - cBoundingVolume* cBeam::GetBoundingVolume() { if(mbUpdateBoundingVolume) @@ -218,8 +248,6 @@ namespace hpl { return &mBoundingVolume; } - //----------------------------------------------------------------------- - void cBeam::UpdateGraphicsForFrame(float afFrameTime) { if( mlStartTransformCount == GetTransformUpdateCount() && @@ -227,68 +255,80 @@ namespace hpl { { return; } + m_activeCopy = (m_activeCopy + 1) % 2; //////////////////////////////// //Get Axis mvAxis = mpEnd->GetWorldPosition() - GetWorldPosition(); - mvMidPosition =GetWorldPosition() + mvAxis*0.5f; + mvMidPosition = GetWorldPosition() + mvAxis*0.5f; float fDist = mvAxis.Length(); mvAxis.Normalize(); - //////////////////////////////// //Update vertex buffer cVector2f vBeamSize = cVector2f(mvSize.x, fDist); - - float *pPos = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Position); - float *pTex = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Texture0); - - cVector3f vCoords[4] = {cVector3f((vBeamSize.x/2),-(vBeamSize.y/2),0), - cVector3f(-(vBeamSize.x/2),-(vBeamSize.y/2),0), - cVector3f(-(vBeamSize.x/2),(vBeamSize.y/2),0), - cVector3f((vBeamSize.x/2),(vBeamSize.y/2),0)}; - - cVector3f vTexCoords[4]; - if(mbTileHeight) - { - vTexCoords[0] = cVector3f(1,1,0); //Bottom left - vTexCoords[1] = cVector3f(0,1,0); //Bottom right - vTexCoords[2] = cVector3f(0,-fDist/mvSize.y,0); //Top left - vTexCoords[3] = cVector3f(1,-fDist/mvSize.y,0); //Top right - } - else - { - vTexCoords[0] = cVector3f(1,1,0); //Bottom left - vTexCoords[1] = cVector3f(0,1,0); //Bottom right - vTexCoords[2] = cVector3f(0,0,0); //Top left - vTexCoords[3] = cVector3f(1,0,0); //Top right - } - - for(int i=0; i<4;++i) - { - pPos[0] = vCoords[i].x; - pPos[1] = vCoords[i].y; - pPos[2] = vCoords[i].z; - pPos+=4; - - pTex[0] = vTexCoords[i].x; - pTex[1] = vTexCoords[i].y; - pTex+=3; - } - - if(cMaterial::IsTranslucent(mpMaterial->Descriptor().m_id)) - { - mpVtxBuffer->UpdateData(eVertexElementFlag_Position | eVertexElementFlag_Texture0,false); - } - else - { - mpVtxBuffer->UpdateData(eVertexElementFlag_Position | eVertexElementFlag_Texture0,false); - } + const std::array vCoords = { float3((vBeamSize.x / 2), -(vBeamSize.y / 2), 0.0f), + float3(-(vBeamSize.x / 2), -(vBeamSize.y / 2), 0.0f), + float3(-(vBeamSize.x / 2), (vBeamSize.y / 2), 0.0f), + float3((vBeamSize.x / 2), (vBeamSize.y / 2), 0.0f) }; + + const std::array vTexCoords = mbTileHeight ? std::array { + float2(1.0f,1.0f), //Bottom left + float2(0.0f,1.0f), //Bottom right + float2(0.0f,-fDist/mvSize.y), //Top left + float2(1.0f,-fDist/mvSize.y) //Top right + } : std::array { + float2(1.0f,1.0f), //Bottom left + float2(0.0f,1.0f), //Bottom right + float2(0.0f,0.0f), //Top left + float2(1.0f,0.0f) //Top right + }; + + { + auto positionStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_POSITION); + auto colorStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_COLOR); + auto textureStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TEXCOORD0); + + BufferUpdateDesc positionUpdateDesc = { positionStream->buffer().m_handle, positionStream->stride() * ((4 * m_activeCopy) + m_geometry->vertexOffset()), positionStream->stride() * 4}; + BufferUpdateDesc textureUpdateDesc = { textureStream->buffer().m_handle, textureStream->stride() * ((4 * m_activeCopy) + m_geometry->vertexOffset()), textureStream->stride() * 4}; + BufferUpdateDesc colorUpdateDesc = { colorStream->buffer().m_handle, colorStream->stride() * ((4 * m_activeCopy) + m_geometry->vertexOffset()), colorStream->stride() * 4}; + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&textureUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuTextureBuffer(textureUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + + auto positionView = gpuPositionBuffer.CreateStructuredView(); + auto textureView = gpuTextureBuffer.CreateStructuredView(); + auto colorView = gpuTextureBuffer.CreateStructuredView(); + for (int i = 0; i < BeamNumberVerts; ++i) { + positionView.Write(i, vCoords[i]); + textureView.Write(i, vTexCoords[i]); + } + cColor endColor = mpEnd->mColor; + cColor startColor = mColor; + if (mbMultiplyAlphaWithColor) { + colorView.Write( + 0, float4(startColor.r * startColor.a, startColor.g * startColor.a, startColor.b * startColor.a, startColor.a)); + colorView.Write( + 1, float4(startColor.r * startColor.a, startColor.g * startColor.a, startColor.b * startColor.a, startColor.a)); + colorView.Write(2, float4(endColor.r * endColor.a, endColor.g * endColor.a, endColor.b * endColor.a, endColor.a)); + colorView.Write(3, float4(endColor.r * endColor.a, endColor.g * endColor.a, endColor.b * endColor.a, endColor.a)); + } else { + colorView.Write(0, float4(startColor.r, startColor.g, startColor.b, startColor.a)); + colorView.Write(1, float4(startColor.r, startColor.g, startColor.b, startColor.a)); + colorView.Write(2, float4(endColor.r, endColor.g, endColor.b, endColor.a)); + colorView.Write(3, float4(endColor.r, endColor.g, endColor.b, endColor.a)); + } + + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&textureUpdateDesc); + endUpdateResource(&colorUpdateDesc); + } } - //----------------------------------------------------------------------- - cMatrixf* cBeam::GetModelMatrix(cFrustum *apFrustum) { if(apFrustum==NULL)return &GetWorldMatrix(); @@ -333,17 +373,12 @@ namespace hpl { return &m_mtxTempTransform; } - //----------------------------------------------------------------------- - int cBeam::GetMatrixUpdateCount() { return GetTransformUpdateCount(); } - //----------------------------------------------------------------------- - - - bool cBeam::LoadXMLProperties(const tString asFile) + bool cBeam::LoadXMLProperties(const tString asFile) { msFileName = asFile; @@ -411,8 +446,6 @@ namespace hpl { return true; } - //----------------------------------------------------------------------- - bool cBeam::IsVisible() { if(mColor.r <= 0 && mColor.g <= 0 && mColor.b <= 0) return false; @@ -420,13 +453,6 @@ namespace hpl { return mbIsVisible; } - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // BEAM END TRANSFORM UPDATE CALLBACK - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- void cBeamEnd_UpdateCallback::OnTransformUpdate(iEntity3D * apEntity) { @@ -435,68 +461,10 @@ namespace hpl { pEnd->mpBeam->SetTransformUpdated(true); } - //----------------------------------------------------------------------- - - - ////////////////////////////////////////////////////////////////////////// - // BEAM END - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - void cBeamEnd::SetColor(const cColor &aColor) { if(mColor == aColor) return; - mColor = aColor; - - float *pColors = mpBeam->mpVtxBuffer->GetFloatArray(eVertexBufferElement_Color0); - - //Change "upper colors" - pColors+= 4*2; - if(mpBeam->mbMultiplyAlphaWithColor) - { - for(int i=0; i<2;++i) - { - pColors[0] = mColor.r * mColor.a; - pColors[1] = mColor.g * mColor.a; - pColors[2] = mColor.b * mColor.a; - pColors[3] = mColor.a; - pColors+=4; - } - } - else - { - for(int i=0; i<2;++i) - { - pColors[0] = mColor.r; - pColors[1] = mColor.g; - pColors[2] = mColor.b; - pColors[3] = mColor.a; - pColors+=4; - } - } - - mpBeam->mpVtxBuffer->UpdateData(eVertexElementFlag_Color0,false); } - //----------------------------------------------------------------------- - - - ////////////////////////////////////////////////////////////////////////// - // PRIVATE METHODS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // SAVE OBJECT STUFF - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - - //----------------------------------------------------------------------- - } diff --git a/HPL2/sources/scene/BillBoard.cpp b/HPL2/sources/scene/BillBoard.cpp index 2cfb5cc42..82489db4e 100644 --- a/HPL2/sources/scene/BillBoard.cpp +++ b/HPL2/sources/scene/BillBoard.cpp @@ -19,6 +19,8 @@ #include "scene/BillBoard.h" +#include "graphics/GraphicsBuffer.h" +#include "graphics/MeshUtility.h" #include "impl/LegacyVertexBuffer.h" #include "impl/tinyXML/tinyxml.h" @@ -43,21 +45,12 @@ namespace hpl { - ////////////////////////////////////////////////////////////////////////// - // CONSTRUCTORS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - cBillboard::cBillboard(const tString asName,const cVector2f& avSize,eBillboardType aType, cResources *apResources,cGraphics *apGraphics) : iRenderable(asName) { mpMaterialManager = apResources->GetMaterialManager(); mpLowLevelGraphics = apGraphics->GetLowLevel(); - // m_occlusionCurrent = bgfx::createOcclusionQuery(); - // m_occlusionMax = bgfx::createOcclusionQuery(); - mvSize = avSize; mvAxis = cVector3f(0,1,0); @@ -71,42 +64,92 @@ namespace hpl { mlLastRenderCount = -1; - mpVtxBuffer = mpLowLevelGraphics->CreateVertexBuffer(eVertexBufferType_Hardware,eVertexBufferDrawType_Tri, eVertexBufferUsageType_Dynamic,4,6); - - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Position,eVertexBufferElementFormat_Float,4); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Normal,eVertexBufferElementFormat_Float,3); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Color0,eVertexBufferElementFormat_Float,4); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Texture0,eVertexBufferElementFormat_Float,3); - - cVector3f vCoords[4] = {cVector3f((mvSize.x/2),-(mvSize.y/2),0), - cVector3f(-(mvSize.x/2),-(mvSize.y/2),0), - cVector3f(-(mvSize.x/2),(mvSize.y/2),0), - cVector3f((mvSize.x/2),(mvSize.y/2),0)}; - - cVector3f vTexCoords[4] = {cVector3f(1,-1,0), - cVector3f(-1,-1,0), - cVector3f(-1,1,0), - cVector3f(1,1,0)}; - for(int i=0;i<4;i++) - { - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Position, vCoords[i]); - mpVtxBuffer->AddVertexColor(eVertexBufferElement_Color0, cColor(1,1,1,1)); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Texture0, (vTexCoords[i] + cVector2f(1,1))/2 ); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Normal,cVector3f(0,0,1)); - } - - for(int i=0;i<3;i++) mpVtxBuffer->AddIndex(i); - for(int i=2;i<5;i++) mpVtxBuffer->AddIndex(i==4?0:i); - - //If the type is fixed, then we need a backside too - //To do this, just all all the same indices in reversed order. - if(mType == eBillboardType_FixedAxis) - { - for(int i=2; i>=0; i--) mpVtxBuffer->AddIndex(i); - for(int i=4; i>=2; i--) mpVtxBuffer->AddIndex(i==4?0:i); - } + auto* graphicsAllocator = Interface::Get(); + auto& opaqueSet = graphicsAllocator->resolveSet(GraphicsAllocator::AllocationSet::OpaqueSet); + const uint32_t numberIndecies = 6 * (mType == eBillboardType_FixedAxis ? 2 : 1); + m_geometry = opaqueSet.allocate(cBillboard::NumberVerts * 2, numberIndecies); + + { + std::array positionCoords = { float3((mvSize.x / 2), -(mvSize.y / 2), 0.0f), + float3(-(mvSize.x / 2), -(mvSize.y / 2), 0.0f), + float3(-(mvSize.x / 2), (mvSize.y / 2), 0.0f), + float3((mvSize.x / 2), (mvSize.y / 2), 0.0f) }; + + std::array texcoords = { (float2(1.0f, -1.0f) + float2(1, 1)) / 2.0f, // Bottom left + (float2(-1.0f, -1.0f) + float2(1, 1)) / 2.0f, // Bottom right + (float2(-1.0f, 1.0f) + float2(1, 1)) / 2.0f, // Top left + (float2(1.0f, 1.0f) + float2(1, 1)) / 2.0f }; // Top right + + auto& indexStream = m_geometry->indexBuffer(); + auto positionStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_POSITION); + auto normalStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_NORMAL); + auto colorStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_COLOR); + auto textureStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TEXCOORD0); + auto tangentStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TANGENT); + + BufferUpdateDesc indexUpdateDesc = { indexStream.m_handle, GeometrySet::IndexBufferStride * m_geometry->indexOffset(), GeometrySet::IndexBufferStride * numberIndecies }; + BufferUpdateDesc positionUpdateDesc = { positionStream->buffer().m_handle, positionStream->stride() * m_geometry->vertexOffset(), positionStream->stride() * cBillboard::NumberVerts * 2 }; + BufferUpdateDesc normalUpdateDesc = { normalStream->buffer().m_handle, normalStream->stride() * m_geometry->vertexOffset(), normalStream->stride() * cBillboard::NumberVerts * 2}; + BufferUpdateDesc colorUpdateDesc = { colorStream->buffer().m_handle, colorStream->stride() * m_geometry->vertexOffset(), colorStream->stride() * cBillboard::NumberVerts * 2}; + BufferUpdateDesc textureUpdateDesc = { textureStream->buffer().m_handle, textureStream->stride() * m_geometry->vertexOffset(), textureStream->stride() * cBillboard::NumberVerts * 2}; + BufferUpdateDesc tangentUpdateDesc = { tangentStream->buffer().m_handle, tangentStream->stride() * m_geometry->vertexOffset(), tangentStream->stride() * cBillboard::NumberVerts * 2}; + + beginUpdateResource(&indexUpdateDesc); + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&normalUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + beginUpdateResource(&textureUpdateDesc); + beginUpdateResource(&tangentUpdateDesc); + + GraphicsBuffer gpuIndexBuffer(indexUpdateDesc); + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuNormalBuffer(normalUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + GraphicsBuffer gpuTextureBuffer(textureUpdateDesc); + GraphicsBuffer gpuTangentBuffer(tangentUpdateDesc); + + auto indexView = gpuIndexBuffer.CreateIndexView(); + { + uint32_t index = 0; + for (int i = 0; i < 3; i++) { + indexView.Write(index++, i); + } + for (int i = 2; i < 5; i++) { + indexView.Write(index++, i == 4 ? 0 : i); + } + if (mType == eBillboardType_FixedAxis) { + for (int i = 2; i >= 0; i--) { + indexView.Write(index++, i); + } + for (int i = 4; i >= 2; i--) { + indexView.Write(index++, i == 4 ? 0 : i); + } + } - mpVtxBuffer->Compile(eVertexCompileFlag_CreateTangents); + for (size_t copyIdx = 0; copyIdx < 2; copyIdx++) { + auto positionView = gpuPositionBuffer.CreateStructuredView(positionStream->stride() * copyIdx * cBillboard::NumberVerts) ; + auto normalView = gpuNormalBuffer.CreateStructuredView(normalStream->stride() * copyIdx * cBillboard::NumberVerts); + auto colorView = gpuColorBuffer.CreateStructuredView(colorStream->stride() * copyIdx * cBillboard::NumberVerts); + auto textureView = gpuTextureBuffer.CreateStructuredView(textureStream->stride() * copyIdx * cBillboard::NumberVerts); + auto tangentView = gpuTangentBuffer.CreateStructuredView(tangentStream->stride() * copyIdx * cBillboard::NumberVerts); + for (size_t i = 0; i < cBillboard::NumberVerts; i++) { + positionView.Write(i, positionCoords[i]); + normalView.Write(i, float3(0.0f, 0.0f, 1.0f)); + colorView.Write(i, float4(1,1,1,1)); + textureView.Write(i, texcoords[i]); + } + Matrix4 trans = Matrix4::identity(); + hpl::MeshUtility::MikkTSpaceGenerate(4, 6, &indexView, &positionView, &textureView, &normalView, &tangentView); + } + } + + endUpdateResource(&indexUpdateDesc); + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&normalUpdateDesc); + endUpdateResource(&colorUpdateDesc); + endUpdateResource(&textureUpdateDesc); + endUpdateResource(&tangentUpdateDesc); + } mbIsHalo = false; mvHaloSourceSize = 1; @@ -122,39 +165,103 @@ namespace hpl { cBillboard::~cBillboard() { if(mpMaterial) mpMaterialManager->Destroy(mpMaterial); - if(mpVtxBuffer) hplDelete(mpVtxBuffer); + //if(mpVtxBuffer) hplDelete(mpVtxBuffer); if(mpHaloSourceBV) hplDelete(mpHaloSourceBV); } - DrawPacket cBillboard::ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) { - return static_cast(mpVtxBuffer)->resolveGeometryBinding(frame.m_currentFrame, elements); + DrawPacket cBillboard::ResolveDrawPacket(const ForgeRenderer::Frame& frame) { + if((frame.m_currentFrame - m_frameIndex) >= ForgeRenderer::SwapChainLength - 1 && m_dirtyBuffer) { + m_frameIndex = frame.m_currentFrame; + m_activeCopy = (m_activeCopy + 1) % 2; + m_dirtyBuffer = false; + + auto positionStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_POSITION); + auto textureStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TEXCOORD0); + auto colorStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_COLOR); + + BufferUpdateDesc positionUpdateDesc = { positionStream->buffer().m_handle, + positionStream->stride() * (m_geometry->vertexOffset() + (cBillboard::NumberVerts * m_activeCopy)), + positionStream->stride() * cBillboard::NumberVerts}; + BufferUpdateDesc textureUpdateDesc = { textureStream->buffer().m_handle, + textureStream->stride() * (m_geometry->vertexOffset() + (cBillboard::NumberVerts * m_activeCopy)), + textureStream->stride() * cBillboard::NumberVerts}; + BufferUpdateDesc colorUpdateDesc = { colorStream->buffer().m_handle, + colorStream->stride() * (m_geometry->vertexOffset() + (cBillboard::NumberVerts * m_activeCopy)), + colorStream->stride() * cBillboard::NumberVerts}; + + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&textureUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuTextureBuffer(textureUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + + auto positionView = gpuPositionBuffer.CreateStructuredView(); + auto textureView = gpuTextureBuffer.CreateStructuredView(); + auto colorView = gpuColorBuffer.CreateStructuredView(); + + std::array positionCoords = { float3((mvSize.x / 2.0f), -(mvSize.y / 2.0f), 0.0f), + float3(-(mvSize.x / 2.0f), -(mvSize.y / 2.0f), 0.0f), + float3(-(mvSize.x / 2.0f), (mvSize.y / 2.0f), 0.0f), + float3((mvSize.x / 2.0f), (mvSize.y / 2.0f), 0.0f) }; + + std::array texcoords = { (float2(1.0f, -1.0f) + float2(1, 1)) / 2.0f, // Bottom left + (float2(-1.0f, -1.0f) + float2(1, 1)) / 2.0f, // Bottom right + (float2(-1.0f, 1.0f) + float2(1, 1)) / 2.0f, // Top left + (float2(1.0f, 1.0f) + float2(1, 1)) / 2.0f }; // Top right + for (size_t i = 0; i < cBillboard::NumberVerts; i++) { + positionView.Write(i, positionCoords[i]); + colorView.Write(i, float4(mColor.r * mfHaloAlpha, mColor.g * mfHaloAlpha, mColor.b * mfHaloAlpha, mColor.a * mfHaloAlpha)); + textureView.Write(i, texcoords[i]); + } + + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&textureUpdateDesc); + endUpdateResource(&colorUpdateDesc); + } + + DrawPacket packet; + + DrawPacket::GeometrySetBinding binding{}; + packet.m_type = DrawPacket::DrawGeometryset; + binding.m_subAllocation = m_geometry.get(); + binding.m_indexOffset = 0; + binding.m_set = GraphicsAllocator::AllocationSet::OpaqueSet; + binding.m_numIndices = 6 * (mType == eBillboardType_FixedAxis ? 2 : 1); + binding.m_vertexOffset = (m_activeCopy * cBillboard::NumberVerts); + packet.m_unified = binding; + return packet; } void cBillboard::SetSize(const cVector2f& avSize) { + m_dirtyBuffer = true; mvSize = avSize; mBoundingVolume.SetSize(cVector3f(mvSize.x, mvSize.y, mvSize.x)); - float *pPos = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Position); + // float *pPos = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Position); - cVector3f vCoords[4] = {cVector3f((mvSize.x/2),-(mvSize.y/2),0), - cVector3f(-(mvSize.x/2),-(mvSize.y/2),0), - cVector3f(-(mvSize.x/2),(mvSize.y/2),0), - cVector3f((mvSize.x/2),(mvSize.y/2),0)}; + // cVector3f vCoords[4] = {cVector3f((mvSize.x/2),-(mvSize.y/2),0), + // cVector3f(-(mvSize.x/2),-(mvSize.y/2),0), + // cVector3f(-(mvSize.x/2),(mvSize.y/2),0), + // cVector3f((mvSize.x/2),(mvSize.y/2),0)}; - for(int i=0; i<4;++i) - { - pPos[0] = vCoords[i].x; - pPos[1] = vCoords[i].y; - pPos[2] = vCoords[i].z; - pPos+=4; - } + // for(int i=0; i<4;++i) + // { + // pPos[0] = vCoords[i].x; + // pPos[1] = vCoords[i].y; + // pPos[2] = vCoords[i].z; + // pPos+=4; + // } - mpVtxBuffer->UpdateData(eVertexElementFlag_Position,false); + // mpVtxBuffer->UpdateData(eVertexElementFlag_Position,false); - if(mType == eBillboardType_Axis) SetAxis(mvAxis); + if(mType == eBillboardType_Axis) { + SetAxis(mvAxis); + } SetTransformUpdated(); } @@ -185,21 +292,21 @@ namespace hpl { void cBillboard::SetColor(const cColor &aColor) { if(mColor == aColor) return; - + m_dirtyBuffer = true; mColor = aColor; - float *pColors = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Color0); + // float *pColors = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Color0); - for(int i=0; i<4;++i) - { - pColors[0] = mColor.r * mfHaloAlpha; - pColors[1] = mColor.g * mfHaloAlpha; - pColors[2] = mColor.b * mfHaloAlpha; - pColors[3] = mColor.a * mfHaloAlpha; - pColors+=4; - } + // for(int i=0; i<4;++i) + // { + // pColors[0] = mColor.r * mfHaloAlpha; + // pColors[1] = mColor.g * mfHaloAlpha; + // pColors[2] = mColor.b * mfHaloAlpha; + // pColors[3] = mColor.a * mfHaloAlpha; + // pColors+=4; + // } - mpVtxBuffer->UpdateData(eVertexElementFlag_Color0,false); + // mpVtxBuffer->UpdateData(eVertexElementFlag_Color0,false); } //----------------------------------------------------------------------- @@ -212,19 +319,20 @@ namespace hpl { } mfHaloAlpha = afX; + m_dirtyBuffer = true; - float *pColors = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Color0); + // float *pColors = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Color0); - for(int i=0; i<4;++i) - { - pColors[0] = mColor.r * mfHaloAlpha; - pColors[1] = mColor.g * mfHaloAlpha; - pColors[2] = mColor.b * mfHaloAlpha; - pColors[3] = mColor.a * mfHaloAlpha; - pColors+=4; - } + // for(int i=0; i<4;++i) + // { + // pColors[0] = mColor.r * mfHaloAlpha; + // pColors[1] = mColor.g * mfHaloAlpha; + // pColors[2] = mColor.b * mfHaloAlpha; + // pColors[3] = mColor.a * mfHaloAlpha; + // pColors+=4; + // } - mpVtxBuffer->UpdateData(eVertexElementFlag_Color0,false); + // mpVtxBuffer->UpdateData(eVertexElementFlag_Color0,false); } //----------------------------------------------------------------------- diff --git a/HPL2/sources/scene/Camera.cpp b/HPL2/sources/scene/Camera.cpp index 06eacf438..364433eb6 100644 --- a/HPL2/sources/scene/Camera.cpp +++ b/HPL2/sources/scene/Camera.cpp @@ -43,7 +43,7 @@ namespace hpl { mfFOV = cMath::ToRad(70.0f); mfAspect = 4.0f/3.0f; mfFarClipPlane = 1000.0f; - mfNearClipPlane = 0.05f; + mfNearClipPlane = 0.5f; mvViewSize = cVector2f(2 * mfAspect, 2); @@ -378,6 +378,7 @@ namespace hpl { // Perspective projection if(mProjectionType == eProjectionType_Perspective) { + m_mtxProjection = cMath::MatrixPerspectiveProjection(mfNearClipPlane, mfFarClipPlane, mfFOV, mfAspect, mbInfFarPlane); } ////////////////////////////////////////////// diff --git a/HPL2/sources/scene/Entity3D.cpp b/HPL2/sources/scene/Entity3D.cpp index 5b74dada3..e3fb3a8ca 100644 --- a/HPL2/sources/scene/Entity3D.cpp +++ b/HPL2/sources/scene/Entity3D.cpp @@ -25,11 +25,6 @@ namespace hpl { - ////////////////////////////////////////////////////////////////////////// - // CONSTRUCTORS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- iEntity3D::iEntity3D(tString asName) { msName = asName; @@ -90,8 +85,6 @@ namespace hpl { return m_mtxLocalTransform.GetTranslation(); } - //----------------------------------------------------------------------- - cMatrixf& iEntity3D::GetLocalMatrix() { return m_mtxLocalTransform; @@ -108,8 +101,6 @@ namespace hpl { return m_mtxWorldTransform.GetTranslation(); } - //----------------------------------------------------------------------- - cMatrixf& iEntity3D::GetWorldMatrix() { UpdateWorldTransform(); @@ -117,12 +108,15 @@ namespace hpl { return m_mtxWorldTransform; } + Point3 iEntity3D::GetWorldPositionP3() { + return cMath::ToForgePoint3(GetWorldPosition()); + } + Matrix4 iEntity3D::GetWorldMat() { UpdateWorldTransform(); return cMath::ToForgeMatrix4(m_mtxWorldTransform); } - //----------------------------------------------------------------------- void iEntity3D::SetPosition(const cVector3f& avPos) { @@ -133,8 +127,6 @@ namespace hpl { SetTransformUpdated(); } - //----------------------------------------------------------------------- - void iEntity3D::SetMatrix(const cMatrixf& a_mtxTransform) { m_mtxLocalTransform = a_mtxTransform; @@ -142,8 +134,6 @@ namespace hpl { SetTransformUpdated(); } - //----------------------------------------------------------------------- - void iEntity3D::SetWorldPosition(const cVector3f& avWorldPos) { if(mpParent) @@ -156,8 +146,6 @@ namespace hpl { } } - //----------------------------------------------------------------------- - void iEntity3D::SetWorldMatrix(const cMatrixf& a_mtxWorldTransform) { if(mpParent) diff --git a/HPL2/sources/scene/FogArea.cpp b/HPL2/sources/scene/FogArea.cpp index 9594b0ac6..2da6e5537 100644 --- a/HPL2/sources/scene/FogArea.cpp +++ b/HPL2/sources/scene/FogArea.cpp @@ -49,7 +49,7 @@ namespace hpl { } - DrawPacket cFogArea::ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) { + DrawPacket cFogArea::ResolveDrawPacket(const ForgeRenderer::Frame& frame) { DrawPacket drawPacket; drawPacket.m_type = DrawPacket::Unknown; return drawPacket; diff --git a/HPL2/sources/scene/LightPoint.cpp b/HPL2/sources/scene/LightPoint.cpp index 2459e28e3..752aff844 100644 --- a/HPL2/sources/scene/LightPoint.cpp +++ b/HPL2/sources/scene/LightPoint.cpp @@ -30,12 +30,6 @@ namespace hpl { - ////////////////////////////////////////////////////////////////////////// - // CONSTRUCTORS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - cLightPoint::cLightPoint(tString asName, cResources *apResources) : iLight(asName,apResources) { mLightType = eLightType_Point; @@ -43,19 +37,9 @@ namespace hpl { UpdateBoundingVolume(); } - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // PRIVATE METHODS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - void cLightPoint::UpdateBoundingVolume() { mBoundingVolume.SetSize(mfRadius*2); mBoundingVolume.SetPosition(GetWorldPosition()); } - //----------------------------------------------------------------------- - } diff --git a/HPL2/sources/scene/ParticleEmitter.cpp b/HPL2/sources/scene/ParticleEmitter.cpp index d6c7a4ac2..e826074cd 100644 --- a/HPL2/sources/scene/ParticleEmitter.cpp +++ b/HPL2/sources/scene/ParticleEmitter.cpp @@ -29,6 +29,7 @@ #include "graphics/LowLevelGraphics.h" #include "graphics/VertexBuffer.h" #include "graphics/Renderer.h" +#include #include "scene/Camera.h" #include "math/Math.h" @@ -42,807 +43,701 @@ namespace hpl { - ////////////////////////////////////////////////////////////////////////// - // DATA LOADER - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - - iParticleEmitterData::iParticleEmitterData(const tString &asName,cResources* apResources, - cGraphics *apGraphics) - { - msName = asName; - mpResources = apResources; - mpGraphics = apGraphics; - - mfWarmUpTime =0; - mfWarmUpStepsPerSec = 20; - } - - //----------------------------------------------------------------------- - - iParticleEmitterData::~iParticleEmitterData() - { - for(int i=0;i<(int)mvMaterials.size();i++) - { - if(mvMaterials[i]) mpResources->GetMaterialManager()->Destroy(mvMaterials[i]); - } - } - //----------------------------------------------------------------------- - - void iParticleEmitterData::AddMaterial(cMaterial *apMaterial) - { - mvMaterials.push_back(apMaterial); - } + iParticleEmitterData::iParticleEmitterData(const tString& asName, cResources* apResources, cGraphics* apGraphics) { + msName = asName; + mpResources = apResources; + mpGraphics = apGraphics; + + mfWarmUpTime = 0; + mfWarmUpStepsPerSec = 20; + } + + //----------------------------------------------------------------------- + + iParticleEmitterData::~iParticleEmitterData() { + for (int i = 0; i < (int)mvMaterials.size(); i++) { + if (mvMaterials[i]) + mpResources->GetMaterialManager()->Destroy(mvMaterials[i]); + } + } + //----------------------------------------------------------------------- + + void iParticleEmitterData::AddMaterial(cMaterial* apMaterial) { + mvMaterials.push_back(apMaterial); + } + + iParticleEmitter::iParticleEmitter( + tString asName, + tMaterialVec* avMaterials, + unsigned int alMaxParticles, + cVector3f avSize, + cGraphics* apGraphics, + cResources* apResources) + : iRenderable(asName) { + mpGraphics = apGraphics; + mpResources = apResources; + + // Create and set up particle data + mvParticles.resize(alMaxParticles); + for (int i = 0; i < (int)alMaxParticles; i++) { + mvParticles[i] = hplNew(cParticle, ()); + } + mlMaxParticles = alMaxParticles; + mlNumOfParticles = 0; + + mvMaterials = avMaterials; + + auto* graphicsAllocator = Interface::Get(); + auto& particleSet = graphicsAllocator->resolveSet(GraphicsAllocator::AllocationSet::ParticleSet); + m_geometry = particleSet.allocate(4 * mlMaxParticles * NumberActiveCopies, 6 * mlMaxParticles); + + auto positionStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_POSITION); + auto colorStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_COLOR); + auto uvStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TEXCOORD0); + + auto& indexStream = m_geometry->indexBuffer(); + + BufferUpdateDesc indexUpdateDesc = { indexStream.m_handle, + m_geometry->indexOffset() * GeometrySet::IndexBufferStride, + GeometrySet::IndexBufferStride * 6 }; + BufferUpdateDesc positionUpdateDesc = { positionStream->buffer().m_handle, + (m_geometry->vertexOffset() * positionStream->stride()), + positionStream->stride() * 4 * mlMaxParticles * NumberActiveCopies }; + BufferUpdateDesc colorUpdateDesc = { colorStream->buffer().m_handle, + (m_geometry->vertexOffset() * colorStream->stride()), + colorStream->stride() * 4 * mlMaxParticles * NumberActiveCopies }; + BufferUpdateDesc uvUpdateDesc = { uvStream->buffer().m_handle, + (m_geometry->vertexOffset() * uvStream->stride()), + uvStream->stride() * 4 * mlMaxParticles * NumberActiveCopies }; + + beginUpdateResource(&indexUpdateDesc); + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + beginUpdateResource(&uvUpdateDesc); + + GraphicsBuffer gpuIndexBuffer(indexUpdateDesc); + + auto indexView = gpuIndexBuffer.CreateIndexView(); + uint32_t appendIdx = 0; + for (size_t i = 0; i < alMaxParticles; i++) { + for (int j = 0; j < 3; j++) { + indexView.Write(appendIdx++, (i * 4) + j); + } + for (int j = 2; j < 5; j++) { + indexView.Write(appendIdx++, (i * 4) + (j == 4 ? 0 : j)); + } + } + + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + GraphicsBuffer gpuUvBuffer(uvUpdateDesc); + + auto positionView = gpuPositionBuffer.CreateStructuredView(); + auto colorView = gpuColorBuffer.CreateStructuredView(); + auto uvView = gpuUvBuffer.CreateStructuredView(); + + for (size_t i = 0; i < mlMaxParticles * NumberActiveCopies; i++) { + uvView.Write((i * 4) + 0, float2(1, 1)); + uvView.Write((i * 4) + 1, float2(0, 1)); + uvView.Write((i * 4) + 2, float2(0, 0)); + uvView.Write((i * 4) + 3, float2(1, 0)); + } + for (size_t i = 0; i < mlMaxParticles * NumberActiveCopies * 4; i++) { + colorView.Write(i, float4(1, 1, 1, 1)); + positionView.Write(i, float3(0, 0, 0)); + } + + endUpdateResource(&indexUpdateDesc); + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&colorUpdateDesc); + endUpdateResource(&uvUpdateDesc); + + //////////////////////////////////// + // Setup vars + mlSleepCount = + 60 * 5; // Start with high sleep count to make sure a looping particle system reaches equilibrium. 5 secs should eb enough! + + mbDying = false; + mfFrame = 0; + + mbUpdateGfx = true; + mbUpdateBV = true; + + mlDirectionUpdateCount = -1; + mvDirection = cVector3f(0, 0, 0); + + mvMaxDrawSize = 0; + + mlAxisDrawUpdateCount = -1; + + mbApplyTransformToBV = false; + + mBoundingVolume.SetSize(0); + mBoundingVolume.SetPosition(0); + + mDrawType = eParticleEmitterType_FixedPoint; + mCoordSystem = eParticleEmitterCoordSystem_World; + + mbUsesDirection = false; // If Direction should be udpdated + } + + iParticleEmitter::~iParticleEmitter() { + for (int i = 0; i < (int)mvParticles.size(); i++) { + hplDelete(mvParticles[i]); + } + } + + void iParticleEmitter::SetSubDivUV(const cVector2l& avSubDiv) { + // Check so that there is any subdivision and that no sub divison axis is + // equal or below zero + if ((avSubDiv.x > 1 || avSubDiv.x > 1) && (avSubDiv.x > 0 && avSubDiv.y > 0)) { + int lSubDivNum = avSubDiv.x * avSubDiv.y; + + mvSubDivUV.resize(lSubDivNum); + + float fInvW = 1.0f / (float)avSubDiv.x; + float fInvH = 1.0f / (float)avSubDiv.y; + + for (int x = 0; x < avSubDiv.x; ++x) + for (int y = 0; y < avSubDiv.y; ++y) { + int lIdx = y * avSubDiv.x + x; + + float fX = (float)x; + float fY = (float)y; + + cPESubDivision* pSubDiv = &mvSubDivUV[lIdx]; + + pSubDiv->mvUV[0] = cVector3f((fX + 1) * fInvW, (fY + 1) * fInvH, 0); // 1,1 + pSubDiv->mvUV[1] = cVector3f(fX * fInvW, (fY + 1) * fInvH, 0); // 0,1 + pSubDiv->mvUV[2] = cVector3f(fX * fInvW, fY * fInvH, 0); // 0,0 + pSubDiv->mvUV[3] = cVector3f((fX + 1) * fInvW, fY * fInvH, 0); // 1,0 + } + } + } + + //----------------------------------------------------------------------- + + // Seems like this fucntion is never called any more... + void iParticleEmitter::UpdateLogic(float afTimeStep) { + if (IsActive() == false) + return; + + ////////////////////////////// + // Update sleep + if (IsDying() == false && iRenderer::GetRenderFrameCount() != mlRenderFrameCount) { + if (mlSleepCount <= 0) + return; + mlSleepCount--; + } else { + if (mlSleepCount < 10) + mlSleepCount = 10; + } + + ////////////////////////////// + // Update vars + mbUpdateGfx = true; + mbUpdateBV = true; + + ////////////////////////////// + // Update direction + if (mbUsesDirection) { + if (mlDirectionUpdateCount != GetMatrixUpdateCount()) { + mlDirectionUpdateCount = GetMatrixUpdateCount(); + cMatrixf mtxInv = cMath::MatrixInverse(GetWorldMatrix()); + mvDirection = mtxInv.GetUp(); + } + } + + UpdateMotion(afTimeStep); - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // CONSTRUCTORS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - - iParticleEmitter::iParticleEmitter(tString asName,tMaterialVec *avMaterials, - unsigned int alMaxParticles, cVector3f avSize, - cGraphics *apGraphics,cResources *apResources) - :iRenderable(asName) - { - - mpGraphics = apGraphics; - mpResources = apResources; + SetTransformUpdated(); + } + + void iParticleEmitter::KillInstantly() { + mlMaxParticles = 0; + mlNumOfParticles = 0; + mbDying = true; + } - ///////////////////////////////////// - //Create and set up particle data - mvParticles.resize(alMaxParticles); - for(int i=0;i<(int)alMaxParticles;i++) - { - mvParticles[i] = hplNew( cParticle, () ); - } - mlMaxParticles = alMaxParticles; - mlNumOfParticles =0; - - mvMaterials = avMaterials; + cMaterial* iParticleEmitter::GetMaterial() { + return (*mvMaterials)[(int)mfFrame]; + } - ////////////////////////////////// - //Create vertex buffer - mpVtxBuffer = apGraphics->GetLowLevel()->CreateVertexBuffer(eVertexBufferType_Hardware, - eVertexBufferDrawType_Tri, eVertexBufferUsageType_Stream, - alMaxParticles*4, alMaxParticles*6); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Position,eVertexBufferElementFormat_Float,4); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Color0,eVertexBufferElementFormat_Float,4); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Texture0,eVertexBufferElementFormat_Float,3); - - ////////////////////////////////// - //Fill the indices with quads - for(int i=0;i<(int)alMaxParticles;i++) - { - int lStart = i*4; - for(int j=0;j<3;j++) mpVtxBuffer->AddIndex(lStart + j); - for(int j=2;j<5;j++) mpVtxBuffer->AddIndex(lStart + (j==4?0:j)); - } - - ////////////////////////////////// - //Fill with texture coords (will do for most particle systems) - for(int i=0;i<(int)alMaxParticles;i++) - { - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Texture0, cVector3f(1,1,0)); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Texture0, cVector3f(0,1,0)); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Texture0, cVector3f(0,0,0)); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Texture0, cVector3f(1,0,0)); - } - - ////////////////////////////////// - //Set default values for pos and col - for(int i=0;i<(int)alMaxParticles*4;i++){ - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Position, 0); - mpVtxBuffer->AddVertexColor(eVertexBufferElement_Color0, cColor(1,1)); - } - - //////////////////////////////////// - // Compile vertex buffer - mpVtxBuffer->Compile(0); - - - //////////////////////////////////// - //Setup vars - mlSleepCount = 60*5; //Start with high sleep count to make sure a looping particle system reaches equilibrium. 5 secs should eb enough! - - mbDying = false; - mfFrame =0; - - mbUpdateGfx = true; - mbUpdateBV = true; - - mlDirectionUpdateCount = -1; - mvDirection = cVector3f(0,0,0); - - mvMaxDrawSize =0; - - mlAxisDrawUpdateCount = -1; - - mbApplyTransformToBV = false; - - mBoundingVolume.SetSize(0); - mBoundingVolume.SetPosition(0); - - mDrawType = eParticleEmitterType_FixedPoint; - mCoordSystem = eParticleEmitterCoordSystem_World; - - mbUsesDirection = false; //If Direction should be udpdated - - } - - //----------------------------------------------------------------------- - - iParticleEmitter::~iParticleEmitter() - { - for(int i=0;i<(int)mvParticles.size();i++) - { - hplDelete(mvParticles[i]); - } - - hplDelete(mpVtxBuffer); - } - - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // PUBLIC METHODS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - - void iParticleEmitter::SetSubDivUV(const cVector2l &avSubDiv) - { - //Check so that there is any subdivision and that no sub divison axis is - //equal or below zero - if( (avSubDiv.x > 1 || avSubDiv.x > 1) && (avSubDiv.x >0 && avSubDiv.y >0)) - { - int lSubDivNum = avSubDiv.x * avSubDiv.y; - - mvSubDivUV.resize(lSubDivNum); - - float fInvW = 1.0f / (float)avSubDiv.x; - float fInvH = 1.0f / (float)avSubDiv.y; - - for(int x=0; x < avSubDiv.x; ++x) - for(int y=0; y < avSubDiv.y; ++y) - { - int lIdx = y*avSubDiv.x + x; - - float fX = (float)x; - float fY = (float)y; - - cPESubDivision *pSubDiv = &mvSubDivUV[lIdx]; - - pSubDiv->mvUV[0] = cVector3f( (fX +1)*fInvW, (fY +1)*fInvH,0); //1,1 - pSubDiv->mvUV[1] = cVector3f( fX*fInvW, (fY +1)*fInvH,0); //0,1 - pSubDiv->mvUV[2] = cVector3f( fX*fInvW, fY*fInvH,0); //0,0 - pSubDiv->mvUV[3] = cVector3f( (fX +1)*fInvW, fY*fInvH,0); //1,0 - } - } - - } - - //----------------------------------------------------------------------- - - //Seems like this fucntion is never called any more... - void iParticleEmitter::UpdateLogic(float afTimeStep) - { - if(IsActive()==false) return; - - ////////////////////////////// - // Update sleep - if(IsDying()==false && iRenderer::GetRenderFrameCount() != mlRenderFrameCount) - { - if(mlSleepCount <= 0)return; - mlSleepCount--; - } - else - { - if(mlSleepCount<10) mlSleepCount =10; - } - - ////////////////////////////// - // Update vars - mbUpdateGfx = true; - mbUpdateBV = true; - - ////////////////////////////// - // Update direction - if(mbUsesDirection) - { - if(mlDirectionUpdateCount != GetMatrixUpdateCount()) - { - mlDirectionUpdateCount = GetMatrixUpdateCount(); - cMatrixf mtxInv = cMath::MatrixInverse(GetWorldMatrix()); - mvDirection = mtxInv.GetUp(); - } - } - - UpdateMotion(afTimeStep); - - SetTransformUpdated(); - } - - //----------------------------------------------------------------------- - - void iParticleEmitter::KillInstantly() - { - mlMaxParticles = 0; - mlNumOfParticles = 0; - mbDying = true; - } - - //----------------------------------------------------------------------- - - cMaterial* iParticleEmitter::GetMaterial() - { - return (*mvMaterials)[(int)mfFrame]; - } - - //----------------------------------------------------------------------- - - static inline void SetCol(float *apCol, const cColor &aCol) - { - apCol[0] = aCol.r; - apCol[1] = aCol.g; - apCol[2] = aCol.b; - apCol[3] = aCol.a; - } - - static inline void SetPos(float *apPos, const cVector3f &aPos) - { - apPos[0] = aPos.x; - apPos[1] = aPos.y; - apPos[2] = aPos.z; - } - - static inline void SetTex(float *apTex, const cVector3f &aPos) - { - apTex[0] = aPos.x; - apTex[1] = aPos.y; - apTex[2] = aPos.z; - } - - bool iParticleEmitter::UpdateGraphicsForViewport(cFrustum *apFrustum,float afFrameTime) - { - //if(mbUpdateGfx == false) return; - - ////////////////////////// - // Get Data - float *pPosArray = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Position); - float *pColArray = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Color0); - - - ////////////////////////// - // Set up color mul + bool iParticleEmitter::UpdateGraphicsForViewport(cFrustum* apFrustum, float afFrameTime) { + if(mlMaxParticles == 0) { + return true; + } + ASSERT(mlNumOfParticles <= mlMaxParticles); + + + m_activeCopy = (m_activeCopy + 1) % NumberActiveCopies; + + auto positionStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_POSITION); + auto colorStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_COLOR); + auto uvStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TEXCOORD0); + + + BufferUpdateDesc positionUpdateDesc = { positionStream->buffer().m_handle, + positionStream->stride() * ((mlMaxParticles * m_activeCopy * 4) + m_geometry->vertexOffset()), + positionStream->stride() * mlNumOfParticles * 4 }; + BufferUpdateDesc textureUpdateDesc = { uvStream->buffer().m_handle, + uvStream->stride() * ((mlMaxParticles * m_activeCopy * 4) + m_geometry->vertexOffset()), + uvStream->stride() * mlNumOfParticles * 4 }; + BufferUpdateDesc colorUpdateDesc = { colorStream->buffer().m_handle, + colorStream->stride() * ((mlMaxParticles * m_activeCopy * 4) + m_geometry->vertexOffset()), + colorStream->stride() * mlNumOfParticles * 4 }; + + // Set up color mul cColor colorMul = mpParentSystem->mColor; - //Set alpha based on fade distance. - if(mpParentSystem->mbFadeAtDistance) - { - float fDistSqr = cMath::Vector3DistSqr(mpParentSystem->GetBoundingVolume()->GetWorldCenter(), apFrustum->GetOrigin()); - float fMinStart = mpParentSystem->mfMinFadeDistanceStart; - float fMaxStart = mpParentSystem->mfMaxFadeDistanceStart; - float fMinEnd = mpParentSystem->mfMinFadeDistanceEnd; - float fMaxEnd = mpParentSystem->mfMaxFadeDistanceEnd; - - /////////// - // Below min - if(fMinStart >0 && fDistSqr < fMinStart* fMinStart) - { - if(fDistSqr <= fMinEnd * fMinEnd) - { - colorMul.a = 0; - } - else - { - float fDist = sqrt(fDistSqr); - colorMul.a *= (fDist - fMinEnd)/(fMinStart - fMinEnd); - } - } - /////////// - // Above max - if(fMaxStart >0 && fDistSqr > fMaxStart* fMaxStart) - { - if(fDistSqr >= fMaxEnd * fMaxEnd) - { - colorMul.a = 0; - } - else - { - float fDist = sqrt(fDistSqr); - colorMul.a *= 1 - (fDist - fMaxStart)/(fMaxEnd - fMaxStart); - } - } - } - //Change color based on alpha - if(mbMultiplyRGBWithAlpha) - { - colorMul.r *= colorMul.a; - colorMul.g *= colorMul.a; - colorMul.b *= colorMul.a; - } - - ////////////////////////////// - // If alpha is 0, skip rendering anything - if(colorMul.a <= 0) - { - mpVtxBuffer->SetElementNum(0); - return false; - } - - ////////////////////////////// - // RENDERING - - if ( mPEType == ePEType_Beam) - { - // for (int i=0; i<(int)mlNumOfParticles; i++) - // { - // cParticle *pParticle = mvParticles[i]; - - // for (int j = 0; j < (int) pParticle->mvBeamPoints->size(); j++) - // { - - // } - // } - - } - else - { - ////////////////////////////////////////////////// - // SUB DIVISION SET UP - if(mvSubDivUV.size() > 1) - { - float *pTexArray = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Texture0); - - for(int i=0;i<(int)mlNumOfParticles;i++) - { - cParticle *pParticle = mvParticles[i]; - - cPESubDivision &subDiv = mvSubDivUV[pParticle->mlSubDivNum]; - - SetTex(&pTexArray[i*12 + 0*3],subDiv.mvUV[0]); - SetTex(&pTexArray[i*12 + 1*3],subDiv.mvUV[1]); - SetTex(&pTexArray[i*12 + 2*3],subDiv.mvUV[2]); - SetTex(&pTexArray[i*12 + 3*3],subDiv.mvUV[3]); - - /*SetTex(&pTexArray[i*12 + 0*3], cVector3f(1,1,0)); - SetTex(&pTexArray[i*12 + 1*3], cVector3f(0,1,0)); - SetTex(&pTexArray[i*12 + 2*3], cVector3f(0,0,0)); - SetTex(&pTexArray[i*12 + 3*3], cVector3f(1,0,0));*/ - } - } - - ////////////////////////////////////////////////// - // FIXED POINT - if(mDrawType == eParticleEmitterType_FixedPoint) - { - cVector3f vAdd[4] = { - cVector3f( mvDrawSize.x,-mvDrawSize.y,0), - cVector3f(-mvDrawSize.x,-mvDrawSize.y,0), - cVector3f(-mvDrawSize.x, mvDrawSize.y,0), - cVector3f( mvDrawSize.x, mvDrawSize.y,0) - }; - - //If this is a reflection, need to invert the ordering. - if(apFrustum->GetInvertsCullMode()) - { - for(int i=0; i<4; ++i) vAdd[i].y = -vAdd[i].y; - } - - // NEW - - // --- - - - int lVtxStride = mpVtxBuffer->GetElementNum(eVertexBufferElement_Position); - int lVtxQuadSize = lVtxStride*4; - - for(int i=0;i<(int)mlNumOfParticles;i++) - { - cParticle *pParticle = mvParticles[i]; - - //This is not the fastest thing possible... - cVector3f vParticlePos = pParticle->mvPos; - - if(mCoordSystem == eParticleEmitterCoordSystem_Local){ - vParticlePos = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos); - } - - cVector3f vPos = cMath::MatrixMul(apFrustum->GetViewMatrix(), vParticlePos); - cColor finalColor = pParticle->mColor * colorMul; - - SetPos(&pPosArray[i*lVtxQuadSize + 0*lVtxStride], vPos + vAdd[0]); - SetCol(&pColArray[i*16 + 0*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 1*lVtxStride], vPos + vAdd[1]); - SetCol(&pColArray[i*16 + 1*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 2*lVtxStride], vPos + vAdd[2]); - SetCol(&pColArray[i*16 + 2*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 3*lVtxStride], vPos + vAdd[3]); - SetCol(&pColArray[i*16 + 3*4], finalColor); - } - } - ////////////////////////////////////////////////// - // DYNAMIC POINT - else if(mDrawType == eParticleEmitterType_DynamicPoint) - { - cVector3f vAdd[4] = { - cVector3f( mvDrawSize.x,-mvDrawSize.y,0), - cVector3f(-mvDrawSize.x,-mvDrawSize.y,0), - cVector3f(-mvDrawSize.x, mvDrawSize.y,0), - cVector3f( mvDrawSize.x, mvDrawSize.y,0) - }; - - //If this is a reflection, need to invert the ordering. - if(apFrustum->GetInvertsCullMode()) - { - for(int i=0; i<4; ++i) vAdd[i].y = -vAdd[i].y; - } - - int lVtxStride = mpVtxBuffer->GetElementNum(eVertexBufferElement_Position); - int lVtxQuadSize = lVtxStride*4; - - for(int i=0;i<(int)mlNumOfParticles;i++) - { - cParticle *pParticle = mvParticles[i]; - - //This is not the fastest thing possible - cVector3f vParticlePos = pParticle->mvPos; - - - if(mCoordSystem == eParticleEmitterCoordSystem_Local){ - vParticlePos = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos); - } - - cVector3f vPos = cMath::MatrixMul(apFrustum->GetViewMatrix(), vParticlePos); - - - // NEW - - cVector3f vParticleSize = pParticle->mvSize; - cColor finalColor = pParticle->mColor * colorMul; - - if ( mbUsePartSpin ) - { - cMatrixf mtxRotationMatrix = cMath::MatrixRotateZ(pParticle->mfSpin); - - - SetPos(&pPosArray[i*lVtxQuadSize + 0*lVtxStride], vPos + cMath::MatrixMul(mtxRotationMatrix, vAdd[0]*vParticleSize)); - SetCol(&pColArray[i*16 + 0*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 1*lVtxStride], vPos + cMath::MatrixMul(mtxRotationMatrix, vAdd[1]*vParticleSize)); - SetCol(&pColArray[i*16 + 1*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 2*lVtxStride], vPos + cMath::MatrixMul(mtxRotationMatrix, vAdd[2]*vParticleSize)); - SetCol(&pColArray[i*16 + 2*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 3*lVtxStride], vPos + cMath::MatrixMul(mtxRotationMatrix, vAdd[3]*vParticleSize)); - SetCol(&pColArray[i*16 + 3*4], finalColor); - - } - else - { - //-- - - SetPos(&pPosArray[i*lVtxQuadSize + 0*lVtxStride], vPos + vAdd[0]*vParticleSize); - SetCol(&pColArray[i*16 + 0*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 1*lVtxStride], vPos + vAdd[1]*vParticleSize); - SetCol(&pColArray[i*16 + 1*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 2*lVtxStride], vPos + vAdd[2]*vParticleSize); - SetCol(&pColArray[i*16 + 2*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 3*lVtxStride], vPos + vAdd[3]*vParticleSize); - SetCol(&pColArray[i*16 + 3*4], finalColor); - - } - } - } - ////////////////////////////////////////////////// - // LINE - else if(mDrawType == eParticleEmitterType_Line) - { - int lVtxStride = mpVtxBuffer->GetElementNum(eVertexBufferElement_Position); - int lVtxQuadSize = lVtxStride*4; - - for(int i=0;i<(int)mlNumOfParticles;i++) - { - cParticle *pParticle = mvParticles[i]; - - //This is not the fastest thing possible... - - cVector3f vParticlePos1 = pParticle->mvPos; - cVector3f vParticlePos2 = pParticle->mvLastPos; - - if(mCoordSystem == eParticleEmitterCoordSystem_Local){ - vParticlePos1 = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos1); - vParticlePos2 = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos2); - } - - cVector3f vPos1 = cMath::MatrixMul(apFrustum->GetViewMatrix(), vParticlePos1); - cVector3f vPos2 = cMath::MatrixMul(apFrustum->GetViewMatrix(), vParticlePos2); - - cVector3f vDirY; - cVector2f vDirX; - - if(vPos1 == vPos2) - { - vDirY = cVector3f(0,1,0); - vDirX = cVector2f(1,0); - } - else - { - vDirY = vPos1 - vPos2; - vDirY.Normalize(); - vDirX = cVector2f(vDirY.y,-vDirY.x); - vDirX.Normalize(); - } - - vDirX = vDirX * mvDrawSize.x * pParticle->mvSize.x; - vDirY = vDirY * mvDrawSize.y * pParticle->mvSize.y; - - if(apFrustum->GetInvertsCullMode()) vDirY = vDirY*-1; - - cColor finalColor = pParticle->mColor * colorMul; - - SetPos(&pPosArray[i*lVtxQuadSize + 0*lVtxStride], vPos2 + vDirY*-1 + vDirX); - SetCol(&pColArray[i*16 + 0*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 1*lVtxStride], vPos2 + vDirY*-1 + vDirX*-1); - SetCol(&pColArray[i*16 + 1*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 2*lVtxStride], vPos1 + vDirY + vDirX*-1); - SetCol(&pColArray[i*16 + 2*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 3*lVtxStride], vPos1 + vDirY + vDirX); - SetCol(&pColArray[i*16 + 3*4], finalColor); - } - } - ////////////////////////////////////////////////// - // AXIS - else if(mDrawType == eParticleEmitterType_Axis) - { - if(mlAxisDrawUpdateCount != GetMatrixUpdateCount()) - { - mlAxisDrawUpdateCount = GetMatrixUpdateCount(); - cMatrixf mtxInv = cMath::MatrixInverse(GetWorldMatrix()); - mvRight = mtxInv.GetRight(); - mvForward = mtxInv.GetForward(); - } - - cVector3f vAdd[4]; - /*= - { - mvRight + mvForward * 1, - mvRight * -1 + mvForward * 1, - mvRight * -1 + mvForward * -1, - mvRight + mvForward * -1 - };*/ - - int lVtxStride = mpVtxBuffer->GetElementNum(eVertexBufferElement_Position); - int lVtxQuadSize = lVtxStride*4; - - for(int i=0;i<(int)mlNumOfParticles;i++) - { - cParticle *pParticle = mvParticles[i]; - - //This is not the fastest thing possible - cVector3f vParticlePos = pParticle->mvPos; - - - if(mCoordSystem == eParticleEmitterCoordSystem_Local){ - vParticlePos = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos); - } - - cVector3f vPos = vParticlePos;//cMath::MatrixMul(apCamera->GetViewMatrix(), vParticlePos); - cVector2f &vSize = pParticle->mvSize; - - vAdd[0] = mvRight * vSize.x + mvForward * vSize.y; - vAdd[1] = mvRight * -vSize.x + mvForward * vSize.y; - vAdd[2] = mvRight * -vSize.x + mvForward * -vSize.y; - vAdd[3] = mvRight * vSize.x + mvForward * -vSize.y; - - cColor finalColor = pParticle->mColor * colorMul; - - SetPos(&pPosArray[i*lVtxQuadSize + 0*lVtxStride], vPos + vAdd[0]); - SetCol(&pColArray[i*16 + 0*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 1*lVtxStride], vPos + vAdd[1]); - SetCol(&pColArray[i*16 + 1*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 2*lVtxStride], vPos + vAdd[2]); - SetCol(&pColArray[i*16 + 2*4], finalColor); - - SetPos(&pPosArray[i*lVtxQuadSize + 3*lVtxStride], vPos + vAdd[3]); - SetCol(&pColArray[i*16 + 3*4], finalColor); - } - } - - mpVtxBuffer->SetElementNum(mlNumOfParticles * 6); - - //Update the vertex buffer data - - if(mvSubDivUV.size() > 1) - mpVtxBuffer->UpdateData(eVertexElementFlag_Position | eVertexElementFlag_Color0 | eVertexElementFlag_Texture0, false); - else - mpVtxBuffer->UpdateData(eVertexElementFlag_Position | eVertexElementFlag_Color0, false); - - } - - return true; - } - - - DrawPacket iParticleEmitter::ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) - { - return static_cast(mpVtxBuffer)->resolveGeometryBinding(frame.m_currentFrame, elements); - } - - iVertexBuffer* iParticleEmitter::GetVertexBuffer() - { - return mpVtxBuffer; - } - - //----------------------------------------------------------------------- - - bool iParticleEmitter::IsVisible() - { - if(IsActive()==false) return false; - return mbIsVisible; - } - - //----------------------------------------------------------------------- - - cBoundingVolume* iParticleEmitter::GetBoundingVolume() - { - if(mbUpdateBV) - { + // Set alpha based on fade distance. + if (mpParentSystem->mbFadeAtDistance) { + float fDistSqr = cMath::Vector3DistSqr(mpParentSystem->GetBoundingVolume()->GetWorldCenter(), apFrustum->GetOrigin()); + float fMinStart = mpParentSystem->mfMinFadeDistanceStart; + float fMaxStart = mpParentSystem->mfMaxFadeDistanceStart; + float fMinEnd = mpParentSystem->mfMinFadeDistanceEnd; + float fMaxEnd = mpParentSystem->mfMaxFadeDistanceEnd; + + // Below min + if (fMinStart > 0 && fDistSqr < fMinStart * fMinStart) { + if (fDistSqr <= fMinEnd * fMinEnd) { + colorMul.a = 0; + } else { + float fDist = sqrt(fDistSqr); + colorMul.a *= (fDist - fMinEnd) / (fMinStart - fMinEnd); + } + } + // Above max + if (fMaxStart > 0 && fDistSqr > fMaxStart * fMaxStart) { + if (fDistSqr >= fMaxEnd * fMaxEnd) { + colorMul.a = 0; + } else { + float fDist = sqrt(fDistSqr); + colorMul.a *= 1 - (fDist - fMaxStart) / (fMaxEnd - fMaxStart); + } + } + } + // Change color based on alpha + if (mbMultiplyRGBWithAlpha) { + colorMul.r *= colorMul.a; + colorMul.g *= colorMul.a; + colorMul.b *= colorMul.a; + } + + // If alpha is 0, skip rendering anything + m_numberParticlesRender = mlNumOfParticles; + if (colorMul.a <= 0) { + m_numberParticlesRender = 0; + return false; + } + + if (mPEType == ePEType_Beam) { + // something something beam Idunno + } else { + + if (mvSubDivUV.size() > 1) { + beginUpdateResource(&textureUpdateDesc); + GraphicsBuffer gpuUvBuffer(textureUpdateDesc); + auto textureView = gpuUvBuffer.CreateStructuredView(); + + for (uint32_t i = 0; i < mlNumOfParticles; i++) { + cParticle* pParticle = mvParticles[i]; + + cPESubDivision& subDiv = mvSubDivUV[pParticle->mlSubDivNum]; + textureView.Write((i * 4) + 0, float2(subDiv.mvUV[0].x, subDiv.mvUV[0].y)); + textureView.Write((i * 4) + 1, float2(subDiv.mvUV[1].x, subDiv.mvUV[1].y)); + textureView.Write((i * 4) + 2, float2(subDiv.mvUV[2].x, subDiv.mvUV[2].y)); + textureView.Write((i * 4) + 3, float2(subDiv.mvUV[3].x, subDiv.mvUV[3].y)); + } + endUpdateResource(&textureUpdateDesc); + } + + // FIXED POINT + switch (mDrawType) { + case eParticleEmitterType_FixedPoint: + { + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + auto positionView = gpuPositionBuffer.CreateStructuredView(); + auto colorView = gpuColorBuffer.CreateStructuredView(); + + cVector3f vAdd[4] = { cVector3f(mvDrawSize.x, -mvDrawSize.y, 0), + cVector3f(-mvDrawSize.x, -mvDrawSize.y, 0), + cVector3f(-mvDrawSize.x, mvDrawSize.y, 0), + cVector3f(mvDrawSize.x, mvDrawSize.y, 0) }; + + // If this is a reflection, need to invert the ordering. + if (apFrustum->GetInvertsCullMode()) { + for (int i = 0; i < 4; ++i) + vAdd[i].y = -vAdd[i].y; + } + + for (uint32_t i = 0; i < mlNumOfParticles; i++) { + cParticle* pParticle = mvParticles[i]; + + // This is not the fastest thing possible... + cVector3f vParticlePos = pParticle->mvPos; + + if (mCoordSystem == eParticleEmitterCoordSystem_Local) { + vParticlePos = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos); + } + + cVector3f vPos = cMath::MatrixMul(apFrustum->GetViewMatrix(), vParticlePos); + cColor finalColor = pParticle->mColor * colorMul; + + positionView.Write((i * 4) + 0, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[0]))); + positionView.Write((i * 4) + 1, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[1]))); + positionView.Write((i * 4) + 2, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[2]))); + positionView.Write((i * 4) + 3, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[3]))); + + colorView.Write((i * 4) + 0, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 1, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 2, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 3, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + } + + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&colorUpdateDesc); + break; + } + case eParticleEmitterType_DynamicPoint: + { + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + auto positionView = gpuPositionBuffer.CreateStructuredView(); + auto colorView = gpuColorBuffer.CreateStructuredView(); + + cVector3f vAdd[4] = { cVector3f(mvDrawSize.x, -mvDrawSize.y, 0), + cVector3f(-mvDrawSize.x, -mvDrawSize.y, 0), + cVector3f(-mvDrawSize.x, mvDrawSize.y, 0), + cVector3f(mvDrawSize.x, mvDrawSize.y, 0) }; + + // If this is a reflection, need to invert the ordering. + if (apFrustum->GetInvertsCullMode()) { + for (int i = 0; i < 4; ++i) + vAdd[i].y = -vAdd[i].y; + } + + for (uint32_t i = 0; i < mlNumOfParticles; i++) { + cParticle* pParticle = mvParticles[i]; + + // This is not the fastest thing possible + cVector3f vParticlePos = pParticle->mvPos; + + if (mCoordSystem == eParticleEmitterCoordSystem_Local) { + vParticlePos = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos); + } + + cVector3f vPos = cMath::MatrixMul(apFrustum->GetViewMatrix(), vParticlePos); + + cVector3f vParticleSize = pParticle->mvSize; + cColor finalColor = pParticle->mColor * colorMul; + + if (mbUsePartSpin) { + cMatrixf mtxRotationMatrix = cMath::MatrixRotateZ(pParticle->mfSpin); + + positionView.Write( + (i * 4) + 0, + v3ToF3(cMath::ToForgeVec3(vPos + cMath::MatrixMul(mtxRotationMatrix, vAdd[0] * vParticleSize)))); + positionView.Write( + (i * 4) + 1, + v3ToF3(cMath::ToForgeVec3(vPos + cMath::MatrixMul(mtxRotationMatrix, vAdd[1] * vParticleSize)))); + positionView.Write( + (i * 4) + 2, + v3ToF3(cMath::ToForgeVec3(vPos + cMath::MatrixMul(mtxRotationMatrix, vAdd[2] * vParticleSize)))); + positionView.Write( + (i * 4) + 3, + v3ToF3(cMath::ToForgeVec3(vPos + cMath::MatrixMul(mtxRotationMatrix, vAdd[3] * vParticleSize)))); + + colorView.Write((i * 4) + 0, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 1, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 2, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 3, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + + } else { + positionView.Write((i * 4) + 0, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[0] * vParticleSize))); + positionView.Write((i * 4) + 1, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[1] * vParticleSize))); + positionView.Write((i * 4) + 2, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[2] * vParticleSize))); + positionView.Write((i * 4) + 3, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[3] * vParticleSize))); + + colorView.Write((i * 4) + 0, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 1, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 2, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 3, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + } + } + + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&colorUpdateDesc); + break; + } + case eParticleEmitterType_Line: + { + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + auto positionView = gpuPositionBuffer.CreateStructuredView(); + auto colorView = gpuColorBuffer.CreateStructuredView(); + + for (uint32_t i = 0; i < mlNumOfParticles; i++) { + cParticle* pParticle = mvParticles[i]; + + // This is not the fastest thing possible... + + cVector3f vParticlePos1 = pParticle->mvPos; + cVector3f vParticlePos2 = pParticle->mvLastPos; + + if (mCoordSystem == eParticleEmitterCoordSystem_Local) { + vParticlePos1 = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos1); + vParticlePos2 = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos2); + } + + cVector3f vPos1 = cMath::MatrixMul(apFrustum->GetViewMatrix(), vParticlePos1); + cVector3f vPos2 = cMath::MatrixMul(apFrustum->GetViewMatrix(), vParticlePos2); + + cVector3f vDirY; + cVector2f vDirX; + + if (vPos1 == vPos2) { + vDirY = cVector3f(0, 1, 0); + vDirX = cVector2f(1, 0); + } else { + vDirY = vPos1 - vPos2; + vDirY.Normalize(); + vDirX = cVector2f(vDirY.y, -vDirY.x); + vDirX.Normalize(); + } + + vDirX = vDirX * mvDrawSize.x * pParticle->mvSize.x; + vDirY = vDirY * mvDrawSize.y * pParticle->mvSize.y; + + if (apFrustum->GetInvertsCullMode()) + vDirY = vDirY * -1; + + cColor finalColor = pParticle->mColor * colorMul; + + positionView.Write((i * 4) + 0, v3ToF3(cMath::ToForgeVec3(vPos2 + vDirY * -1 + vDirX))); + positionView.Write((i * 4) + 1, v3ToF3(cMath::ToForgeVec3(vPos2 + vDirY * -1 + vDirX * -1))); + positionView.Write((i * 4) + 2, v3ToF3(cMath::ToForgeVec3(vPos1 + vDirY + vDirX * -1))); + positionView.Write((i * 4) + 3, v3ToF3(cMath::ToForgeVec3(vPos1 + vDirY + vDirX))); + + colorView.Write((i * 4) + 0, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 1, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 2, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 3, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + } + + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&colorUpdateDesc); + + break; + } + case eParticleEmitterType_Axis: { + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + auto positionView = gpuPositionBuffer.CreateStructuredView(); + auto colorView = gpuColorBuffer.CreateStructuredView(); + + if (mlAxisDrawUpdateCount != GetMatrixUpdateCount()) { + mlAxisDrawUpdateCount = GetMatrixUpdateCount(); + cMatrixf mtxInv = cMath::MatrixInverse(GetWorldMatrix()); + mvRight = mtxInv.GetRight(); + mvForward = mtxInv.GetForward(); + } + + cVector3f vAdd[4]; + + for (int i = 0; i < (int)mlNumOfParticles; i++) { + cParticle* pParticle = mvParticles[i]; + + // This is not the fastest thing possible + cVector3f vParticlePos = pParticle->mvPos; + + if (mCoordSystem == eParticleEmitterCoordSystem_Local) { + vParticlePos = cMath::MatrixMul(mpParentSystem->GetWorldMatrix(), vParticlePos); + } + + cVector3f vPos = vParticlePos; // cMath::MatrixMul(apCamera->GetViewMatrix(), vParticlePos); + cVector2f& vSize = pParticle->mvSize; + + vAdd[0] = mvRight * vSize.x + mvForward * vSize.y; + vAdd[1] = mvRight * -vSize.x + mvForward * vSize.y; + vAdd[2] = mvRight * -vSize.x + mvForward * -vSize.y; + vAdd[3] = mvRight * vSize.x + mvForward * -vSize.y; + + cColor finalColor = pParticle->mColor * colorMul; + + positionView.Write((i * 4) + 0, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[0]))); + positionView.Write((i * 4) + 1, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[1]))); + positionView.Write((i * 4) + 2, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[2]))); + positionView.Write((i * 4) + 3, v3ToF3(cMath::ToForgeVec3(vPos + vAdd[3]))); + + colorView.Write((i * 4) + 0, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 1, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 2, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + colorView.Write((i * 4) + 3, float4(finalColor.r, finalColor.g, finalColor.b, finalColor.a)); + } + + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&colorUpdateDesc); + break; + } + } + + } + + return true; + } + + DrawPacket iParticleEmitter::ResolveDrawPacket(const ForgeRenderer::Frame& frame) { + DrawPacket packet; + if (m_numberParticlesRender == 0) { + return packet; + } + + DrawPacket::GeometrySetBinding binding{}; + packet.m_type = DrawPacket::DrawGeometryset; + binding.m_subAllocation = m_geometry.get(); + binding.m_set = GraphicsAllocator::AllocationSet::ParticleSet; + binding.m_indexOffset = 0; + binding.m_numIndices = m_numberParticlesRender * 6; + binding.m_vertexOffset = (mlMaxParticles * m_activeCopy * 4); + packet.m_unified = binding; + return packet; + } + + iVertexBuffer* iParticleEmitter::GetVertexBuffer() { + return nullptr; + } + + bool iParticleEmitter::IsVisible() { + if (IsActive() == false) + return false; + return mbIsVisible; + } + + cBoundingVolume* iParticleEmitter::GetBoundingVolume() { + if (mbUpdateBV) { cVector3f vMin; - cVector3f vMax; - - if(mlNumOfParticles >0) - { - //Make a bounding volume that encompasses start pos too! - vMin = GetWorldPosition(); - vMax = GetWorldPosition(); - - for(int i=0;i<(int)mlNumOfParticles;i++) - { - cParticle *pParticle = mvParticles[i]; - - //X - if(pParticle->mvPos.x < vMin.x) vMin.x = pParticle->mvPos.x; - else if(pParticle->mvPos.x > vMax.x) vMax.x = pParticle->mvPos.x; - - //Y - if(pParticle->mvPos.y < vMin.y) vMin.y = pParticle->mvPos.y; - else if(pParticle->mvPos.y > vMax.y) vMax.y = pParticle->mvPos.y; - - //Z - if(pParticle->mvPos.z < vMin.z) vMin.z = pParticle->mvPos.z; - else if(pParticle->mvPos.z > vMax.z) vMax.z = pParticle->mvPos.z; - } - } - else - { - vMin = GetWorldPosition(); - vMax = GetWorldPosition();; - } - - /////////////////////////7 - // Add size for axis - if(mDrawType == eParticleEmitterType_Axis) - { - if(mlAxisDrawUpdateCount != GetMatrixUpdateCount()) - { - mlAxisDrawUpdateCount = GetMatrixUpdateCount(); - cMatrixf mtxInv = cMath::MatrixInverse(GetWorldMatrix()); - mvRight = mtxInv.GetRight(); - mvForward = mtxInv.GetForward(); - } - - cVector3f vAdd = mvRight*mvMaxDrawSize.x + mvForward*mvMaxDrawSize.y; - - vMax += vAdd; - vMin -= vAdd; - } - /////////////////////////7 - // Add size for other particle types. - else - { - vMax += cVector3f(mvMaxDrawSize.x,mvMaxDrawSize.y, mvMaxDrawSize.x); - vMin -= cVector3f(mvMaxDrawSize.x,mvMaxDrawSize.y, mvMaxDrawSize.x); - } - - mBoundingVolume.SetLocalMinMax(vMin, vMax); - - //Log("Min: (%f, %f, %f) Max: (%f, %f, %f)\n", vMin.x, vMin.y, vMin.z, vMax.x,vMax.y,vMax.z); - - if(mCoordSystem == eParticleEmitterCoordSystem_Local) - { - mBoundingVolume.SetTransform(mpParentSystem->GetWorldMatrix()); - } - - mbUpdateBV = false; - } - - return &mBoundingVolume; - } - - //----------------------------------------------------------------------- - - cMatrixf* iParticleEmitter::GetModelMatrix(cFrustum *apFrustum) - { - if(apFrustum) - { - if(mDrawType == eParticleEmitterType_Axis) - { - m_mtxTemp = cMatrixf::Identity; - } - //This is really not good... - else if(mCoordSystem == eParticleEmitterCoordSystem_World) - { - m_mtxTemp = cMath::MatrixInverse(apFrustum->GetViewMatrix()); - } - else - { - m_mtxTemp = cMath::MatrixInverse(apFrustum->GetViewMatrix()); - //m_mtxTemp = cMath::MatrixMul(cMath::MatrixInverse(apCamera->GetViewMatrix()), - // GetWorldMatrix()); - } - - //m_mtxTemp.SetTranslation(cVector3f(0,0,0));//GetWorldMatrix().GetTranslation()); - - //m_mtxTemp = cMatrixf::Identity; - - //cMatrixf mtxCam = apCamera->GetViewMatrix(); - //Log("MATRIX: %s\n",mtxCam.ToString().c_str()); - - return &m_mtxTemp; - - } - else - { - return &GetWorldMatrix(); - } - } - - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // PROTECTED METHODS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - - cParticle* iParticleEmitter::CreateParticle() - { - if(mlNumOfParticles == mlMaxParticles) return NULL; - ++mlNumOfParticles; - return mvParticles[mlNumOfParticles-1]; - } - - //----------------------------------------------------------------------- - - void iParticleEmitter::SwapRemove(unsigned int alIndex) - { - if(alIndex < mlNumOfParticles-1) - { - cParticle* pTemp = mvParticles[alIndex]; - mvParticles[alIndex] = mvParticles[mlNumOfParticles-1]; - mvParticles[mlNumOfParticles-1] = pTemp; - } - mlNumOfParticles--; - } - - //----------------------------------------------------------------------- - - //----------------------------------------------------------------------- -} + cVector3f vMax; + + if (mlNumOfParticles > 0) { + // Make a bounding volume that encompasses start pos too! + vMin = GetWorldPosition(); + vMax = GetWorldPosition(); + + for (int i = 0; i < (int)mlNumOfParticles; i++) { + cParticle* pParticle = mvParticles[i]; + + // X + if (pParticle->mvPos.x < vMin.x) + vMin.x = pParticle->mvPos.x; + else if (pParticle->mvPos.x > vMax.x) + vMax.x = pParticle->mvPos.x; + + // Y + if (pParticle->mvPos.y < vMin.y) + vMin.y = pParticle->mvPos.y; + else if (pParticle->mvPos.y > vMax.y) + vMax.y = pParticle->mvPos.y; + + // Z + if (pParticle->mvPos.z < vMin.z) + vMin.z = pParticle->mvPos.z; + else if (pParticle->mvPos.z > vMax.z) + vMax.z = pParticle->mvPos.z; + } + } else { + vMin = GetWorldPosition(); + vMax = GetWorldPosition(); + ; + } + + /////////////////////////7 + // Add size for axis + if (mDrawType == eParticleEmitterType_Axis) { + if (mlAxisDrawUpdateCount != GetMatrixUpdateCount()) { + mlAxisDrawUpdateCount = GetMatrixUpdateCount(); + cMatrixf mtxInv = cMath::MatrixInverse(GetWorldMatrix()); + mvRight = mtxInv.GetRight(); + mvForward = mtxInv.GetForward(); + } + + cVector3f vAdd = mvRight * mvMaxDrawSize.x + mvForward * mvMaxDrawSize.y; + + vMax += vAdd; + vMin -= vAdd; + } + /////////////////////////7 + // Add size for other particle types. + else { + vMax += cVector3f(mvMaxDrawSize.x, mvMaxDrawSize.y, mvMaxDrawSize.x); + vMin -= cVector3f(mvMaxDrawSize.x, mvMaxDrawSize.y, mvMaxDrawSize.x); + } + + mBoundingVolume.SetLocalMinMax(vMin, vMax); + + // Log("Min: (%f, %f, %f) Max: (%f, %f, %f)\n", vMin.x, vMin.y, vMin.z, vMax.x,vMax.y,vMax.z); + + if (mCoordSystem == eParticleEmitterCoordSystem_Local) { + mBoundingVolume.SetTransform(mpParentSystem->GetWorldMatrix()); + } + + mbUpdateBV = false; + } + + return &mBoundingVolume; + } + + cMatrixf* iParticleEmitter::GetModelMatrix(cFrustum* apFrustum) { + if (apFrustum) { + if (mDrawType == eParticleEmitterType_Axis) { + m_mtxTemp = cMatrixf::Identity; + } + // This is really not good... + else if (mCoordSystem == eParticleEmitterCoordSystem_World) { + m_mtxTemp = cMath::MatrixInverse(apFrustum->GetViewMatrix()); + } else { + m_mtxTemp = cMath::MatrixInverse(apFrustum->GetViewMatrix()); + // m_mtxTemp = cMath::MatrixMul(cMath::MatrixInverse(apCamera->GetViewMatrix()), + // GetWorldMatrix()); + } + + // m_mtxTemp.SetTranslation(cVector3f(0,0,0));//GetWorldMatrix().GetTranslation()); + + // m_mtxTemp = cMatrixf::Identity; + + // cMatrixf mtxCam = apCamera->GetViewMatrix(); + // Log("MATRIX: %s\n",mtxCam.ToString().c_str()); + + return &m_mtxTemp; + + } else { + return &GetWorldMatrix(); + } + } + + cParticle* iParticleEmitter::CreateParticle() { + if (mlNumOfParticles == mlMaxParticles) + return NULL; + ++mlNumOfParticles; + return mvParticles[mlNumOfParticles - 1]; + } + + void iParticleEmitter::SwapRemove(unsigned int alIndex) { + if (alIndex < mlNumOfParticles - 1) { + cParticle* pTemp = mvParticles[alIndex]; + mvParticles[alIndex] = mvParticles[mlNumOfParticles - 1]; + mvParticles[mlNumOfParticles - 1] = pTemp; + } + mlNumOfParticles--; + } + +} // namespace hpl diff --git a/HPL2/sources/scene/RenderableContainer.cpp b/HPL2/sources/scene/RenderableContainer.cpp index 65116d7fd..676914ebd 100644 --- a/HPL2/sources/scene/RenderableContainer.cpp +++ b/HPL2/sources/scene/RenderableContainer.cpp @@ -22,16 +22,69 @@ #include "system/LowLevelSystem.h" #include "graphics/Renderable.h" + +#include "math/cFrustum.h" #include "math/Math.h" namespace hpl { + void iRenderableContainer::WalkRenderableContainer( + iRenderableContainer& container, cFrustum* frustum, std::function handler, tRenderableFlag renderableFlag) { + std::function walkRenderables; + walkRenderables = [&](iRenderableContainerNode* childNode) { + childNode->UpdateBeforeUse(); + for (auto& childNode : childNode->GetChildNodes()) { + childNode->UpdateBeforeUse(); + eCollision frustumCollision = frustum->CollideNode(childNode); + if (frustumCollision == eCollision_Outside) { + continue; + } + if (frustum->CheckAABBNearPlaneIntersection(childNode->GetMin(), childNode->GetMax())) { + cVector3f vViewSpacePos = cMath::MatrixMul(frustum->GetViewMatrix(), childNode->GetCenter()); + childNode->SetViewDistance(vViewSpacePos.z); + childNode->SetInsideView(true); + } else { + // Frustum origin is outside of node. Do intersection test. + cVector3f vIntersection; + cMath::CheckAABBLineIntersection( + childNode->GetMin(), childNode->GetMax(), frustum->GetOrigin(), childNode->GetCenter(), &vIntersection, NULL); + cVector3f vViewSpacePos = cMath::MatrixMul(frustum->GetViewMatrix(), vIntersection); + childNode->SetViewDistance(vViewSpacePos.z); + childNode->SetInsideView(false); + } + walkRenderables(childNode); + } + for (auto& pObject : childNode->GetObjects()) { + if (!iRenderable::IsObjectIsVisible(*pObject, renderableFlag, {})) { + continue; + } + handler(pObject); + } + }; + auto rootNode = container.GetRoot(); + rootNode->UpdateBeforeUse(); + rootNode->SetInsideView(true); + walkRenderables(rootNode); + + } + + bool iRenderableContainer::IsRenderableNodeIsVisible(iRenderableContainerNode& apNode, std::span clipPlanes) { + for(auto& plane: clipPlanes) + { + if (cMath::CheckPlaneAABBCollision(plane, apNode.GetMin(), apNode.GetMax(), apNode.GetCenter(), apNode.GetRadius()) == + eCollision_Outside) + { + return false; + } + } + return true; + } + cRenderableContainerObjectCallback::cRenderableContainerObjectCallback() { } - //----------------------------------------------------------------------- static void PushUpNeedPropertyUpdate(iRenderableContainerNode *apNode) { @@ -47,25 +100,18 @@ namespace hpl { if(pNode) PushUpNeedPropertyUpdate(pNode); } - //----------------------------------------------------------------------- void cRenderableContainerObjectCallback::OnVisibleChange(iRenderable *apObject) { PushUpNeedPropertyUpdateFromObject(apObject); } - //----------------------------------------------------------------------- void cRenderableContainerObjectCallback::OnRenderFlagsChange(iRenderable *apObject) { PushUpNeedPropertyUpdateFromObject(apObject); } - //----------------------------------------------------------------------- - - ////////////////////////////////////////////////////////////////////////// - // RENDERABLE CONTAINER NODE - ////////////////////////////////////////////////////////////////////////// iRenderableContainerNode::iRenderableContainerNode() { diff --git a/HPL2/sources/scene/RopeEntity.cpp b/HPL2/sources/scene/RopeEntity.cpp index 3a7915ea3..e49334e7e 100644 --- a/HPL2/sources/scene/RopeEntity.cpp +++ b/HPL2/sources/scene/RopeEntity.cpp @@ -26,6 +26,8 @@ #include "graphics/Material.h" #include "graphics/LowLevelGraphics.h" #include "graphics/VertexBuffer.h" +#include +#include #include "resources/Resources.h" #include "resources/MaterialManager.h" @@ -55,51 +57,114 @@ namespace hpl { mfLengthTileAmount = 1; mfLengthTileSize = 1; - mpVtxBuffer = mpLowLevelGraphics->CreateVertexBuffer( eVertexBufferType_Hardware, eVertexBufferDrawType_Tri, eVertexBufferUsageType_Dynamic, - 4 * mlMaxSegments, 6 * mlMaxSegments); - - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Position,eVertexBufferElementFormat_Float,4); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Normal,eVertexBufferElementFormat_Float,3); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Color0,eVertexBufferElementFormat_Float,4); - mpVtxBuffer->CreateElementArray(eVertexBufferElement_Texture0,eVertexBufferElementFormat_Float,3); - - for(int i=0; iAddVertexVec3f(eVertexBufferElement_Position, 0); - mpVtxBuffer->AddVertexColor(eVertexBufferElement_Color0, mColor); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Texture0, 0); - mpVtxBuffer->AddVertexVec3f(eVertexBufferElement_Normal, cVector3f(0,0,1)); - } - - for(int j=0;j<3;j++) mpVtxBuffer->AddIndex(j + i*4); - for(int j=2;j<5;j++) mpVtxBuffer->AddIndex( (j==4?0:j) + i*4); - } - - mpVtxBuffer->Compile(eVertexCompileFlag_CreateTangents); + { + auto* graphicsAllocator = Interface::Get(); + auto& opaqueSet = graphicsAllocator->resolveSet(GraphicsAllocator::AllocationSet::OpaqueSet); + m_geometry = opaqueSet.allocate(4 * mlMaxSegments, 6 * mlMaxSegments); + + auto& indexStream = m_geometry->indexBuffer(); + auto positionStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_POSITION); + auto normalStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_NORMAL); + auto colorStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_COLOR); + auto textureStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TEXCOORD0); + auto tangentStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TANGENT); + + BufferUpdateDesc indexUpdateDesc = { indexStream.m_handle, + m_geometry->indexOffset() * GeometrySet::IndexBufferStride, + GeometrySet::IndexBufferStride * 6 * mlMaxSegments * NumberOfCopies }; + BufferUpdateDesc positionUpdateDesc = { positionStream->buffer().m_handle, + m_geometry->vertexOffset() * positionStream->stride(), + positionStream->stride() * 4 * mlMaxSegments * NumberOfCopies }; + BufferUpdateDesc normalUpdateDesc = { normalStream->buffer().m_handle, + m_geometry->vertexOffset() * normalStream->stride(), + normalStream->stride() * 4 * mlMaxSegments * NumberOfCopies }; + BufferUpdateDesc colorUpdateDesc = { colorStream->buffer().m_handle, + m_geometry->vertexOffset() * colorStream->stride(), + colorStream->stride() * 4 * mlMaxSegments * NumberOfCopies }; + BufferUpdateDesc textureUpdateDesc = { textureStream->buffer().m_handle, + m_geometry->vertexOffset() * textureStream->stride(), + textureStream->stride() * 4 * mlMaxSegments * NumberOfCopies }; + BufferUpdateDesc tangentUpdateDesc = { tangentStream->buffer().m_handle, + m_geometry->vertexOffset() * tangentStream->stride(), + tangentStream->stride() * 4 * mlMaxSegments * NumberOfCopies }; + + beginUpdateResource(&indexUpdateDesc); + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&normalUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + beginUpdateResource(&textureUpdateDesc); + beginUpdateResource(&tangentUpdateDesc); + + GraphicsBuffer gpuIndexBuffer(indexUpdateDesc); + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuNormalBuffer(normalUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + GraphicsBuffer gpuTextureBuffer(textureUpdateDesc); + GraphicsBuffer gpuTangentBuffer(tangentUpdateDesc); + auto indexView = gpuPositionBuffer.CreateIndexView(); + uint32_t index = 0; + for (int i = 0; i < mlMaxSegments; ++i) { + for (int j = 0; j < 3; j++) { + indexView.Write(index, j + i * 4); + } + for (int j = 2; j < 5; j++) { + indexView.Write(index, (j == 4 ? 0 : j) + i * 4); + } + } + + for(size_t copyIdx = 0; copyIdx < 2; copyIdx++) { + auto positionView = gpuPositionBuffer.CreateStructuredView(positionStream->stride() * copyIdx * mlMaxSegments * 4); + auto normalView = gpuNormalBuffer.CreateStructuredView(normalStream->stride() * copyIdx * mlMaxSegments * 4); + auto colorView = gpuColorBuffer.CreateStructuredView(colorStream->stride() * copyIdx * mlMaxSegments * 4); + auto textureView = gpuTextureBuffer.CreateStructuredView(textureStream->stride() * copyIdx * mlMaxSegments * 4); + auto tangentView = gpuTangentBuffer.CreateStructuredView(tangentStream->stride() * copyIdx * mlMaxSegments * 4); + for(int i=0; i < mlMaxSegments; ++i) + { + for(size_t j = 0; j < 4; j++) { + tangentView.Write((i * 4) + j, float3(0, 0, 1)); + positionView.Write((i * 4) + j, float3(0,0,0)); + normalView.Write((i * 4) + j, float3(0.0f, 0.0f, 1.0f)); + colorView.Write((i * 4) + j, float4(mColor.r, mColor.g, mColor.g, mColor.a)); + textureView.Write((i * 4) + j, float2(0,0)); + } + } + Matrix4 trans = Matrix4::identity(); + hpl::MeshUtility::MikkTSpaceGenerate(4 * mlMaxSegments, 6 * mlMaxSegments, &indexView, &positionView, &textureView, &normalView, &tangentView); + } + + endUpdateResource(&indexUpdateDesc); + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&normalUpdateDesc); + endUpdateResource(&colorUpdateDesc); + endUpdateResource(&textureUpdateDesc); + endUpdateResource(&tangentUpdateDesc); + } mbApplyTransformToBV = false; mlLastUpdateCount = -1; } - //----------------------------------------------------------------------- - - DrawPacket cRopeEntity::ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) { + DrawPacket cRopeEntity::ResolveDrawPacket(const ForgeRenderer::Frame& frame) { + DrawPacket packet; + if(m_numberSegments <= 0) { + return packet; + } - return static_cast(mpVtxBuffer)->resolveGeometryBinding(frame.m_currentFrame, elements); + DrawPacket::GeometrySetBinding binding{}; + packet.m_type = DrawPacket::DrawGeometryset; + binding.m_subAllocation = m_geometry.get(); + binding.m_indexOffset = 0; + binding.m_set = GraphicsAllocator::AllocationSet::OpaqueSet; + binding.m_numIndices = 6 * m_numberSegments; + binding.m_vertexOffset = (m_activeCopy * mlMaxSegments * 4); + packet.m_unified = binding; + return packet; } cRopeEntity::~cRopeEntity() { if(mpMaterial) mpMaterialManager->Destroy(mpMaterial); - if(mpVtxBuffer) hplDelete(mpVtxBuffer); } @@ -118,36 +183,14 @@ namespace hpl { mColor = aColor; - float *pColors = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Color0); - - cColor finalColor = mColor; - if(mbMultiplyAlphaWithColor) - { - finalColor.r = finalColor.r * mColor.a; - finalColor.g = finalColor.g * mColor.a; - finalColor.b = finalColor.b * mColor.a; - } - - for(int i=0; iUpdateData(eVertexElementFlag_Color0,false); } - //----------------------------------------------------------------------- void cRopeEntity::SetMaterial(cMaterial * apMaterial) { mpMaterial = apMaterial; } - //----------------------------------------------------------------------- cBoundingVolume* cRopeEntity::GetBoundingVolume() { @@ -179,25 +222,6 @@ namespace hpl { } - //----------------------------------------------------------------------- - - static inline void SetVec3(float *apPos, const cVector3f &aPos) - { - apPos[0] = aPos.x; - apPos[1] = aPos.y; - apPos[2] = aPos.z; - } - - static inline void SetVec4(float *apPos, const cVector3f &aPos) - { - apPos[0] = aPos.x; - apPos[1] = aPos.y; - apPos[2] = aPos.z; - apPos[3] = 1; - } - - //----------------------------------------------------------------------- - static cVector2f gvPosAdd[4] = { //cVector2f (1,1), cVector2f (1,0), cVector2f (-1,0), cVector2f (-1,1) cVector2f (1,0), cVector2f (-1,0), cVector2f (-1,1), cVector2f (1,1) @@ -205,18 +229,52 @@ namespace hpl { bool cRopeEntity::UpdateGraphicsForViewport(cFrustum *apFrustum,float afFrameTime) { - float *pPosArray = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Position); - float *pUvArray = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Texture0); - float *pNrmArray = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Normal); - float *pTanArray = mpVtxBuffer->GetFloatArray(eVertexBufferElement_Texture1Tangent); + m_activeCopy = (m_activeCopy + 1) % NumberOfCopies; + cColor finalColor = mColor; + if(mbMultiplyAlphaWithColor) + { + finalColor.r = finalColor.r * mColor.a; + finalColor.g = finalColor.g * mColor.a; + finalColor.b = finalColor.b * mColor.a; + } + + + auto positionStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_POSITION); + auto colorStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_COLOR); + auto textureStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TEXCOORD0); + auto normalStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_NORMAL); + auto tangentStream = m_geometry->getStreamBySemantic(ShaderSemantic::SEMANTIC_TANGENT); + + BufferUpdateDesc positionUpdateDesc = { positionStream->buffer().m_handle, positionStream->stride() * ((mlMaxSegments * 4 * m_activeCopy) + m_geometry->vertexOffset()), positionStream->stride() * mlMaxSegments * 4 }; + BufferUpdateDesc textureUpdateDesc = { textureStream->buffer().m_handle, textureStream->stride() * ((mlMaxSegments * 4 * m_activeCopy)+ m_geometry->vertexOffset()), textureStream->stride() * mlMaxSegments * 4 }; + BufferUpdateDesc colorUpdateDesc = { colorStream->buffer().m_handle, colorStream->stride() * ((mlMaxSegments * 4 * m_activeCopy)+ m_geometry->vertexOffset()), colorStream->stride() * mlMaxSegments * 4 }; + BufferUpdateDesc normalUpdateDesc = { normalStream->buffer().m_handle, normalStream->stride() * ((mlMaxSegments * 4 * m_activeCopy)+ m_geometry->vertexOffset()), normalStream->stride() * mlMaxSegments * 4 }; + BufferUpdateDesc tangentUpdateDesc = { tangentStream->buffer().m_handle, tangentStream->stride() * ((mlMaxSegments * 4 * m_activeCopy)+ m_geometry->vertexOffset()), tangentStream->stride() * mlMaxSegments * 4 }; + + beginUpdateResource(&positionUpdateDesc); + beginUpdateResource(&textureUpdateDesc); + beginUpdateResource(&colorUpdateDesc); + beginUpdateResource(&normalUpdateDesc); + beginUpdateResource(&tangentUpdateDesc); + + GraphicsBuffer gpuPositionBuffer(positionUpdateDesc); + GraphicsBuffer gpuNormalBuffer(normalUpdateDesc); + GraphicsBuffer gpuColorBuffer(colorUpdateDesc); + GraphicsBuffer gpuTextureBuffer(textureUpdateDesc); + GraphicsBuffer gpuTangentBuffer(tangentUpdateDesc); + auto positionView = gpuPositionBuffer.CreateStructuredView(); + auto normalView = gpuNormalBuffer.CreateStructuredView(); + auto colorView = gpuColorBuffer.CreateStructuredView(); + auto textureView = gpuTextureBuffer.CreateStructuredView(); + auto tangentView = gpuTangentBuffer.CreateStructuredView(); float fSegmentLength = mpRope->GetSegmentLength(); - cVector3f vTexCoords[4] = { - cVector3f(1,1,0), //Bottom left - cVector3f(0,1,0), //Bottom right - cVector3f(0,0,0), //Top left - cVector3f(1,0,0) //Top right + cVector2f vTexCoords[4] = { + cVector2f(1,1), //Bottom left + cVector2f(0,1), //Bottom right + cVector2f(0,0), //Top left + cVector2f(1,0) //Top right }; vTexCoords[0].y *= mfLengthTileAmount; @@ -225,7 +283,9 @@ namespace hpl { cVerletParticleIterator it = mpRope->GetParticleIterator(); int lCount=0; cVector3f vPrevPos; - while(it.HasNext()) + + size_t segmentIndex = 0; + while(it.HasNext()) { if(lCount >= mlMaxSegments) break; ++lCount; @@ -237,7 +297,6 @@ namespace hpl { continue; } - ///////////////////////// //Calculate properties cVector3f vPos = pPart->GetSmoothPosition(); cVector3f vDelta = vPos - vPrevPos; @@ -246,75 +305,66 @@ namespace hpl { cVector3f vRight = cMath::Vector3Normalize(cMath::Vector3Cross(vUp, apFrustum->GetForward())); cVector3f vFwd = cMath::Vector3Cross(vRight, vUp); - ///////////////////////// //Update position - for(int i=0; i<4; ++i) - SetVec4(&pPosArray[i*4], vPrevPos + vRight * gvPosAdd[i].x*mfRadius + vUp * gvPosAdd[i].y*fLength); + for(int i=0; i<4; ++i) { + positionView.Write(segmentIndex + i, v3ToF3(cMath::ToForgeVec3(vPrevPos + vRight * gvPosAdd[i].x*mfRadius + vUp * gvPosAdd[i].y*fLength))); + //SetVec4(&pPosArray[i*4], vPrevPos + vRight * gvPosAdd[i].x*mfRadius + vUp * gvPosAdd[i].y*fLength); + } - ///////////////////////// //Update uv if(lCount==2 && (fLength < fSegmentLength || fSegmentLength==0)) { - ////////////////// //No segments if(fSegmentLength==0) { float fYAdd = 1 - fLength/ mfLengthTileSize; - - SetVec3(&pUvArray[0*3], vTexCoords[0] - cVector3f(0,fYAdd,0)); - SetVec3(&pUvArray[1*3], vTexCoords[1] - cVector3f(0,fYAdd,0)); - - SetVec3(&pUvArray[2*3], vTexCoords[2]); - SetVec3(&pUvArray[3*3], vTexCoords[3]); + textureView.Write(segmentIndex + 0, v2ToF2(cMath::ToForgeVec2(vTexCoords[0] - cVector2f(0,fYAdd)))); + textureView.Write(segmentIndex + 1, v2ToF2(cMath::ToForgeVec2(vTexCoords[1] - cVector2f(0,fYAdd)))); + textureView.Write(segmentIndex + 2, v2ToF2(cMath::ToForgeVec2(vTexCoords[2]))); + textureView.Write(segmentIndex + 3, v2ToF2(cMath::ToForgeVec2(vTexCoords[3]))); } - ////////////////// //First segment of many else { float fYAdd = (1 - (fLength / fSegmentLength))*mfLengthTileAmount; - SetVec3(&pUvArray[0*3], vTexCoords[0] - cVector3f(0,fYAdd,0) ); - SetVec3(&pUvArray[1*3], vTexCoords[1] - cVector3f(0,fYAdd,0) ); - - SetVec3(&pUvArray[2*3], vTexCoords[2]); - SetVec3(&pUvArray[3*3], vTexCoords[3]); + textureView.Write(segmentIndex + 0, v2ToF2(cMath::ToForgeVec2(vTexCoords[0] - cVector2f(0,fYAdd)))); + textureView.Write(segmentIndex + 1, v2ToF2(cMath::ToForgeVec2(vTexCoords[1] - cVector2f(0,fYAdd)))); + textureView.Write(segmentIndex + 2, v2ToF2(cMath::ToForgeVec2(vTexCoords[2]))); + textureView.Write(segmentIndex + 3, v2ToF2(cMath::ToForgeVec2(vTexCoords[3]))); } } else { - for(int i=0; i<4; ++i) - SetVec3(&pUvArray[i*3], vTexCoords[i]); + for(int i=0; i<4; ++i) { + textureView.Write(segmentIndex + i, v2ToF2(cMath::ToForgeVec2(vTexCoords[i]))); + } } - ///////////////////////// //Update Normal and Tangent for(int i=0; i<4; ++i) { - SetVec3(&pNrmArray[i*3], vFwd); - SetVec4(&pTanArray[i*4], vRight); + normalView.Write(i + segmentIndex, v3ToF3(cMath::ToForgeVec3(vFwd))); + tangentView.Write(i + segmentIndex, v3ToF3(cMath::ToForgeVec3(vRight))); + colorView.Write(i + segmentIndex,float4(finalColor.r,finalColor.g,finalColor.b,finalColor.a)); } - ///////////////////////// - //Update pointers - pPosArray += 4 * 4; - pUvArray += 3 * 4; - pNrmArray += 3 * 4; - pTanArray += 4 * 4; + segmentIndex++; - ///////////////////////// //Update misc vPrevPos = vPos; } - mpVtxBuffer->SetElementNum((lCount-1) * 6); - - mpVtxBuffer->UpdateData(eVertexElementFlag_Position | eVertexElementFlag_Texture0 | eVertexElementFlag_Texture1 | eVertexElementFlag_Normal, false); + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&textureUpdateDesc); + endUpdateResource(&colorUpdateDesc); + endUpdateResource(&normalUpdateDesc); + endUpdateResource(&tangentUpdateDesc); + m_numberSegments = lCount - 1; return true; } - //----------------------------------------------------------------------- - cMatrixf* cRopeEntity::GetModelMatrix(cFrustum *apFrustum) { if(apFrustum==NULL)return &GetWorldMatrix(); @@ -322,15 +372,11 @@ namespace hpl { return NULL; } - //----------------------------------------------------------------------- - int cRopeEntity::GetMatrixUpdateCount() { return GetTransformUpdateCount(); } - //----------------------------------------------------------------------- - bool cRopeEntity::IsVisible() { if(mColor.r <= 0 && mColor.g <= 0 && mColor.b <= 0) return false; @@ -338,16 +384,4 @@ namespace hpl { return mbIsVisible; } - - //----------------------------------------------------------------------- - - - - ////////////////////////////////////////////////////////////////////////// - // PRIVATE METHODS - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------- - - //----------------------------------------------------------------------- } diff --git a/HPL2/sources/scene/Scene.cpp b/HPL2/sources/scene/Scene.cpp index dda25557b..3c5c009d2 100644 --- a/HPL2/sources/scene/Scene.cpp +++ b/HPL2/sources/scene/Scene.cpp @@ -19,6 +19,7 @@ #include "scene/Scene.h" +#include "Common_3/Graphics/Interfaces/IGraphics.h" #include "engine/IUpdateEventLoop.h" #include "engine/Interface.h" #include "graphics/RenderTarget.h" @@ -100,7 +101,6 @@ namespace hpl { pViewport->SetCamera(apCamera); pViewport->SetWorld(apWorld); - // pViewport->SetSize(-1); pViewport->SetRenderer(mpGraphics->GetRenderer(eRenderer_Main)); if (abPushFront) { @@ -172,7 +172,7 @@ namespace hpl { } } - void cScene::Render(const ForgeRenderer::Frame& frame, float afFrameTime, tFlag alFlags) { + void cScene::Render(ForgeRenderer::Frame& frame, float afFrameTime, tFlag alFlags) { // Increase the frame count (do this at top, so render count is valid until this Render is called again!) iRenderer::IncRenderFrameCount(); @@ -193,10 +193,13 @@ namespace hpl { iRenderer* pRenderer = pViewPort->GetRenderer(); cCamera* pCamera = pViewPort->GetCamera(); cFrustum* pFrustum = pCamera ? pCamera->GetFrustum() : NULL; - ////////////////////////////////////////////// + if(pViewPort) { + pViewPort->SignalBeforeDraw(&frame); + } + // Render world and call callbacks if (alFlags & tSceneRenderFlag_World) { - pViewPort->RunViewportCallbackMessage(eViewportMessage_OnPreWorldDraw); + //pViewPort->RunViewportCallbackMessage(eViewportMessage_OnPreWorldDraw); if (pPostEffectComposite && (alFlags & tSceneRenderFlag_PostEffects)) { bPostEffects = pPostEffectComposite->HasActiveEffects(); @@ -211,8 +214,7 @@ namespace hpl { afFrameTime, pFrustum, pViewPort->GetWorld(), - pViewPort->GetRenderSettings(), - bPostEffects); + pViewPort->GetRenderSettings()); STOP_TIMING(RenderWorld) } else { // If no renderer sets up viewport do that by our selves. @@ -222,7 +224,7 @@ namespace hpl { // pRenderTarget->mvSize); // umm need to workout how this framebuffer is used ... } - pViewPort->RunViewportCallbackMessage(eViewportMessage_OnPostWorldDraw); + //pViewPort->RunViewportCallbackMessage(eViewportMessage_OnPostWorldDraw); ////////////////////////////////////////////// // Render 3D GuiSets @@ -234,45 +236,49 @@ namespace hpl { auto forgeRenderer = Interface::Get(); - ////////////////////////////////////////////// // Render Post effects auto outputImage = pRenderer->GetOutputImage(frame.m_frameIndex, *pViewPort); - if(outputImage.IsValid()) { - const bool isViewportTarget = pViewPort->Target().IsValid(); - auto& target = isViewportTarget ? pViewPort->Target().m_handle : frame.m_finalRenderTarget; + SharedRenderTarget& viewportTarget = pViewPort->Target(frame); + const bool isViewportTarget = viewportTarget.IsValid(); + auto target = isViewportTarget ? viewportTarget.m_handle : frame.finalTarget(); + if (isViewportTarget) { + cmdBindRenderTargets(frame.m_cmd, NULL); + std::array rtBarriers = { + RenderTargetBarrier{ target, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, + }; + cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); + } if (bPostEffects) { START_TIMING(RenderPostEffects) - if (isViewportTarget) { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); - std::array rtBarriers = { - RenderTargetBarrier{ target, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, - }; - cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); - } pPostEffectComposite->Draw( frame, *pViewPort, afFrameTime, outputImage.m_handle->pTexture, target); - if (isViewportTarget) { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); - std::array rtBarriers = { - RenderTargetBarrier{ target, RESOURCE_STATE_RENDER_TARGET ,RESOURCE_STATE_SHADER_RESOURCE}, - }; - cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); - } - STOP_TIMING(RenderPostEffects) - } else { + STOP_TIMING(RenderPostEffects) + } else { auto size = pViewPort->GetSize(); cRect2l rect = cRect2l(0, 0, size.x, size.y); - forgeRenderer->cmdCopyTexture(frame.m_cmd, outputImage.m_handle->pTexture, - target); - } + forgeRenderer->cmdCopyTexture(frame.m_cmd, outputImage.m_handle->pTexture, target); + } + if (isViewportTarget) { + cmdBindRenderTargets(frame.m_cmd, NULL); + std::array rtBarriers = { + RenderTargetBarrier{ target, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, + }; + cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); + } } - + //if(outputImage.IsValid()) { + // RunViewportCallbackMessagecmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + // std::array rtBarriers = { + // RenderTargetBarrier{ outputImage.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, + // }; + // cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); + //} ////////////////////////////////////////////// // Render Screen GUI if (alFlags & tSceneRenderFlag_Gui) { diff --git a/HPL2/sources/scene/SubMeshEntity.cpp b/HPL2/sources/scene/SubMeshEntity.cpp index 44c7b0484..78e3e3550 100644 --- a/HPL2/sources/scene/SubMeshEntity.cpp +++ b/HPL2/sources/scene/SubMeshEntity.cpp @@ -21,7 +21,6 @@ #include "Common_3/Resources/ResourceLoader/Interfaces/IResourceLoader.h" #include "FixPreprocessor.h" - #include "graphics/ForgeRenderer.h" #include "graphics/GraphicsAllocator.h" #include "graphics/GraphicsBuffer.h" @@ -79,7 +78,7 @@ namespace hpl { auto gpuStream = m_geometry->getStreamBySemantic(localStream.m_semantic); ASSERT(gpuStream != m_geometry->vertexStreams().end()); - BufferUpdateDesc updateDesc = { gpuStream->buffer().m_handle, gpuStream->stride() * m_geometry->vertextOffset(), gpuStream->stride() * reservedVerticies}; + BufferUpdateDesc updateDesc = { gpuStream->buffer().m_handle, gpuStream->stride() * m_geometry->vertexOffset(), gpuStream->stride() * reservedVerticies}; beginUpdateResource(&updateDesc); GraphicsBuffer gpuBuffer(updateDesc); @@ -95,7 +94,7 @@ namespace hpl { dest.WriteRaw(((i + m_numberVertices) * gpuStream->stride()), sp); } } - endUpdateResource(&updateDesc, nullptr); + endUpdateResource(&updateDesc); } { BufferUpdateDesc updateDesc = { m_geometry->indexBuffer().m_handle, m_geometry->indexOffset() * GeometrySet::IndexBufferStride, GeometrySet::IndexBufferStride * m_numberIndecies}; @@ -106,7 +105,7 @@ namespace hpl { for(size_t i = 0; i < m_numberIndecies; i++) { dest.Write(i, src.Get(i)); } - endUpdateResource(&updateDesc, nullptr); + endUpdateResource(&updateDesc); } } @@ -183,9 +182,9 @@ namespace hpl { targetTangentIt != m_geometry->vertexStreams().end() ); - BufferUpdateDesc positionUpdateDesc = { targetPositionIt->buffer().m_handle, (m_geometry->vertextOffset() * targetPositionIt->stride()) + m_activeCopy * (targetPositionIt->stride() * m_numberVertices), targetPositionIt->stride() * m_numberVertices}; - BufferUpdateDesc tangentUpdateDesc = { targetTangentIt->buffer().m_handle, (m_geometry->vertextOffset() * targetTangentIt->stride()) + m_activeCopy * (targetTangentIt->stride() * m_numberVertices), targetTangentIt->stride() * m_numberVertices}; - BufferUpdateDesc normalUpdateDesc = { targetNormalIt->buffer().m_handle, (m_geometry->vertextOffset() * targetNormalIt->stride()) + m_activeCopy * (targetNormalIt->stride() * m_numberVertices), targetNormalIt->stride() * m_numberVertices}; + BufferUpdateDesc positionUpdateDesc = { targetPositionIt->buffer().m_handle, (m_geometry->vertexOffset() * targetPositionIt->stride()) + (m_activeCopy * targetPositionIt->stride() * m_numberVertices), targetPositionIt->stride() * m_numberVertices}; + BufferUpdateDesc tangentUpdateDesc = { targetTangentIt->buffer().m_handle, (m_geometry->vertexOffset() * targetTangentIt->stride()) + (m_activeCopy * targetTangentIt->stride() * m_numberVertices), targetTangentIt->stride() * m_numberVertices}; + BufferUpdateDesc normalUpdateDesc = { targetNormalIt->buffer().m_handle, (m_geometry->vertexOffset() * targetNormalIt->stride()) + (m_activeCopy * targetNormalIt->stride() * m_numberVertices), targetNormalIt->stride() * m_numberVertices}; beginUpdateResource(&positionUpdateDesc); beginUpdateResource(&tangentUpdateDesc); beginUpdateResource(&normalUpdateDesc); @@ -222,15 +221,15 @@ namespace hpl { targetTangentView.Write(i, accmulatedTangent); } - endUpdateResource(&positionUpdateDesc, nullptr); - endUpdateResource(&tangentUpdateDesc, nullptr); - endUpdateResource(&normalUpdateDesc, nullptr); + endUpdateResource(&positionUpdateDesc); + endUpdateResource(&tangentUpdateDesc); + endUpdateResource(&normalUpdateDesc); } } - DrawPacket cSubMeshEntity::ResolveDrawPacket(const ForgeRenderer::Frame& frame,std::span elements) { + DrawPacket cSubMeshEntity::ResolveDrawPacket(const ForgeRenderer::Frame& frame) { DrawPacket packet; if(m_numberIndecies == 0) { return packet; @@ -238,8 +237,6 @@ namespace hpl { DrawPacket::GeometrySetBinding binding{}; packet.m_type = DrawPacket::DrawGeometryset; - std::copy(elements.begin(), elements.end(), binding.m_elements); - binding.m_numStreams = elements.size(); binding.m_subAllocation = m_geometry.get(); binding.m_indexOffset = 0; binding.m_set = GraphicsAllocator::AllocationSet::OpaqueSet; diff --git a/HPL2/sources/scene/Viewport.cpp b/HPL2/sources/scene/Viewport.cpp index 6d7c69a7f..88ecb29c0 100644 --- a/HPL2/sources/scene/Viewport.cpp +++ b/HPL2/sources/scene/Viewport.cpp @@ -120,40 +120,42 @@ namespace hpl { window.ConnectWindowEventHandler(m_windowEventHandler); SetSize(window.GetWindowSize()); } + void cViewport::InitializeTarget(Renderer* renderer, RenderTargetDesc renderTargetDesc) { + for(size_t i = 0; i < m_targets.size(); i++) { + m_targets[i].Load(renderer, [&](RenderTarget** target) { + addRenderTarget(renderer, &renderTargetDesc, target); + return true; + }); + auto texture = SharedTexture(); + texture.SetRenderTarget(m_targets[i]); + m_images[i] = std::make_shared(); + m_images[i]->SetForgeTexture(std::move(texture)); + } - void cViewport::AddViewportCallback(iViewportCallback* apCallback) { - mlstCallbacks.push_back(apCallback); - } - - void cViewport::RemoveViewportCallback(iViewportCallback* apCallback) { - STLFindAndRemove(mlstCallbacks, apCallback); } - - void cViewport::RunViewportCallbackMessage(eViewportMessage aMessage) { - tViewportCallbackListIt it = mlstCallbacks.begin(); - for (; it != mlstCallbacks.begin(); ++it) { - iViewportCallback* pCallback = *it; - - pCallback->RunMessage(aMessage); + void cViewport::InvalidateTarget() { + for(auto& target: m_targets) { + target.TryFree(); + } + for(auto& image: m_images) { + image = nullptr; } - } - void cViewport::SetTarget(SharedRenderTarget& target) { - m_target = target; - auto texture = SharedTexture(); - texture.SetRenderTarget(m_target); - m_image = std::make_shared(); - m_image->SetForgeTexture(std::move(texture)); - //m_dirtyViewport = true; } - void cViewport::SetTarget(SharedRenderTarget&& target) { - m_target = std::move(target); - auto texture = SharedTexture(); - texture.SetRenderTarget(m_target); - m_image = std::make_shared(); - m_image->SetForgeTexture(std::move(texture)); - //m_dirtyViewport = true; - } + // void cViewport::SetTarget(SharedRenderTarget& target) { + // m_targets = target; + // auto texture = SharedTexture(); + // texture.SetRenderTarget(m_target); + // m_images = std::make_shared(); + // m_images->SetForgeTexture(std::move(texture)); + // } + + // void cViewport::SetTarget(SharedRenderTarget&& target) { + // m_targets = std::move(target); + // auto texture = SharedTexture(); + // texture.SetRenderTarget(m_target); + // m_images = std::make_shared(); + // } } // namespace hpl diff --git a/HPL2/sources/system/Bootstrap.cpp b/HPL2/sources/system/Bootstrap.cpp index b5c07ea08..8594d855c 100644 --- a/HPL2/sources/system/Bootstrap.cpp +++ b/HPL2/sources/system/Bootstrap.cpp @@ -3,6 +3,7 @@ #include #include +#include "Common_3/Utilities/Interfaces/IFileSystem.h" #include "engine/IUpdateEventLoop.h" #include "engine/Interface.h" #include "graphics/GraphicsAllocator.h" @@ -49,9 +50,19 @@ namespace hpl { return; } + FileSystemInitDesc fsDesc = {}; + fsDesc.pAppName = "HPL2"; + + if (!initFileSystem(&fsDesc)) { + LOGF(eERROR, "Filesystem failed to initialize."); + } + + initLog("HPL2", DEFAULT_LOG_LEVEL); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_SHADER_BINARIES, "./CompiledShaders"); - fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_SHADER_SOURCES, "./Shaders"); + fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_LOG, "./log"); + fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_GPU_CONFIG, "./"); + //fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_SHADER_SOURCES, "./Shaders"); Interface::Register(&m_updateEventLoop); @@ -77,7 +88,6 @@ namespace hpl { // graphics allocator m_graphicsAlloc = std::make_unique(&m_renderer); - m_renderer.InitializeResource(); gui::InitializeGui(m_renderer); // this is safe because the render target is scheduled on the api thread diff --git a/amnesia/CMakeLists.txt b/amnesia/CMakeLists.txt index a81227770..fb3c2e114 100644 --- a/amnesia/CMakeLists.txt +++ b/amnesia/CMakeLists.txt @@ -74,49 +74,12 @@ ELSEIF(LINUX) -DLINUX ) ENDIF() - +hpl_set_output_dir(Amnesia "") add_custom_target(GameRelease DEPENDS Amnesia) set(AMNESIA_EXECUTABLE_OUTPUT_PATH ${INSTALL_OUTPUT_PATH}/Amnesia) install(DIRECTORY DESTINATION ${AMNESIA_EXECUTABLE_OUTPUT_PATH}) -if(WITH_TOOLS) - add_custom_command (TARGET Amnesia POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ $ - DEPENDS MapViewer - ) - add_custom_command (TARGET Amnesia POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ $ - DEPENDS ModelViewer - ) - add_custom_command (TARGET Amnesia POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ $ - DEPENDS MshConverter - ) - add_custom_command (TARGET Amnesia POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ $ - DEPENDS LevelEditor - ) - add_custom_command (TARGET Amnesia POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ $ - DEPENDS ParticleEditor - ) - add_custom_command (TARGET Amnesia POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ $ - DEPENDS ModelEditor - ) - add_custom_command ( TARGET Amnesia POST_BUILD - COMMAND ${CMAKE_COMMAND} ARGS -E copy_directory - ${_HPL_TOOL_RESOURCE_PATH_} $ - ) -endif() - if(WIN32) add_custom_command ( TARGET Amnesia POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different @@ -144,6 +107,10 @@ endif() ## ARGS -E copy_directory "${_HPL2_COMPILEDSHADER_}" "$/CompiledShaders" ##) copy_shader_to_target_dir(Amnesia) +add_custom_command ( TARGET Amnesia POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${CMAKE_CURRENT_SOURCE_DIR}/gpu.data $ +) target_compile_definitions(Amnesia PUBLIC AMNESIA_TDD_VERSION="${AMNESIA_TDD_VERSION}") target_compile_definitions(Amnesia PUBLIC AMNESIA_TDD_TAG="${AMNESIA_TDD_TAG}") diff --git a/amnesia/game/LuxEffectRenderer.cpp b/amnesia/game/LuxEffectRenderer.cpp index 961506285..69cdae3a5 100644 --- a/amnesia/game/LuxEffectRenderer.cpp +++ b/amnesia/game/LuxEffectRenderer.cpp @@ -212,11 +212,9 @@ cLuxEffectRenderer::cLuxEffectRenderer() depthStateDesc.mDepthFunc = CMP_LEQUAL; { VertexLayout vertexLayout = {}; - #ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 2; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); - #endif vertexLayout.mAttribCount = 2; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -247,11 +245,7 @@ cLuxEffectRenderer::cLuxEffectRenderer() depthStateOutlineDesc.mStencilReadMask = 0xff; BlendStateDesc blendStateDesc{}; - #ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = ALL; - #else blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_ALL; - #endif blendStateDesc.mSrcFactors[0] = BC_ONE; blendStateDesc.mDstFactors[0] = BC_ZERO; @@ -281,11 +275,9 @@ cLuxEffectRenderer::cLuxEffectRenderer() } { VertexLayout vertexLayout = {}; - #ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 2; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); - #endif vertexLayout.mAttribCount = 2; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -333,12 +325,10 @@ cLuxEffectRenderer::cLuxEffectRenderer() } { VertexLayout vertexLayout = {}; - #ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 3; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); - #endif vertexLayout.mAttribCount = 3; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -363,11 +353,7 @@ cLuxEffectRenderer::cLuxEffectRenderer() blendStateDesc.mSrcAlphaFactors[0] = BC_ONE; blendStateDesc.mDstAlphaFactors[0] = BC_ONE; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; - #ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; - #else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; - #endif + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -391,12 +377,10 @@ cLuxEffectRenderer::cLuxEffectRenderer() } { VertexLayout vertexLayout = {}; - #ifndef USE_THE_FORGE_LEGACY vertexLayout.mBindingCount = 3; vertexLayout.mBindings[0].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float3); vertexLayout.mBindings[1].mStride = sizeof(float2); - #endif vertexLayout.mAttribCount = 3; vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION; vertexLayout.mAttribs[0].mFormat = TinyImageFormat_R32G32B32_SFLOAT; @@ -421,11 +405,7 @@ cLuxEffectRenderer::cLuxEffectRenderer() blendStateDesc.mSrcAlphaFactors[0] = BC_ONE; blendStateDesc.mDstAlphaFactors[0] = BC_ONE; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; - #ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; - #else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; - #endif + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -484,11 +464,7 @@ cLuxEffectRenderer::cLuxEffectRenderer() blendStateDesc.mSrcAlphaFactors[0] = BC_ONE; blendStateDesc.mDstAlphaFactors[0] = BC_ONE; blendStateDesc.mBlendAlphaModes[0] = BM_ADD; - #ifdef USE_THE_FORGE_LEGACY - blendStateDesc.mMasks[0] = RED | GREEN | BLUE; - #else - blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; - #endif + blendStateDesc.mColorWriteMasks[0] = ColorMask::COLOR_MASK_RED | ColorMask::COLOR_MASK_GREEN | ColorMask::COLOR_MASK_BLUE; blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_0; blendStateDesc.mIndependentBlend = false; @@ -629,6 +605,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp cRendererDeferred* pRendererDeferred = static_cast(pGraphics->GetRenderer(eRenderer_Main)); auto sharedData = pRendererDeferred->GetSharedData(*input.m_viewport); auto& frame = input.m_frame; + cRendererDeferred::GBuffer& currentGBuffer = sharedData->m_gBuffer[input.m_frame->m_frameIndex]; if(!currentGBuffer.m_depthBuffer.IsValid() || !currentGBuffer.m_outputBuffer.IsValid()) { @@ -643,13 +620,20 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp cmdBeginDebugMarker(input.m_frame->m_cmd, 0, 0, 0, "DDS Flashing"); { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - loadActions.mLoadActionStencil = LOAD_ACTION_DONTCARE; - loadActions.mClearDepth = {.depth = 1.0f, .stencil = 0}; + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + // loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + // loadActions.mLoadActionStencil = LOAD_ACTION_DONTCARE; + // loadActions.mClearDepth = {.depth = 1.0f, .stencil = 0}; + // cmdBindRenderTargets(input.m_frame->m_cmd, 1, &sharedData->m_outputBuffer[frame->m_frameIndex].m_handle, sharedData->m_depthBuffer[frame->m_frameIndex].m_handle, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mDepthStencil = {.pDepthStencil = currentGBuffer.m_depthBuffer.m_handle, .mLoadAction = LOAD_ACTION_LOAD, .mClearValue = {.depth = 1.0f, .stencil = 0}}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { currentGBuffer.m_outputBuffer.m_handle, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(input.m_frame->m_cmd, &bindRenderTargets); + - cmdBindRenderTargets(input.m_frame->m_cmd, 1, ¤tGBuffer.m_outputBuffer.m_handle, currentGBuffer.m_depthBuffer.m_handle, &loadActions, NULL, NULL, -1, -1); cmdSetViewport(input.m_frame->m_cmd, 0.0f, 0.0f, (float)sharedData->m_size.x, (float)sharedData->m_size.y, 0.0f, 1.0f); cmdSetScissor(input.m_frame->m_cmd, 0, 0, sharedData->m_size.x, sharedData->m_size.y); } @@ -658,7 +642,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp for(auto& flashObject: mvFlashObjects) { auto* pObject = flashObject.mpObject; std::array targets = { eVertexBufferElement_Position, eVertexBufferElement_Normal, eVertexBufferElement_Texture0 }; - DrawPacket packet = pObject->ResolveDrawPacket(*frame, targets); + DrawPacket packet = pObject->ResolveDrawPacket(*frame); if (!pObject->CollidesWithFrustum(input.m_frustum) && packet.m_type == DrawPacket::Unknown) { continue; @@ -666,11 +650,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp uint32_t requestSize = round_up(sizeof(LuxEffectObjectUniform::FlashUniform), 256); - #ifdef USE_THE_FORGE_LEGACY - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(m_uniformBuffer, requestSize); - #else - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&m_uniformBuffer, requestSize); - #endif + GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&m_uniformBuffer, requestSize); cMatrixf worldMatrix = pObject->GetModelMatrixPtr() ? *pObject->GetModelMatrixPtr() : cMatrixf::Identity; const cMatrixf modelViewMat = cMath::MatrixMul(mainFrustumView, worldMatrix); @@ -693,10 +673,10 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp BufferUpdateDesc updateDesc = { uniformBlockOffset.pBuffer, uniformBlockOffset.mOffset }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = uniform; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); cmdBindDescriptorSet(input.m_frame->m_cmd, objectIndex++, m_perObjectDescriptorSet[frame->m_frameIndex]); - DrawPacket::cmdBindBuffers(frame->m_cmd, frame->m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(frame->m_cmd, frame->m_resourcePool, &packet , targets); for(size_t i = 0; i < 2; i++) { cmdDrawIndexed(input.m_frame->m_cmd, packet.numberOfIndecies(), 0, 0); } @@ -714,14 +694,10 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp continue; } std::array targets = { eVertexBufferElement_Position, eVertexBufferElement_Normal, eVertexBufferElement_Texture0 }; - DrawPacket packet = pObject->ResolveDrawPacket(*frame, targets); + DrawPacket packet = pObject->ResolveDrawPacket(*frame); uint32_t requestSize = round_up(sizeof(LuxEffectObjectUniform::FlashUniform), 256); - #ifdef USE_THE_FORGE_LEGACY - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(m_uniformBuffer, requestSize); - #else - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&m_uniformBuffer, requestSize); - #endif + GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&m_uniformBuffer, requestSize); cMatrixf worldMatrix = pObject->GetModelMatrixPtr() ? *pObject->GetModelMatrixPtr() : cMatrixf::Identity; const cMatrixf modelViewMat = cMath::MatrixMul(mainFrustumView, worldMatrix); const cMatrixf mvp = cMath::MatrixMul(mainFrustumViewProj, worldMatrix); @@ -743,10 +719,10 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp BufferUpdateDesc updateDesc = { uniformBlockOffset.pBuffer, uniformBlockOffset.mOffset }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = uniform; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); cmdBindDescriptorSet(input.m_frame->m_cmd, objectIndex++, m_perObjectDescriptorSet[frame->m_frameIndex]); - DrawPacket::cmdBindBuffers(frame->m_cmd, frame->m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(frame->m_cmd, frame->m_resourcePool, &packet, targets); cmdDrawIndexed(input.m_frame->m_cmd, packet.numberOfIndecies(), 0, 0); } cmdEndDebugMarker(input.m_frame->m_cmd); @@ -759,12 +735,19 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp } } - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; - loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; - loadActions.mLoadActionStencil = LOAD_ACTION_CLEAR; - loadActions.mClearColorValues[0] = { .r = 0.0f, .g = 0.0f, .b = 0.0f, .a = 0.0f }; - cmdBindRenderTargets(frame->m_cmd, 1, &postEffectData->m_outlineBuffer.m_handle, currentGBuffer.m_depthBuffer.m_handle, &loadActions, NULL, NULL, -1, -1); + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR; + // loadActions.mLoadActionDepth = LOAD_ACTION_LOAD; + // loadActions.mLoadActionStencil = LOAD_ACTION_CLEAR; + // loadActions.mClearColorValues[0] = { .r = 0.0f, .g = 0.0f, .b = 0.0f, .a = 0.0f }; + // cmdBindRenderTargets(frame->m_cmd, 1, &postEffectData->m_outlineBuffer.m_handle, sharedData->m_depthBuffer[frame->m_frameIndex].m_handle, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mDepthStencil = {.pDepthStencil = currentGBuffer.m_depthBuffer.m_handle, .mLoadAction = LOAD_ACTION_LOAD, .mClearValue = {.depth = 1.0f, .stencil = 0}}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = {.pRenderTarget = postEffectData->m_outlineBuffer.m_handle, .mLoadAction = LOAD_ACTION_CLEAR, .mClearValue = {0.0f, 0.0f, 0.0f, 0.0f}}; + cmdBindRenderTargets(frame->m_cmd, &bindRenderTargets ); + cmdBeginDebugMarker(input.m_frame->m_cmd, 0, 0, 0, "DDS Outline Stencil"); cmdBindPipeline(frame->m_cmd, m_outlineStencilPipeline); @@ -778,14 +761,10 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp } auto* imageAlpha = pMaterial->GetImage(eMaterialTexture_Alpha); std::array targets = { eVertexBufferElement_Position, eVertexBufferElement_Texture0 }; - DrawPacket packet = pObject->ResolveDrawPacket(*frame, targets); + DrawPacket packet = pObject->ResolveDrawPacket(*frame); uint32_t requestSize = round_up(sizeof(LuxEffectObjectUniform::OutlineUniform), 256); - #ifdef USE_THE_FORGE_LEGACY - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(m_uniformBuffer, requestSize); - #else - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&m_uniformBuffer, requestSize); - #endif + GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&m_uniformBuffer, requestSize); cMatrixf worldMatrix = pObject->GetModelMatrixPtr() ? *pObject->GetModelMatrixPtr() : cMatrixf::Identity; const cMatrixf modelViewMat = cMath::MatrixMul(mainFrustumView, worldMatrix); @@ -797,7 +776,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp BufferUpdateDesc updateDesc = { uniformBlockOffset.pBuffer, uniformBlockOffset.mOffset }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = uniform; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); folly::small_vector params = {}; DescriptorDataRange range = { (uint32_t)uniformBlockOffset.mOffset, requestSize }; @@ -816,7 +795,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp updateDescriptorSet(frame->m_renderer->Rend(), objectIndex, m_perObjectDescriptorSet[frame->m_frameIndex], params.size(), params.data()); cmdBindDescriptorSet(input.m_frame->m_cmd, objectIndex++, m_perObjectDescriptorSet[frame->m_frameIndex]); - DrawPacket::cmdBindBuffers(input.m_frame->m_cmd, frame->m_resourcePool, &packet); + DrawPacket::cmdBindBuffers(input.m_frame->m_cmd, frame->m_resourcePool, &packet, targets); cmdDrawIndexed(input.m_frame->m_cmd, packet.numberOfIndecies(), 0, 0); } cmdEndDebugMarker(input.m_frame->m_cmd); @@ -829,17 +808,13 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp auto* pMaterial = pObject->GetMaterial(); std::array targets = { eVertexBufferElement_Position, eVertexBufferElement_Texture0 }; - DrawPacket drawPacket = pObject->ResolveDrawPacket(*frame, targets); + DrawPacket drawPacket = pObject->ResolveDrawPacket(*frame); if (!pObject->CollidesWithFrustum(input.m_frustum) || drawPacket.m_type == DrawPacket::Unknown) { continue; } uint32_t requestSize = round_up(sizeof(LuxEffectObjectUniform::OutlineUniform), 256); - #ifdef USE_THE_FORGE_LEGACY - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(m_uniformBuffer, requestSize); - #else - GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&m_uniformBuffer, requestSize); - #endif + GPURingBufferOffset uniformBlockOffset = getGPURingBufferOffset(&m_uniformBuffer, requestSize); cBoundingVolume* pBV = pObject->GetBoundingVolume(); cVector3f vLocalSize = pBV->GetLocalMax() - pBV->GetLocalMin(); @@ -856,7 +831,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp BufferUpdateDesc updateDesc = { uniformBlockOffset.pBuffer, uniformBlockOffset.mOffset }; beginUpdateResource(&updateDesc); (*reinterpret_cast(updateDesc.pMappedData)) = uniform; - endUpdateResource(&updateDesc, NULL); + endUpdateResource(&updateDesc); std::array params = {}; DescriptorDataRange range = { (uint32_t)uniformBlockOffset.mOffset, requestSize }; @@ -868,7 +843,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp updateDescriptorSet(frame->m_renderer->Rend(), objectIndex, m_perObjectDescriptorSet[frame->m_frameIndex], params.size(), params.data()); cmdBindDescriptorSet(input.m_frame->m_cmd, objectIndex++, m_perObjectDescriptorSet[frame->m_frameIndex]); - DrawPacket::cmdBindBuffers(input.m_frame->m_cmd, input.m_frame->m_resourcePool, &drawPacket); + DrawPacket::cmdBindBuffers(input.m_frame->m_cmd, input.m_frame->m_resourcePool, &drawPacket, targets); cmdDrawIndexed(input.m_frame->m_cmd, drawPacket.numberOfIndecies(), 0, 0); } cmdEndDebugMarker(input.m_frame->m_cmd); @@ -878,7 +853,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp auto requestBlur = [&](Texture** input) { ASSERT(input && "Invalid input texture"); { - cmdBindRenderTargets(frame->m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame->m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ postEffectData->m_blurTarget[0].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, RenderTargetBarrier{ postEffectData->m_blurTarget[1].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE}, @@ -886,11 +861,19 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp cmdResourceBarrier(frame->m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; auto& blurTarget = postEffectData->m_blurTarget[0].m_handle; - cmdBindRenderTargets(frame->m_cmd, 1, &blurTarget , NULL, &loadActions, NULL, NULL, -1, -1); + + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + // loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + // cmdBindRenderTargets(frame->m_cmd, 1, &blurTarget , NULL, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { blurTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame->m_cmd, &bindRenderTargets ); + + cmdSetViewport( frame->m_cmd, 0.0f, 0.0f, static_cast(blurTarget->mWidth), static_cast(blurTarget->mHeight), 0.0f, 1.0f); cmdSetScissor(frame->m_cmd, 0, 0, static_cast(blurTarget->mWidth), static_cast(blurTarget->mHeight)); @@ -909,7 +892,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp } { - cmdBindRenderTargets(frame->m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame->m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ postEffectData->m_blurTarget[0].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, @@ -919,12 +902,17 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp cmdResourceBarrier(frame->m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - auto& blurTarget = postEffectData->m_blurTarget[1].m_handle; - cmdBindRenderTargets(frame->m_cmd, 1, &blurTarget, NULL, &loadActions, NULL, NULL, -1, -1); + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + // loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + // cmdBindRenderTargets(frame->m_cmd, 1, &blurTarget, NULL, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { blurTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame->m_cmd, &bindRenderTargets ); + cmdSetViewport( frame->m_cmd, 0.0f, 0.0f, static_cast(blurTarget->mWidth), static_cast(blurTarget->mHeight), 0.0f, 1.0f); cmdSetScissor(frame->m_cmd, 0, 0, static_cast(blurTarget->mWidth), static_cast(blurTarget->mHeight)); @@ -944,7 +932,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp } }; { - cmdBindRenderTargets(frame->m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame->m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{postEffectData->m_outlineBuffer.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE } }; @@ -958,17 +946,23 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp cmdEndDebugMarker(input.m_frame->m_cmd); { - cmdBindRenderTargets(frame->m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame->m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{postEffectData->m_blurTarget[1].m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE } }; cmdResourceBarrier(frame->m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - cmdBindRenderTargets(input.m_frame->m_cmd, 1, ¤tGBuffer.m_outputBuffer.m_handle, NULL, &loadActions, NULL, NULL, -1, -1); + // LoadActionsDesc loadActions = {}; + // loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + // loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + // cmdBindRenderTargets(input.m_frame->m_cmd, 1, ¤tGBuffer.m_outputBuffer.m_handle, NULL, &loadActions, NULL, NULL, -1, -1); + + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { currentGBuffer.m_outputBuffer.m_handle, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(input.m_frame->m_cmd, &bindRenderTargets ); + } { std::array params = {}; @@ -987,7 +981,7 @@ void cLuxEffectRenderer::RenderTrans(cViewport::PostTranslucenceDrawPacket& inp cmdDraw(frame->m_cmd, 3, 0); cmdEndDebugMarker(input.m_frame->m_cmd); { - cmdBindRenderTargets(frame->m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame->m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{postEffectData->m_outlineBuffer.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, RenderTargetBarrier{postEffectData->m_blurTarget[1].m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET } diff --git a/amnesia/game/LuxEffectRenderer.h b/amnesia/game/LuxEffectRenderer.h index 251ef8911..f75b6e17a 100644 --- a/amnesia/game/LuxEffectRenderer.h +++ b/amnesia/game/LuxEffectRenderer.h @@ -118,11 +118,7 @@ class cLuxEffectRenderer : public iLuxUpdateable UniqueViewportData m_boundPostEffectData; // outline effect - #ifdef USE_THE_FORGE_LEGACY - GPURingBuffer* m_uniformBuffer; - #else - GPURingBuffer m_uniformBuffer; - #endif + GPURingBuffer m_uniformBuffer; Sampler* m_diffuseSampler; std::array m_perObjectDescriptorSet; diff --git a/amnesia/game/LuxHelpFuncs.cpp b/amnesia/game/LuxHelpFuncs.cpp index 2d91d74cb..bff1cf6e7 100644 --- a/amnesia/game/LuxHelpFuncs.cpp +++ b/amnesia/game/LuxHelpFuncs.cpp @@ -187,7 +187,7 @@ bool cLuxHelpFuncs::PlayGuiSoundData(const tString& asName,eSoundEntryType aDest void cLuxHelpFuncs::DrawSetToScreen(bool abClearScreen, const cColor& aCol, cGuiSet* apSet) { auto renderer = hpl::Interface::Get(); - auto frame = renderer->GetFrame(); + auto& frame = renderer->GetFrame(); // /////////////////////////// // // Clear screen @@ -281,8 +281,7 @@ float cLuxHelpFuncs::GetStringDuration(const tWString& asStr) void cLuxHelpFuncs::RenderBackgroundScreen(bool abDrawFullHUD) { auto render = hpl::Interface::Get(); - auto frame = render->GetFrame(); - + auto& frame = render->GetFrame(); gpBase->mpMapHandler->GetViewport()->SetVisible(true); gpBase->mpGameHudSet->ClearRenderObjects(); diff --git a/amnesia/game/LuxInventory.cpp b/amnesia/game/LuxInventory.cpp index a47ad84dc..5dfac1d43 100644 --- a/amnesia/game/LuxInventory.cpp +++ b/amnesia/game/LuxInventory.cpp @@ -1631,11 +1631,11 @@ void cLuxInventory::CreateBackground() } { auto* renderer = viewport->GetRenderer(); - auto frame = forgeRenderer->GetFrame(); + auto& frame = forgeRenderer->GetFrame(); auto screenSize = viewport->GetSize(); auto outputRt = renderer->GetOutputImage(frame.m_frameIndex, *viewport); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ m_screenTarget.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, }; @@ -1643,7 +1643,7 @@ void cLuxInventory::CreateBackground() } forgeRenderer->cmdCopyTexture(frame.m_cmd, outputRt.m_handle->pTexture, m_screenTarget.m_handle); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ m_screenTarget.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, RenderTargetBarrier{ m_screenBgTarget.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, @@ -1652,7 +1652,10 @@ void cLuxInventory::CreateBackground() } { - cmdBindRenderTargets(frame.m_cmd, 1, &m_screenBgTarget.m_handle, NULL, NULL, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { m_screenBgTarget.m_handle, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); std::array params = {}; params[0].pName = "sourceInput"; @@ -1668,7 +1671,7 @@ void cLuxInventory::CreateBackground() m_setIndex = (m_setIndex + 1) % cLuxInventory::DescriptorSetSize; } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ m_screenBgTarget.m_handle, RESOURCE_STATE_RENDER_TARGET , RESOURCE_STATE_SHADER_RESOURCE}, }; diff --git a/amnesia/game/LuxJournal.cpp b/amnesia/game/LuxJournal.cpp index 35b21a9ca..ed819b25a 100644 --- a/amnesia/game/LuxJournal.cpp +++ b/amnesia/game/LuxJournal.cpp @@ -1892,7 +1892,7 @@ void cLuxJournal::CreateBackground() auto* viewport = gpBase->mpMapHandler->GetViewport(); auto* renderer = viewport->GetRenderer(); auto* forgeRenderer = Interface::Get(); - auto frame = forgeRenderer->GetFrame(); + auto& frame = forgeRenderer->GetFrame(); auto screenSize = viewport->GetSize(); { iLowLevelGraphics* pLowGfx = mpGraphics->GetLowLevel(); @@ -1947,7 +1947,7 @@ void cLuxJournal::CreateBackground() auto outputRt = renderer->GetOutputImage(frame.m_frameIndex, *viewport); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ m_screenTarget.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, }; @@ -1955,7 +1955,7 @@ void cLuxJournal::CreateBackground() } forgeRenderer->cmdCopyTexture( frame.m_cmd, outputRt.m_handle->pTexture, m_screenTarget.m_handle); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ m_screenTarget.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, RenderTargetBarrier{ m_screenBgTarget.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, @@ -1964,7 +1964,10 @@ void cLuxJournal::CreateBackground() } { - cmdBindRenderTargets(frame.m_cmd, 1, &m_screenBgTarget.m_handle, NULL, NULL, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { m_screenBgTarget.m_handle, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); std::array params = {}; params[0].pName = "sourceInput"; @@ -1980,7 +1983,7 @@ void cLuxJournal::CreateBackground() m_setIndex = (m_setIndex + 1) % cLuxJournal::DescriptorSetSize; } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ m_screenBgTarget.m_handle, RESOURCE_STATE_RENDER_TARGET , RESOURCE_STATE_SHADER_RESOURCE}, }; diff --git a/amnesia/game/LuxMainMenu.cpp b/amnesia/game/LuxMainMenu.cpp index be3ac808d..f972bd871 100644 --- a/amnesia/game/LuxMainMenu.cpp +++ b/amnesia/game/LuxMainMenu.cpp @@ -1346,7 +1346,7 @@ void cLuxMainMenu::CreateBackground() void cLuxMainMenu::UpdateBackground() { auto* forgeRenderer = Interface::Get(); EngineInterface* engine = Interface::Get(); - auto frame = forgeRenderer->GetFrame(); + auto& frame = forgeRenderer->GetFrame(); auto* scene = engine->GetScene(); auto* viewport = gpBase->mpMapHandler->GetViewport(); auto* renderer = viewport->GetRenderer(); @@ -1423,11 +1423,15 @@ void cLuxMainMenu::UpdateBackground() { // third copy umm need to out how to handle this auto requestBlur = [&](Texture* input) { { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //LoadActionsDesc loadActions = {}; + //loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + //loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //cmdBindRenderTargets(frame.m_cmd, 1, &tempBlurTarget.m_handle, NULL, &loadActions, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { tempBlurTarget.m_handle, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); - cmdBindRenderTargets(frame.m_cmd, 1, &tempBlurTarget.m_handle, NULL, &loadActions, NULL, NULL, -1, -1); std::array params = {}; params[0].pName = "sourceInput"; @@ -1447,7 +1451,7 @@ void cLuxMainMenu::UpdateBackground() { m_setIndex = (m_setIndex + 1) % cLuxMainMenu::BlurSetSize; } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ tempBlurTarget.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, RenderTargetBarrier{ m_screenBlurTarget.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, @@ -1455,11 +1459,15 @@ void cLuxMainMenu::UpdateBackground() { cmdResourceBarrier(frame.m_cmd, 0, NULL, 0, NULL, rtBarriers.size(), rtBarriers.data()); } { - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //LoadActionsDesc loadActions = {}; + //loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; + //loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; + //cmdBindRenderTargets(frame.m_cmd, 1, &m_screenBlurTarget.m_handle, NULL, &loadActions, NULL, NULL, -1, -1); - cmdBindRenderTargets(frame.m_cmd, 1, &m_screenBlurTarget.m_handle, NULL, &loadActions, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { m_screenBlurTarget.m_handle, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets); std::array params = {}; params[0].pName = "sourceInput"; @@ -1479,7 +1487,7 @@ void cLuxMainMenu::UpdateBackground() { m_setIndex = (m_setIndex + 1) % cLuxMainMenu::BlurSetSize; } { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ tempBlurTarget.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, RenderTargetBarrier{ m_screenBlurTarget.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, @@ -1489,7 +1497,7 @@ void cLuxMainMenu::UpdateBackground() { }; auto outputRt = renderer->GetOutputImage(frame.m_frameIndex, *viewport); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ m_screenTarget.m_handle, RESOURCE_STATE_SHADER_RESOURCE, RESOURCE_STATE_RENDER_TARGET }, }; @@ -1498,7 +1506,7 @@ void cLuxMainMenu::UpdateBackground() { forgeRenderer->cmdCopyTexture(frame.m_cmd, outputRt.m_handle->pTexture, m_screenTarget.m_handle); { - cmdBindRenderTargets(frame.m_cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1); + cmdBindRenderTargets(frame.m_cmd, NULL); std::array rtBarriers = { RenderTargetBarrier{ m_screenTarget.m_handle, RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_SHADER_RESOURCE }, }; diff --git a/amnesia/game/LuxPostEffects.cpp b/amnesia/game/LuxPostEffects.cpp index a9d35913a..43916babc 100644 --- a/amnesia/game/LuxPostEffects.cpp +++ b/amnesia/game/LuxPostEffects.cpp @@ -136,11 +136,10 @@ void cLuxPostEffect_Insanity::RenderEffect( uint32_t rootConstantIndex = getDescriptorIndexFromName(m_instantyRootSignature, "rootConstant"); cmdBindPushConstants(frame.m_cmd, m_instantyRootSignature, rootConstantIndex, ¶m); - LoadActionsDesc loadActions = {}; - loadActions.mLoadActionsColor[0] = LOAD_ACTION_LOAD; - loadActions.mLoadActionDepth = LOAD_ACTION_DONTCARE; - - cmdBindRenderTargets(frame.m_cmd, 1, &renderTarget, NULL, &loadActions, NULL, NULL, -1, -1); + BindRenderTargetsDesc bindRenderTargets = {}; + bindRenderTargets.mRenderTargetCount = 1; + bindRenderTargets.mRenderTargets[0] = { renderTarget, LOAD_ACTION_LOAD }; + cmdBindRenderTargets(frame.m_cmd, &bindRenderTargets ); std::array params = {}; params[0].pName = "sourceInput"; diff --git a/amnesia/gpu.data b/amnesia/gpu.data new file mode 100644 index 000000000..0e820e3d4 --- /dev/null +++ b/amnesia/gpu.data @@ -0,0 +1,709 @@ +version: 0.2 +#Possible Classfications for Preset: ultra; high; medium; low; verylow; office +#Sources: +#https://technical.city/en/video/rating +#https://raw.githubusercontent.com/GameTechDev/gpudetect/master/IntelGfx.cfg +#https://vulkan.gpuinfo.org/api/v2/getreportlist.php + +BEGIN_DEFAULT_CONFIGURATION; +#if the gpu doesn't exist in the GPU_LIST use this instead +DefaultPresetLevel; Low; +END_DEFAULT_CONFIGURATION; + +BEGIN_VENDOR_LIST; +intel; 0x8086; +amd; 0x1002; +nvidia; 0x10de; +qualcomm; 0x5143; +END_VENDOR_LIST; + +#VendorID ; DeviceID ; Preset ; #Device Details + +BEGIN_GPU_LIST; +#intel +0x8086; 0x0042; verylow; #Intel; Intel(R) HD Graphics - Core i3/i5 + Pentium G9650 Processors +0x8086; 0x0046; verylow; #Intel; Intel(R) HD Graphics - Core i3/i5/i7 Mobile Processors +0x8086; 0x0102; verylow; #Intel; Intel(R) HD Graphics 2000 +0x8086; 0x0106; verylow; #Intel; Intel(R) HD Graphics 2000 +0x8086; 0x010A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0112; verylow; #Intel; Intel(R) HD Graphics 3000 +0x8086; 0x0116; verylow; #Intel; Intel(R) HD Graphics 3000 +0x8086; 0x0122; verylow; #Intel; Intel(R) HD Graphics 3000 +0x8086; 0x0126; verylow; #Intel; Intel(R) HD Graphics 3000 +0x8086; 0x0152; verylow; #Intel; Intel(R) HD Graphics 2500 +0x8086; 0x0156; verylow; #Intel; Intel(R) HD Graphics 2500 +0x8086; 0x015A; verylow; #Intel; Intel(R) HD Graphics 2500 +0x8086; 0x0162; verylow; #Intel; Intel(R) HD Graphics 4000 +0x8086; 0x0166; verylow; #Intel; Intel(R) HD Graphics 4000 +0x8086; 0x016A; verylow; #Intel; Intel(R) HD Graphics 4000 +0x8086; 0x0402; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0406; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x040A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x040B; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x040E; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0412; verylow; #Intel; Intel(R) HD Graphics 4600 +0x8086; 0x0416; verylow; #Intel; Intel(R) HD Graphics 4600 +0x8086; 0x041A; verylow; #Intel; Intel(R) HD Graphics P4600/P4700 +0x8086; 0x041B; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x041E; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0422; verylow; #Intel; Intel(R) HD Graphics 5000 +0x8086; 0x0426; verylow; #Intel; Intel(R) HD Graphics 5000 +0x8086; 0x042A; verylow; #Intel; Intel(R) HD Graphics 5000 +0x8086; 0x042B; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x042E; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0900; low; #Intel; Intel(R) HD Graphics +0x8086; 0x0901; low; #Intel; Intel(R) HD Graphics +0x8086; 0x0902; low; #Intel; Intel(R) HD Graphics +0x8086; 0x0903; low; #Intel; Intel(R) HD Graphics +0x8086; 0x0904; low; #Intel; Intel(R) HD Graphics +0x8086; 0x0A02; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0BD0; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0BD1; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0BD2; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0BD3; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0BD4; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C02; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C06; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C0A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C12; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C16; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C1A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C22; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C26; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0C2A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x0F30; verylow; #Intel; Intel(R) Vallyview Graphics +0x8086; 0x0F31; verylow; #Intel; Intel(R) Vallyview Graphics +0x8086; 0x1602; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x1606; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x160A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x160B; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x160D; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x160E; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x1612; verylow; #Intel; Intel(R) HD Graphics 5600 +0x8086; 0x1616; verylow; #Intel; Intel(R) HD Graphics 5500 +0x8086; 0x161A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x161B; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x161D; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x161E; verylow; #Intel; Intel(R) HD Graphics 5300 +0x8086; 0x1622; verylow; #Intel; Intel(R) Iris(TM) Pro Graphics 6200 +0x8086; 0x1626; verylow; #Intel; Intel(R) HD Graphics 6000 +0x8086; 0x162A; verylow; #Intel; Intel(R) Iris(TM) Pro Graphics P6300 +0x8086; 0x162B; verylow; #Intel; Intel(R) Iris(TM) Graphics 6100 +0x8086; 0x162D; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x162E; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x1632; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x1636; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x163A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x163B; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x163D; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x163E; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x1902; low; #Intel; Intel(R) HD Graphics 510 +0x8086; 0x1906; low; #Intel; Intel(R) HD Graphics 510 +0x8086; 0x190A; low; #Intel; Intel(R) HD Graphics +0x8086; 0x190B; low; #Intel; Intel(R) HD Graphics +0x8086; 0x190E; low; #Intel; Intel(R) HD Graphics +0x8086; 0x1912; low; #Intel; Intel(R) HD Graphics 530 +0x8086; 0x1913; low; #Intel; Intel(R) HD Graphics +0x8086; 0x1916; low; #Intel; Intel(R) HD Graphics 520 +0x8086; 0x191A; low; #Intel; Intel(R) HD Graphics +0x8086; 0x191B; low; #Intel; Intel(R) HD Graphics 530 +0x8086; 0x191D; low; #Intel; Intel(R) HD Graphics P530 +0x8086; 0x191E; low; #Intel; Intel(R) HD Graphics 515 +0x8086; 0x1921; low; #Intel; Intel(R) HD Graphics +0x8086; 0x1923; low; #Intel; Intel(R) HD Graphics +0x8086; 0x1926; low; #Intel; Intel(R) Iris Graphics 540 +0x8086; 0x1927; low; #Intel; Intel(R) Iris Graphics 540 +0x8086; 0x192A; low; #Intel; Intel(R) HD Graphics +0x8086; 0x192B; low; #Intel; Intel(R) HD Graphics +0x8086; 0x192D; low; #Intel; Intel(R) HD Graphics +0x8086; 0x193A; low; #Intel; Intel(R) HD Graphics +0x8086; 0x193B; medium; #Intel; Intel(R) Iris Pro Graphics 580 +0x8086; 0x193D; medium; #Intel; Intel(R) Iris Pro Graphics P580 +0x8086; 0x22B0; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x22B1; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x22B2; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x22B3; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x2982; verylow; #Intel; Intel(R) G35 Express Chipset Family +0x8086; 0x2983; verylow; #Intel; Intel(R) G35 Express Chipset Family +0x8086; 0x2A02; verylow; #Intel; Mobile Intel(R) 965 Express Chipset Family +0x8086; 0x2A03; verylow; #Intel; Mobile Intel(R) 965 Express Chipset Family +0x8086; 0x2A12; verylow; #Intel; Mobile Intel(R) 965 Express Chipset Family +0x8086; 0x2A13; verylow; #Intel; Mobile Intel(R) 965 Express Chipset Family +0x8086; 0x2A42; verylow; #Intel; Mobile Intel(R) 4 Series Express Chipset Family +0x8086; 0x2A43; verylow; #Intel; Mobile Intel(R) 4 Series Express Chipset Family +0x8086; 0x2E02; verylow; #Intel; Intel(R) 4 Series Express Chipset +0x8086; 0x2E03; verylow; #Intel; Intel(R) 4 Series Express Chipset +0x8086; 0x2E12; verylow; #Intel; Intel(R) Q45/Q43 Express Chipset +0x8086; 0x2E13; verylow; #Intel; Intel(R) Q45/Q43 Express Chipset +0x8086; 0x2E22; verylow; #Intel; Intel(R) G45/G43 Express Chipset +0x8086; 0x2E23; verylow; #Intel; Intel(R) G45/G43 Express Chipset +0x8086; 0x2E32; verylow; #Intel; Intel(R) G41 Express Chipset +0x8086; 0x2E33; verylow; #Intel; Intel(R) G41 Express Chipset +0x8086; 0x2E42; verylow; #Intel; Intel(R) B43 Express Chipset +0x8086; 0x2E43; verylow; #Intel; Intel(R) B43 Express Chipset +0x8086; 0x2E92; verylow; #Intel; Intel(R) B43 Express Chipset +0x8086; 0x2E93; verylow; #Intel; Intel(R) B43 Express Chipset +0x8086; 0x3184; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3185; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E90; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E91; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E92; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E93; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E94; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E96; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E98; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E99; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E9A; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E9B; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3E9C; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x3EA0; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3EA1; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x3EA2; medium; #Intel; Intel(R) Iris Plus Graphics +0x8086; 0x3EA3; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x3EA4; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x3EA5; medium; #Intel; Intel(R) Iris Plus Graphics +0x8086; 0x3EA6; medium; #Intel; Intel(R) Iris Plus Graphics +0x8086; 0x3EA7; medium; #Intel; Intel(R) Iris Plus Graphics +0x8086; 0x3EA8; medium; #Intel; Intel(R) Iris Plus Graphics +0x8086; 0x3EA9; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x4626; low; #Intel; , Intel(R) Xe Graphics +0x8086; 0x4680; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0x4682; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0x4688; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0x468A; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0x468B; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0x4690; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0x4692; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0x4693; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0x46A3; low; #Intel; , Intel(R) Xe Graphics +0x8086; 0x46A6; low; #Intel; Intel(R) Xe Graphics +0x8086; 0x4905; low; #Intel; Intel(R) Iris(R) Xe MAX Graphics +0x8086; 0x4906; low; #Intel; Intel(R) Iris(R) Xe MAX Graphics +0x8086; 0x4907; low; #Intel; Intel(R) Iris(R) Xe MAX Graphics +0x8086; 0x4C8A; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x4C8B; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x4C90; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x5690; medium; #Intel; Intel(R) Arc(TM) A770M Graphics +0x8086; 0x5693; medium; #Intel; Intel(R) Arc(TM) A370M Graphics +0x8086; 0x56A0; medium; #Intel; Intel(R) Arc(TM) A770 Graphics +0x8086; 0x56A1; medium; #Intel; Intel(R) Arc(TM) A750 Graphics +0x8086; 0x56A5; medium; #Intel; Intel(R) Arc(TM) A380 Graphics +0x8086; 0x5902; verylow; #Intel; Intel(R) HD Graphics 610 +0x8086; 0x5906; verylow; #Intel; Intel(R) HD Graphics 610 +0x8086; 0x5908; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x590A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x590B; verylow; #Intel; Intel(R) HD Graphics P610 +0x8086; 0x590E; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5912; low; #Intel; Intel(R) HD Graphics 630 +0x8086; 0x5913; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5915; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5916; low; #Intel; Intel(R) HD Graphics 620 +0x8086; 0x5917; low; #Intel; Intel(R) UHD Graphics 620 +0x8086; 0x591A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x591B; low; #Intel; Intel(R) HD Graphics 630 +0x8086; 0x591C; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x591D; low; #Intel; Intel(R) HD Graphics P630 +0x8086; 0x591E; verylow; #Intel; Intel(R) HD Graphics 615 +0x8086; 0x5921; low; #Intel; Intel(R) HD Graphics 620 +0x8086; 0x5923; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5926; medium; #Intel; Intel(R) Iris Plus Graphics 640 +0x8086; 0x5927; medium; #Intel; Intel(R) Iris Plus Graphics 650 +0x8086; 0x592A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x592B; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5932; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x593A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x593B; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x593D; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A40; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A41; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A42; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A44; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A49; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A4A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A4C; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A50; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A51; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A52; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A54; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A59; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A5A; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x5A5C; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x87C0; verylow; #Intel; Intel(R) HD Graphics +0x8086; 0x87CA; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x8A50; low; #Intel; Intel(R) Iris Plus Graphics (64 EUs) +0x8086; 0x8A51; low; #Intel; Intel(R) Iris Plus Graphics (64 EUs) +0x8086; 0x8A52; low; #Intel; Intel(R) Iris Plus Graphics (64 EUs) +0x8086; 0x8A53; low; #Intel; Intel(R) Iris Plus Graphics (64 EUs) +0x8086; 0x8A54; low; #Intel; Intel(R) Iris Plus Graphics (48 EUs) +0x8086; 0x8A56; low; #Intel; Intel(R) Iris Plus Graphics (48 EUs) +0x8086; 0x8A57; low; #Intel; Intel(R) Iris Plus Graphics (48 EUs) +0x8086; 0x8A58; low; #Intel; Intel(R) Iris Plus Graphics (32 EUs) +0x8086; 0x8A59; low; #Intel; Intel(R) Iris Plus Graphics (48 EUs) +0x8086; 0x8A5A; low; #Intel; Intel(R) Iris Plus Graphics (48 EUs) +0x8086; 0x8A5B; low; #Intel; Intel(R) Iris Plus Graphics (32 EUs) +0x8086; 0x8A5C; low; #Intel; Intel(R) Iris Plus Graphics (48 EUs) +0x8086; 0x8A5D; low; #Intel; Intel(R) Iris Plus Graphics (32 EUs) +0x8086; 0x8A71; low; #Intel; Intel(R) Iris Plus Graphics (8 EUs) +0x8086; 0x9A40; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9A49; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9A59; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9A60; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9A68; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9A70; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9A78; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9A7F; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9AC0; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9AC9; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9AD9; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9AF8; low; #Intel; Intel(R) Iris(R) Xe Graphics +0x8086; 0x9B21; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9B41; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BA0; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BA2; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BA4; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BA5; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BA8; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BAA; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BAB; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BAC; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BC0; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BC2; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BC4; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BC5; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BC6; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BC8; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BCA; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BCB; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BCC; low; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BE6; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0x9BF6; verylow; #Intel; Intel(R) UHD Graphics +0x8086; 0xA780; medium; #Intel; Intel(R) Xe Graphics +0x8086; 0xA788; medium; #Intel; Intel(R) Xe Graphics + +#amd +0x1002; 0x1309; verylow; #AMD; AMD Radeon(TM) R7 Graphics +0x1002; 0x130A; verylow; #AMD; AMD Radeon(TM) R6 Graphics +0x1002; 0x130D; verylow; #AMD; AMD Radeon(TM) R6 Graphics +0x1002; 0x130F; verylow; #AMD; AMD Radeon(TM) R7 Graphics +0x1002; 0x1313; verylow; #AMD; AMD Radeon(TM) R7 Graphics +0x1002; 0x15BF; verylow; #AMD; AMD Radeon (TM) 740M Graphics +0x1002; 0x15D8; verylow; #AMD; AMD 15D8:C8 +0x1002; 0x15DD; verylow; #AMD; AMD Radeon(TM) RX Vega 10 Graphics +0x1002; 0x15E7; verylow; #AMD; AMD Radeon (TM) Graphics +0x1002; 0x163F; verylow; #AMD; AMD Custom GPU 0405 +0x1002; 0x164E; verylow; #AMD; AMD Radeon(TM) 610M +0x1002; 0x1681; verylow; #AMD; AMD Radeon (TM) Graphics +0x1002; 0x6600; verylow; #AMD; AMD Radeon (TM) R7 M370 +0x1002; 0x6601; verylow; #AMD; AMD Radeon (TM) HD 8500M/8700M +0x1002; 0x6604; verylow; #AMD; AMD Radeon (TM) R7 M350 +0x1002; 0x6605; verylow; #AMD; AMD FirePro M4150 +0x1002; 0x6606; verylow; #AMD; AMD Radeon HD 8790M +0x1002; 0x6608; verylow; #AMD; AMD FirePro W2100 +0x1002; 0x6610; verylow; #AMD; AMD Radeon (TM) R5 340 +0x1002; 0x6611; verylow; #AMD; AMD Radeon HD 8570 +0x1002; 0x6613; verylow; #AMD; AMD Radeon R7 240 +0x1002; 0x6640; verylow; #AMD; AMD FirePro M6100 +0x1002; 0x6646; verylow; #AMD; AMD Radeon (TM) R9 M470X +0x1002; 0x6660; verylow; #AMD; AMD Radeon (TM) 520 +0x1002; 0x6665; verylow; #AMD; AMD Radeon (TM) R5 M320 +0x1002; 0x666F; verylow; #AMD; AMD Radeon HD 8500M +0x1002; 0x66A1; medium; #AMD; AMD Radeon Pro VII +0x1002; 0x66AF; high; #AMD; AMD Radeon VII +0x1002; 0x67A0; verylow; #AMD; AMD FirePro S9150 +0x1002; 0x67B0; low; #AMD; AMD Radeon(TM) R9 290X +0x1002; 0x67C4; medium; #AMD; AMD Radeon (TM) Pro WX 7100 Graphics +0x1002; 0x67C7; low; #AMD; Radeon (TM) Pro WX 5100 Graphics +0x1002; 0x67DF; medium; #AMD; AMD Radeon (TM) RX 480 +0x1002; 0x67E3; verylow; #AMD; Radeon (TM) Pro WX 4100 +0x1002; 0x67E8; verylow; #AMD; Radeon(TM) Pro WX 4150 Graphics +0x1002; 0x67EF; verylow; #AMD; AMD Radeon Pro 460 +0x1002; 0x6801; verylow; #AMD; AMD Radeon(TM) HD8970M +0x1002; 0x6808; low; #AMD; AMD FirePro W7000 +0x1002; 0x6810; verylow; #AMD; AMD FirePro D300 +0x1002; 0x6820; verylow; #AMD; AMD FirePro W5170M +0x1002; 0x6821; verylow; #AMD; AMD FirePro M5100 +0x1002; 0x682B; verylow; #AMD; AMD Radeon (TM) R9 M360 +0x1002; 0x682C; verylow; #AMD; AMD FirePro W4100 +0x1002; 0x683D; verylow; #AMD; AMD Radeon HD 7770 GHz Edition +0x1002; 0x6861; medium; #AMD; Radeon (TM) Pro WX 9100 +0x1002; 0x6863; medium; #AMD; Radeon Vega Frontier Edition +0x1002; 0x6869; medium; #AMD; Radeon Pro Vega 48 +0x1002; 0x686B; medium; #AMD; Radeon Pro Vega 64X +0x1002; 0x687F; medium; #AMD; Radeon RX Vega +0x1002; 0x6900; verylow; #AMD; AMD Radeon (TM) 535DX +0x1002; 0x6901; verylow; #AMD; AMD Radeon R5 M255 +0x1002; 0x6920; low; #AMD; AMD RADEON R9 M395X +0x1002; 0x6929; verylow; #AMD; AMD FirePro S7150 +0x1002; 0x692B; low; #AMD; AMD FirePro W7100 +0x1002; 0x6938; low; #AMD; AMD RADEON R9 M295X +0x1002; 0x694C; low; #AMD; Radeon RX Vega M GH Graphics +0x1002; 0x694E; verylow; #AMD; Radeon RX Vega M GL Graphics +0x1002; 0x699F; verylow; #AMD; AMD Embedded Radeon E9175 +0x1002; 0x69AF; low; #AMD; Radeon Pro Vega 20 +0x1002; 0x6FDF; low; #AMD; AMD Radeon RX 580 2048SP +0x1002; 0x7300; medium; #AMD; Radeon (TM) Pro Duo +0x1002; 0x7312; medium; #AMD; AMD Radeon Pro W5700 +0x1002; 0x731F; medium; #AMD; AMD Radeon RX 5600 XT +0x1002; 0x7340; low; #AMD; AMD Radeon Pro 5300 +0x1002; 0x7341; medium; #AMD; AMD Radeon Pro W5500 +0x1002; 0x7360; medium; #AMD; AMD Radeon Pro 5600M +0x1002; 0x7362; low; #AMD; AMD Radeon Pro V520 MxGPU +0x1002; 0x73A3; high; #AMD; AMD Radeon PRO W6800 +0x1002; 0x73A5; high; #AMD; AMD Radeon RX 6950 XT +0x1002; 0x73AB; low; #AMD; AMD Radeon Pro W6800X +0x1002; 0x73AF; high; #AMD; AMD Radeon RX 6900 XT +0x1002; 0x73BF; high; #AMD; AMD Radeon RX 6800 +0x1002; 0x73DF; high; #AMD; AMD Radeon RX 6700 +0x1002; 0x73E3; high; #AMD; AMD Radeon PRO W6600 +0x1002; 0x73EF; high; #AMD; AMD Radeon RX 6650 XT +0x1002; 0x73FF; medium; #AMD; AMD Radeon RX 6600 +0x1002; 0x7422; medium; #AMD; AMD Radeon PRO W6400 +0x1002; 0x743F; low; #AMD; AMD Radeon RX 6400 +0x1002; 0x744C; high; #AMD; AMD Radeon RX 7900 XT +0x1002; 0x747E; high; #AMD; AMD Radeon RX 7700 XT +0x1002; 0x7480; high; #AMD; AMD Radeon RX 7600 +0x1002; 0x9832; verylow; #AMD; AMD Radeon HD 8330 +0x1002; 0x9834; office; #AMD; AMD Radeon HD 8210 +0x1002; 0x9850; verylow; #AMD; AMD Radeon(TM) R2 Graphics +0x1002; 0x9851; verylow; #AMD; AMD Radeon(TM) R4 Graphics +0x1002; 0x9853; verylow; #AMD; AMD Radeon(TM) R2 Graphics +0x1002; 0x9874; verylow; #AMD; AMD Radeon R5 Graphics +0x1002; 0x98E4; verylow; #AMD; AMD Radeon(TM) R2 Graphics + +#nvidia +0x10DE; 0x1001; medium; #NVIDIA; GeForce GTX TITAN Z +0x10DE; 0x1004; medium; #NVIDIA; GeForce GTX 780 +0x10DE; 0x1005; medium; #NVIDIA; GeForce GTX TITAN +0x10DE; 0x100A; medium; #NVIDIA; GeForce GTX 780 Ti +0x10DE; 0x100C; medium; #NVIDIA; GeForce GTX TITAN Black +0x10DE; 0x1023; verylow; #NVIDIA; Tesla K40m +0x10DE; 0x103A; medium; #NVIDIA; Quadro K6000 +0x10DE; 0x103C; low; #NVIDIA; Quadro K5200 +0x10DE; 0x1180; low; #NVIDIA; GeForce GTX 680 +0x10DE; 0x1183; low; #NVIDIA; GeForce GTX 660 Ti +0x10DE; 0x1184; low; #NVIDIA; GeForce GTX 770 +0x10DE; 0x1185; low; #NVIDIA; GeForce GTX 660 +0x10DE; 0x1187; low; #NVIDIA; GeForce GTX 760 +0x10DE; 0x1188; low; #NVIDIA; GeForce GTX 690 +0x10DE; 0x1189; low; #NVIDIA; GeForce GTX 670 +0x10DE; 0x118E; low; #NVIDIA; GeForce GTX 760 (192-bit) +0x10DE; 0x1198; verylow; #NVIDIA; GeForce GTX 880M +0x10DE; 0x1199; verylow; #NVIDIA; GeForce GTX 870M +0x10DE; 0x119A; verylow; #NVIDIA; GeForce GTX 860M +0x10DE; 0x119E; verylow; #NVIDIA; GeForce GTX 780M +0x10DE; 0x119F; verylow; #NVIDIA; GeForce GTX 780M +0x10DE; 0x11A1; verylow; #NVIDIA; GeForce GTX 670MX +0x10DE; 0x11A3; low; #NVIDIA; GeForce GTX 680MX +0x10DE; 0x11A7; verylow; #NVIDIA; GeForce GTX 675MX +0x10DE; 0x11B4; low; #NVIDIA; Quadro K4200 +0x10DE; 0x11B6; verylow; #NVIDIA; Quadro K3100M +0x10DE; 0x11B7; verylow; #NVIDIA; Quadro K4100M +0x10DE; 0x11B8; verylow; #NVIDIA; Quadro K5100M +0x10DE; 0x11BC; verylow; #NVIDIA; Quadro K5000M +0x10DE; 0x11BE; verylow; #NVIDIA; Quadro K3000M +0x10DE; 0x11C0; low; #NVIDIA; GeForce GTX 660 +0x10DE; 0x11C2; verylow; #NVIDIA; GeForce GTX 650 Ti BOOST +0x10DE; 0x11C4; verylow; #NVIDIA; GeForce GTX 645 +0x10DE; 0x11C6; verylow; #NVIDIA; GeForce GTX 650 Ti +0x10DE; 0x11C8; verylow; #NVIDIA; GeForce GTX 650 +0x10DE; 0x11E0; verylow; #NVIDIA; GeForce GTX 770M +0x10DE; 0x11E1; verylow; #NVIDIA; NVIDIA GeForce GTX 765M +0x10DE; 0x11E2; verylow; #NVIDIA; GeForce GTX 765M +0x10DE; 0x11E3; verylow; #NVIDIA; GeForce GTX 760M +0x10DE; 0x11FA; verylow; #NVIDIA; Quadro K4000 +0x10DE; 0x11FC; verylow; #NVIDIA; K2100M +0x10DE; 0x1280; verylow; #NVIDIA; GeForce GT 635 +0x10DE; 0x1281; verylow; #NVIDIA; GT 710 +0x10DE; 0x1282; verylow; #NVIDIA; NVIDIA GeForce GT 640 +0x10DE; 0x1284; verylow; #NVIDIA; GeForce GT 630 +0x10DE; 0x1286; verylow; #NVIDIA; GeForce GT 720 +0x10DE; 0x1287; verylow; #NVIDIA; GeForce GT 730 +0x10DE; 0x1288; verylow; #NVIDIA; GeForce GT 720 +0x10DE; 0x128B; verylow; #NVIDIA; GeForce GT 710 +0x10DE; 0x1290; verylow; #NVIDIA; GeForce GT 730M +0x10DE; 0x1292; verylow; #NVIDIA; GeForce GT 740M +0x10DE; 0x1295; verylow; #NVIDIA; GeForce 810A +0x10DE; 0x1299; verylow; #NVIDIA; 920M +0x10DE; 0x129A; verylow; #NVIDIA; GeForce 910M +0x10DE; 0x12B9; verylow; #NVIDIA; Quadro K610M +0x10DE; 0x1340; verylow; #NVIDIA; NVIDIA GeForce 830M +0x10DE; 0x1341; verylow; #NVIDIA; 840M +0x10DE; 0x1344; verylow; #NVIDIA; GeForce 845M +0x10DE; 0x1346; verylow; #NVIDIA; GeForce 930M +0x10DE; 0x1347; verylow; #NVIDIA; GeForce 940M +0x10DE; 0x134B; verylow; #NVIDIA; NVIDIA GeForce GPU +0x10DE; 0x134D; verylow; #NVIDIA; GeForce 940MX +0x10DE; 0x134E; verylow; #NVIDIA; 930MX +0x10DE; 0x134F; verylow; #NVIDIA; 920MX +0x10DE; 0x137B; verylow; #NVIDIA; Quadro M520 +0x10DE; 0x1380; low; #NVIDIA; GeForce GTX 750 Ti +0x10DE; 0x1381; verylow; #NVIDIA; GeForce GTX 750 +0x10DE; 0x1382; low; #NVIDIA; GeForce GTX 745 +0x10DE; 0x1391; verylow; #NVIDIA; GeForce GTX 850M +0x10DE; 0x1392; verylow; #NVIDIA; GeForce GPU +0x10DE; 0x139A; verylow; #NVIDIA; GeForce GTX 950M +0x10DE; 0x139B; verylow; #NVIDIA; GeForce GTX 960M +0x10DE; 0x139C; verylow; #NVIDIA; NVIDIA GeForce 940M +0x10DE; 0x13B0; verylow; #NVIDIA; Quadro M2000M +0x10DE; 0x13B1; verylow; #NVIDIA; M1000M +0x10DE; 0x13B4; verylow; #NVIDIA; Quadro M620 +0x10DE; 0x13B6; verylow; #NVIDIA; Quadro M1200 +0x10DE; 0x13BA; verylow; #NVIDIA; K2200 +0x10DE; 0x13BB; verylow; #NVIDIA; Quadro K620 +0x10DE; 0x13C0; medium; #NVIDIA; GeForce GTX 980 +0x10DE; 0x13C2; medium; #NVIDIA; GeForce GTX 970 +0x10DE; 0x13D7; low; #NVIDIA; GeForce GTX 980M +0x10DE; 0x13D8; low; #NVIDIA; GeForce GTX 970M +0x10DE; 0x13F1; low; #NVIDIA; Quadro M4000 +0x10DE; 0x13F2; low; #NVIDIA; GRID M60-8Q +0x10DE; 0x13F8; low; #NVIDIA; Quadro M5000M +0x10DE; 0x13F9; low; #NVIDIA; Quadro M4000M +0x10DE; 0x13FA; low; #NVIDIA; Quadro M3000M +0x10DE; 0x1401; low; #NVIDIA; GeForce GTX 960 +0x10DE; 0x1402; low; #NVIDIA; GeForce GTX 950 +0x10DE; 0x1407; verylow; #NVIDIA; GeForce GTX 750 +0x10DE; 0x1427; verylow; #NVIDIA; GeForce GTX 965M +0x10DE; 0x1430; low; #NVIDIA; Quadro M2000 +0x10DE; 0x1436; low; #NVIDIA; Quadro M2200 +0x10DE; 0x15F0; high; #NVIDIA; Quadro GP100 +0x10DE; 0x1617; low; #NVIDIA; NVIDIA GeForce GTX 980M +0x10DE; 0x1618; low; #NVIDIA; GeForce GTX 970M +0x10DE; 0x174D; verylow; #NVIDIA; GeForce MX130 +0x10DE; 0x174E; verylow; #NVIDIA; GeForce MX110 +0x10DE; 0x179C; verylow; #NVIDIA; 940MX +0x10DE; 0x17C2; medium; #NVIDIA; GeForce GTX TITAN X +0x10DE; 0x17C8; medium; #NVIDIA; GeForce GTX 980 Ti +0x10DE; 0x17F0; medium; #NVIDIA; Quadro M6000 +0x10DE; 0x17F1; medium; #NVIDIA; Quadro M6000 24GB +0x10DE; 0x1B00; medium; #NVIDIA; NVIDIA TITAN X (Pascal) +0x10DE; 0x1B02; high; #NVIDIA; NVIDIA TITAN Xp +0x10DE; 0x1B06; high; #NVIDIA; GeForce GTX 1080 Ti +0x10DE; 0x1B30; medium; #NVIDIA; Quadro P6000 +0x10DE; 0x1B38; verylow; #NVIDIA; GRID P40-4Q +0x10DE; 0x1B80; high; #NVIDIA; GeForce GTX 1080 +0x10DE; 0x1B81; medium; #NVIDIA; GeForce GTX 1070 +0x10DE; 0x1B82; medium; #NVIDIA; GeForce GTX 1070 Ti +0x10DE; 0x1B83; medium; #NVIDIA; GeForce GTX 1060 6GB +0x10DE; 0x1B84; medium; #NVIDIA; NVIDIA GeForce GTX 1060 3GB +0x10DE; 0x1BA1; low; #NVIDIA; GeForce GTX 1070 with Max-Q Design +0x10DE; 0x1BB0; medium; #NVIDIA; Quadro P5000 +0x10DE; 0x1BB1; medium; #NVIDIA; NVIDIA Quadro P4000 +0x10DE; 0x1BB3; medium; #NVIDIA; Tesla P4 +0x10DE; 0x1BB5; medium; #NVIDIA; Quadro P5200 +0x10DE; 0x1BB6; medium; #NVIDIA; Quadro P5000 +0x10DE; 0x1BB7; medium; #NVIDIA; NVIDIA Quadro P4000 +0x10DE; 0x1BB8; medium; #NVIDIA; Quadro P3000 +0x10DE; 0x1BB9; medium; #NVIDIA; Quadro P4200 +0x10DE; 0x1BBB; medium; #NVIDIA; Quadro P3200 +0x10DE; 0x1BE0; high; #NVIDIA; GeForce GTX 1080 +0x10DE; 0x1BE1; medium; #NVIDIA; GeForce GTX 1070 +0x10DE; 0x1C02; medium; #NVIDIA; GeForce GTX 1060 3GB +0x10DE; 0x1C03; medium; #NVIDIA; GeForce GTX 1060 6GB +0x10DE; 0x1C04; medium; #NVIDIA; GeForce GTX 1060 5GB +0x10DE; 0x1C06; medium; #NVIDIA; GeForce GTX 1060 6GB +0x10DE; 0x1C07; low; #NVIDIA; P106-100 +0x10DE; 0x1C09; verylow; #NVIDIA; P106-090 +0x10DE; 0x1C20; medium; #NVIDIA; GeForce GTX 1060 +0x10DE; 0x1C21; low; #NVIDIA; GeForce GTX 1050 Ti +0x10DE; 0x1C30; low; #NVIDIA; Quadro P2000 +0x10DE; 0x1C31; medium; #NVIDIA; Quadro P2200 +0x10DE; 0x1C60; medium; #NVIDIA; GeForce GTX 1060 +0x10DE; 0x1C81; low; #NVIDIA; GeForce GTX 1050 +0x10DE; 0x1C82; low; #NVIDIA; GeForce GTX 1050 Ti +0x10DE; 0x1C8C; low; #NVIDIA; GeForce GTX 1050 Ti +0x10DE; 0x1C8D; low; #NVIDIA; GeForce GTX 1050 +0x10DE; 0x1C8F; low; #NVIDIA; GeForce GTX 1050 Ti with Max-Q Design +0x10DE; 0x1C90; verylow; #NVIDIA; NVIDIA GeForce MX150 +0x10DE; 0x1C91; low; #NVIDIA; GeForce GTX 1050 +0x10DE; 0x1C92; low; #NVIDIA; GeForce GTX 1050 +0x10DE; 0x1C94; verylow; #NVIDIA; NVIDIA GeForce MX350 +0x10DE; 0x1C96; verylow; #NVIDIA; GeForce MX350 +0x10DE; 0x1CB2; verylow; #NVIDIA; Quadro P600 +0x10DE; 0x1CB3; verylow; #NVIDIA; Quadro P400 +0x10DE; 0x1CB6; verylow; #NVIDIA; Quadro P620 +0x10DE; 0x1CBA; low; #NVIDIA; Quadro P2000 +0x10DE; 0x1CBB; low; #NVIDIA; Quadro P1000 +0x10DE; 0x1CBC; verylow; #NVIDIA; Quadro P600 +0x10DE; 0x1CBD; verylow; #NVIDIA; NVIDIA Quadro P620 +0x10DE; 0x1D01; verylow; #NVIDIA; GeForce GT 1030 +0x10DE; 0x1D10; verylow; #NVIDIA; GeForce MX150 +0x10DE; 0x1D11; verylow; #NVIDIA; GeForce MX230 +0x10DE; 0x1D12; verylow; #NVIDIA; GeForce MX150 +0x10DE; 0x1D13; verylow; #NVIDIA; GeForce MX250 +0x10DE; 0x1D16; verylow; #NVIDIA; GeForce MX330 +0x10DE; 0x1D52; verylow; #NVIDIA; GeForce MX250 +0x10DE; 0x1D81; high; #NVIDIA; NVIDIA TITAN V +0x10DE; 0x1DBA; high; #NVIDIA; Quadro GV100 +0x10DE; 0x1E02; high; #NVIDIA; NVIDIA TITAN RTX +0x10DE; 0x1E04; high; #NVIDIA; GeForce RTX 2080 Ti +0x10DE; 0x1E07; high; #NVIDIA; GeForce RTX 2080 Ti +0x10DE; 0x1E30; high; #NVIDIA; Quadro RTX 6000 +0x10DE; 0x1E81; high; #NVIDIA; GeForce RTX 2080 SUPER +0x10DE; 0x1E82; high; #NVIDIA; GeForce RTX 2080 +0x10DE; 0x1E84; high; #NVIDIA; GeForce RTX 2070 SUPER +0x10DE; 0x1E87; high; #NVIDIA; GeForce RTX 2080 +0x10DE; 0x1E89; medium; #NVIDIA; GeForce RTX 2060 +0x10DE; 0x1E90; medium; #NVIDIA; GeForce RTX 2080 with Max-Q Design +0x10DE; 0x1E91; high; #NVIDIA; NVIDIA GeForce RTX 2070 Super +0x10DE; 0x1E93; medium; #NVIDIA; NVIDIA GeForce RTX 2080 Super with Max-Q Design +0x10DE; 0x1EB0; high; #NVIDIA; Quadro RTX 5000 +0x10DE; 0x1EB1; medium; #NVIDIA; Quadro RTX 4000 +0x10DE; 0x1EB5; medium; #NVIDIA; NVIDIA Quadro RTX 5000 with Max-Q Design +0x10DE; 0x1EB6; medium; #NVIDIA; Quadro RTX 4000 +0x10DE; 0x1EB8; low; #NVIDIA; GRID T4-2B +0x10DE; 0x1EC7; high; #NVIDIA; NVIDIA GeForce RTX 2070 SUPER +0x10DE; 0x1ED0; high; #NVIDIA; NVIDIA GeForce RTX 2080 +0x10DE; 0x1ED1; high; #NVIDIA; NVIDIA GeForce RTX 2070 Super +0x10DE; 0x1ED3; medium; #NVIDIA; NVIDIA GeForce RTX 2080 Super with Max-Q Design +0x10DE; 0x1F02; high; #NVIDIA; GeForce RTX 2070 +0x10DE; 0x1F03; medium; #NVIDIA; NVIDIA GeForce RTX 2060 +0x10DE; 0x1F06; high; #NVIDIA; GeForce RTX 2060 SUPER +0x10DE; 0x1F07; high; #NVIDIA; GeForce RTX 2070 +0x10DE; 0x1F08; medium; #NVIDIA; GeForce RTX 2060 +0x10DE; 0x1F0A; medium; #NVIDIA; NVIDIA GeForce GTX 1650 +0x10DE; 0x1F10; high; #NVIDIA; GeForce RTX 2070 +0x10DE; 0x1F11; medium; #NVIDIA; GeForce RTX 2060 +0x10DE; 0x1F12; medium; #NVIDIA; GeForce RTX 2060 with Max-Q Design +0x10DE; 0x1F14; high; #NVIDIA; NVIDIA GeForce RTX 2070 +0x10DE; 0x1F15; medium; #NVIDIA; GeForce RTX 2060 +0x10DE; 0x1F36; medium; #NVIDIA; Quadro RTX 3000 +0x10DE; 0x1F47; high; #NVIDIA; NVIDIA GeForce RTX 2060 SUPER +0x10DE; 0x1F50; high; #NVIDIA; GeForce RTX 2070 +0x10DE; 0x1F82; medium; #NVIDIA; GeForce GTX 1650 +0x10DE; 0x1F91; medium; #NVIDIA; GeForce GTX 1650 +0x10DE; 0x1F95; medium; #NVIDIA; GeForce GTX 1650 Ti +0x10DE; 0x1F96; medium; #NVIDIA; GeForce GTX 1650 +0x10DE; 0x1F97; verylow; #NVIDIA; NVIDIA GeForce MX450 +0x10DE; 0x1F99; medium; #NVIDIA; GeForce GTX 1650 +0x10DE; 0x1F9C; verylow; #NVIDIA; NVIDIA GeForce MX450 +0x10DE; 0x1F9D; medium; #NVIDIA; GeForce GTX 1650 +0x10DE; 0x1F9F; low; #NVIDIA; NVIDIA GeForce MX550 +0x10DE; 0x1FB1; low; #NVIDIA; NVIDIA T600 +0x10DE; 0x1FB2; verylow; #NVIDIA; NVIDIA T400 +0x10DE; 0x1FB6; verylow; #NVIDIA; NVIDIA T600 Laptop GPU +0x10DE; 0x1FB7; low; #NVIDIA; NVIDIA T550 Laptop GPU +0x10DE; 0x1FB8; low; #NVIDIA; NVIDIA Quadro T2000 +0x10DE; 0x1FB9; low; #NVIDIA; Quadro T1000 +0x10DE; 0x1FBA; verylow; #NVIDIA; NVIDIA T600 Laptop GPU +0x10DE; 0x1FBB; verylow; #NVIDIA; NVIDIA T500 +0x10DE; 0x1FBC; low; #NVIDIA; NVIDIA T1200 Laptop GPU +0x10DE; 0x1FDD; medium; #NVIDIA; NVIDIA GeForce GTX 1650 +0x10DE; 0x1FF2; verylow; #NVIDIA; NVIDIA T400 4GB +0x10DE; 0x2182; medium; #NVIDIA; GeForce GTX 1660 Ti +0x10DE; 0x2184; medium; #NVIDIA; GeForce GTX 1660 +0x10DE; 0x2187; medium; #NVIDIA; GeForce GTX 1650 SUPER +0x10DE; 0x2188; medium; #NVIDIA; NVIDIA GeForce GTX 1650 +0x10DE; 0x2191; medium; #NVIDIA; GeForce GTX 1660 Ti +0x10DE; 0x2192; medium; #NVIDIA; GeForce GTX 1650 Ti +0x10DE; 0x21C4; medium; #NVIDIA; GeForce GTX 1660 SUPER +0x10DE; 0x2203; ultra; #NVIDIA; NVIDIA GeForce RTX 3090 Ti +0x10DE; 0x2204; high; #NVIDIA; GeForce RTX 3090 +0x10DE; 0x2206; high; #NVIDIA; GeForce RTX 3080 +0x10DE; 0x2207; high; #NVIDIA; NVIDIA GeForce RTX 3070 Ti +0x10DE; 0x2208; high; #NVIDIA; NVIDIA GeForce RTX 3080 Ti +0x10DE; 0x220A; high; #NVIDIA; NVIDIA GeForce RTX 3080 +0x10DE; 0x2216; high; #NVIDIA; NVIDIA GeForce RTX 3080 +0x10DE; 0x2230; high; #NVIDIA; NVIDIA RTX A6000 +0x10DE; 0x2231; high; #NVIDIA; NVIDIA RTX A5000 +0x10DE; 0x2232; high; #NVIDIA; NVIDIA RTX A4500 +0x10DE; 0x2237; high; #NVIDIA; NVIDIA A10G +0x10DE; 0x2420; high; #NVIDIA; NVIDIA GeForce RTX 3080 Ti Laptop GPU +0x10DE; 0x2438; medium; #NVIDIA; NVIDIA RTX A5500 Laptop GPU +0x10DE; 0x2460; high; #NVIDIA; NVIDIA GeForce RTX 3080 Ti Laptop GPU +0x10DE; 0x2482; high; #NVIDIA; NVIDIA GeForce RTX 3070 Ti +0x10DE; 0x2484; high; #NVIDIA; GeForce RTX 3070 +0x10DE; 0x2486; high; #NVIDIA; GeForce RTX 3060 Ti +0x10DE; 0x2487; high; #NVIDIA; NVIDIA GeForce RTX 3060 +0x10DE; 0x2488; high; #NVIDIA; NVIDIA GeForce RTX 3070 +0x10DE; 0x2489; high; #NVIDIA; NVIDIA GeForce RTX 3060 Ti +0x10DE; 0x249C; high; #NVIDIA; GeForce RTX 3080 Laptop GPU +0x10DE; 0x249D; medium; #NVIDIA; GeForce RTX 3070 Laptop GPU +0x10DE; 0x24A0; high; #NVIDIA; NVIDIA GeForce RTX 3070 Ti Laptop GPU +0x10DE; 0x24B0; high; #NVIDIA; NVIDIA RTX A4000 +0x10DE; 0x24B6; medium; #NVIDIA; NVIDIA RTX A5000 Laptop GPU +0x10DE; 0x24B8; medium; #NVIDIA; NVIDIA RTX A3000 Laptop GPU +0x10DE; 0x24B9; medium; #NVIDIA; NVIDIA RTX A3000 12GB Laptop GPU +0x10DE; 0x24C9; high; #NVIDIA; NVIDIA GeForce RTX 3060 Ti +0x10DE; 0x24DC; high; #NVIDIA; GeForce RTX 3080 Laptop GPU +0x10DE; 0x24DD; medium; #NVIDIA; NVIDIA GeForce RTX 3070 Laptop GPU +0x10DE; 0x24E0; high; #NVIDIA; NVIDIA GeForce RTX 3070 Ti Laptop GPU +0x10DE; 0x2503; high; #NVIDIA; NVIDIA GeForce RTX 3060 +0x10DE; 0x2504; high; #NVIDIA; NVIDIA GeForce RTX 3060 +0x10DE; 0x2507; high; #NVIDIA; NVIDIA GeForce RTX 3050 +0x10DE; 0x2508; medium; #NVIDIA; NVIDIA GeForce RTX 3050 OEM +0x10DE; 0x2520; medium; #NVIDIA; GeForce RTX 3060 Laptop GPU +0x10DE; 0x2531; medium; #NVIDIA; NVIDIA RTX A2000 +0x10DE; 0x2544; high; #NVIDIA; NVIDIA GeForce RTX 3060 +0x10DE; 0x2560; medium; #NVIDIA; NVIDIA GeForce RTX 3060 Laptop GPU +0x10DE; 0x2563; medium; #NVIDIA; NVIDIA GeForce RTX 3050 Ti Laptop GPU +0x10DE; 0x2571; medium; #NVIDIA; NVIDIA RTX A2000 12GB +0x10DE; 0x2582; high; #NVIDIA; NVIDIA GeForce RTX 3050 +0x10DE; 0x25A0; medium; #NVIDIA; GeForce RTX 3050 Ti Laptop GPU +0x10DE; 0x25A2; medium; #NVIDIA; GeForce RTX 3050 Laptop GPU +0x10DE; 0x25A5; medium; #NVIDIA; NVIDIA GeForce RTX 3050 Laptop GPU +0x10DE; 0x25A9; high; #NVIDIA; NVIDIA GeForce RTX 2050 +0x10DE; 0x25AA; low; #NVIDIA; NVIDIA GeForce MX570 A +0x10DE; 0x25AC; high; #NVIDIA; NVIDIA GeForce RTX 3050 6GB Laptop GPU +0x10DE; 0x25AD; high; #NVIDIA; NVIDIA GeForce RTX 2050 +0x10DE; 0x25B8; medium; #NVIDIA; NVIDIA RTX A2000 Laptop GPU +0x10DE; 0x25B9; medium; #NVIDIA; NVIDIA RTX A1000 Laptop GPU +0x10DE; 0x25BA; medium; #NVIDIA; NVIDIA RTX A2000 8GB Laptop GPU +0x10DE; 0x25BB; medium; #NVIDIA; NVIDIA RTX A500 Laptop GPU +0x10DE; 0x25BC; medium; #NVIDIA; NVIDIA RTX A1000 6GB Laptop GPU +0x10DE; 0x25E0; medium; #NVIDIA; NVIDIA GeForce RTX 3050 Ti Laptop GPU +0x10DE; 0x25E2; medium; #NVIDIA; NVIDIA GeForce RTX 3050 Laptop GPU +0x10DE; 0x25EC; medium; #NVIDIA; NVIDIA GeForce RTX 3050 6GB Laptop GPU +0x10DE; 0x2684; ultra; #NVIDIA; NVIDIA GeForce RTX 4090 +0x10DE; 0x2702; ultra; #NVIDIA; NVIDIA GeForce RTX 4080 SUPER +0x10DE; 0x2704; ultra; #NVIDIA; NVIDIA GeForce RTX 4080 +0x10DE; 0x2705; ultra; #NVIDIA; NVIDIA GeForce RTX 4070 Ti SUPER +0x10DE; 0x2730; high; #NVIDIA; NVIDIA RTX 5000 Ada Generation Laptop GPU +0x10DE; 0x2757; high; #NVIDIA; NVIDIA GeForce RTX 4090 Laptop GPU +0x10DE; 0x2782; ultra; #NVIDIA; NVIDIA GeForce RTX 4070 Ti +0x10DE; 0x2783; ultra; #NVIDIA; NVIDIA GeForce RTX 4070 SUPER +0x10DE; 0x2786; high; #NVIDIA; NVIDIA GeForce RTX 4070 +0x10DE; 0x27A0; high; #NVIDIA; NVIDIA GeForce RTX 4080 Laptop GPU +0x10DE; 0x27BB; high; #NVIDIA; NVIDIA RTX 3500 Ada Generation Laptop GPU +0x10DE; 0x27E0; high; #NVIDIA; NVIDIA GeForce RTX 4080 Laptop GPU +0x10DE; 0x2803; high; #NVIDIA; NVIDIA GeForce RTX 4060 Ti +0x10DE; 0x2805; high; #NVIDIA; NVIDIA GeForce RTX 4060 Ti +0x10DE; 0x2820; high; #NVIDIA; NVIDIA GeForce RTX 4070 Laptop GPU +0x10DE; 0x2860; high; #NVIDIA; NVIDIA GeForce RTX 4070 Laptop GPU +0x10DE; 0x2882; high; #NVIDIA; NVIDIA GeForce RTX 4060 +0x10DE; 0x28A0; high; #NVIDIA; NVIDIA GeForce RTX 4060 Laptop GPU +0x10DE; 0x28A1; medium; #NVIDIA; NVIDIA GeForce RTX 4050 Laptop GPU +0x10DE; 0x28E0; high; #NVIDIA; NVIDIA GeForce RTX 4060 Laptop GPU +0x10DE; 0x28E1; medium; #NVIDIA; NVIDIA GeForce RTX 4050 Laptop GPU +0x10DE; 0x67DF; verylow; #NVIDIA; NVIDIA GeForce GTX 765M +0x10DE; 0xFC0; verylow; #NVIDIA; GeForce GT 640 +0x10DE; 0xFC1; verylow; #NVIDIA; GeForce GT 640 +0x10DE; 0xFC2; verylow; #NVIDIA; GeForce GT 630 +0x10DE; 0xFC6; verylow; #NVIDIA; GeForce GT 740 +0x10DE; 0xFC8; verylow; #NVIDIA; GeForce GT 740 +0x10DE; 0xFCD; verylow; #NVIDIA; GeForce GT 755M +0x10DE; 0xFD1; verylow; #NVIDIA; GeForce GT 650M +0x10DE; 0xFD2; verylow; #NVIDIA; GeForce GT 640M +0x10DE; 0xFD3; verylow; #NVIDIA; GeForce GT 640M LE +0x10DE; 0xFD4; verylow; #NVIDIA; GeForce GTX 660M +0x10DE; 0xFD9; verylow; #NVIDIA; GeForce GT 645M +0x10DE; 0xFDF; verylow; #NVIDIA; GeForce GT 740M +0x10DE; 0xFE1; verylow; #NVIDIA; GeForce GT 730M +0x10DE; 0xFE3; verylow; #NVIDIA; GeForce GT 745M +0x10DE; 0xFE4; verylow; #NVIDIA; GeForce GT 750M +0x10DE; 0xFE9; verylow; #NVIDIA; GeForce GT 750M +0x10DE; 0xFF3; verylow; #NVIDIA; Quadro K420 +0x10DE; 0xFF6; verylow; #NVIDIA; Quadro K1100M +0x10DE; 0xFFA; verylow; #NVIDIA; Quadro K600 +0x10DE; 0xFFB; verylow; #NVIDIA; Quadro K2000M +0x10DE; 0xFFC; verylow; #NVIDIA; Quadro K1000M +0x10DE; 0xFFE; verylow; #NVIDIA; K2000 +0x10DE; 0xFFF; verylow; #NVIDIA; NVIDIA Quadro 410 + +#qualcomm +0x5143; 0x6030500; UNDEFINED; #Qualcomm; Adreno 7c+ Gen 3 +0x5143; 0x6080001; UNDEFINED; #Qualcomm; Qualcomm(R) Adreno(TM) 640 GPU +0x5143; 0x6090000; UNDEFINED; #Qualcomm; Adreno (TM) 690 +0x5143; 0x7030002; UNDEFINED; #Qualcomm; Turnip Adreno (TM) 725 + +END_GPU_LIST; + diff --git a/cmake/HPLUtils.cmake b/cmake/HPLUtils.cmake new file mode 100644 index 000000000..4dcd1ca49 --- /dev/null +++ b/cmake/HPLUtils.cmake @@ -0,0 +1,14 @@ +macro(hpl_set_output_dir name dir) + foreach (OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES}) + string(TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIGUPPERCASE) + set_target_properties(${name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIGUPPERCASE} ${CMAKE_HOME_DIRECTORY}/build/${OUTPUTCONFIG}/${dir}) + set_target_properties(${name} PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${OUTPUTCONFIGUPPERCASE} ${CMAKE_HOME_DIRECTORY}/build/${OUTPUTCONFIG}/${dir}) + set_target_properties(${name} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIGUPPERCASE} ${CMAKE_HOME_DIRECTORY}/build/${OUTPUTCONFIG}/${dir}) + endforeach() + + set_target_properties(${name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_HOME_DIRECTORY}/build/${dir}) + set_target_properties(${name} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_HOME_DIRECTORY}/build/${dir}) + set_target_properties(${name} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_HOME_DIRECTORY}/build/${dir}) +endmacro() + + diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 253a7f37d..2b6f4fcad 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -7,39 +7,19 @@ add_subdirectory(AngelScript) set(THE_FORGE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/The-Forge" CACHE STRING "Location of the forge.") -# file(GLOB EASTL_SOURCES -# ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/EASTL/*.cpp) -# add_library(Eastl STATIC ${EASTL_SOURCES}) - add_library(cpu_features OBJECT ${THE_FORGE_DIR}/Common_3/OS/ThirdParty/OpenSource/cpu_features/src/impl_x86_macos.c ${THE_FORGE_DIR}/Common_3/OS/ThirdParty/OpenSource/cpu_features/src/impl_aarch64_iOS.c ${THE_FORGE_DIR}/Common_3/OS/ThirdParty/OpenSource/cpu_features/src/impl_x86_windows.c + ${THE_FORGE_DIR}/Common_3/OS/ThirdParty/OpenSource/cpu_features/src/impl_x86_linux_or_android.c ) - -file(GLOB BASIS_UNVERSAL_SOURCES - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/*.c - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/transcoder/*.cpp - #${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/*.cpp\ - - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_astc_decomp.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_backend.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_basis_file.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_comp.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_enc.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_etc.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_frontend.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_global_selector_palette_helpers.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_gpu_texture.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_pvrtc1_4.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_resampler.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_resample_filters.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/basisu_ssim.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/lodepng.cpp -) -add_library(basis_universal STATIC ${BASIS_UNVERSAL_SOURCES}) -target_include_directories(basis_universal PUBLIC ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal) +#file(GLOB BASIS_UNVERSAL_SOURCES +# ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/*.c +# ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal/transcoder/*.cpp +#) +#add_library(basis_universal STATIC ${BASIS_UNVERSAL_SOURCES}) +#target_include_directories(basis_universal PUBLIC ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/basis_universal) add_library(ags SHARED IMPORTED IMPORTED GLOBAL) set_property(TARGET ags PROPERTY IMPORTED_LOCATION @@ -55,43 +35,31 @@ target_include_directories(ags INTERFACE ${THE_FORGE_DIR}/Common_3/Graphics/Thi # ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/TinyEXR) -add_library(astc-encoder OBJECT - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenccli_error_metrics.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenccli_image.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenccli_image_external.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenccli_image_load_store.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenccli_platform_dependents.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_averages_and_directions.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_block_sizes.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_color_quantize.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_color_unquantize.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_compress_symbolic.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_compute_variance.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_decompress_symbolic.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_diagnostic_trace.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_entry.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_find_best_partitioning.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_ideal_endpoints_and_weights.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_image.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_integer_sequence.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_mathlib.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_mathlib_softfloat.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_partition_tables.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_percentile_tables.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_pick_best_endpoint_format.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_platform_isa_detection.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_quantization.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_symbolic_physical.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_weight_align.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/astcenc_weight_quant_xfer_tables.cpp - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/wuffs-v0.3.c - - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/TinyEXR/miniz.c +# add_library(astc-encoder OBJECT +# ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/*.c +# ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/astc-encoder/Source/*.cpp +# ) +# target_include_directories(astc-encoder PRIVATE +# ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/TinyEXR) +# target_include_directories(astc-encoder PUBLIC ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/zip) + add_library(lz4 OBJECT + ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/lz4/lz4.c + ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/lz4/lz4hc.c + ) + target_include_directories(lz4 PUBLIC + ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/lz4) + +file(GLOB ZSTD_FILESYSTEM_SOURCES + ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/zstd/common/*.c + ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/zstd/compress/*.c + ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/zstd/decompress/*.c + ) -target_include_directories(astc-encoder PRIVATE - ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/TinyEXR) -target_include_directories(astc-encoder PUBLIC ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/zip) - +if(CMAKE_SYSTEM_NAME MATCHES "Linux") + list(APPEND ZSTD_FILESYSTEM_SOURCES ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/zstd/decompress/huf_decompress_amd64.S) +endif() +add_library(zstd_filesystem OBJECT ${ZSTD_FILESYSTEM_SOURCES}) +target_include_directories(zstd_filesystem PUBLIC ${THE_FORGE_DIR}/Common_3/Utilities/ThirdParty/OpenSource/zstd) # VulkanMemoryAllocator add_library(VulkanMemoryAllocator INTERFACE) @@ -129,9 +97,9 @@ target_include_directories(tinyimageformat INTERFACE #add_library(ozz-animation STATIC ${OZZ_ANIMATION_SOURCES}) #target_include_directories(ozz-animation PUBLIC ${THE_FORGE_DIR}/Common_3/Resources/AnimationSystem/ThirdParty/OpenSource/ozz-animation/include) -file(GLOB MESH_OPTIMIZER_SOURCES ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/meshoptimizer/src/*.cpp) -add_library(meshoptimizer STATIC ${MESH_OPTIMIZER_SOURCES}) -target_include_directories(meshoptimizer PUBLIC ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/meshoptimizer/src) +#file(GLOB MESH_OPTIMIZER_SOURCES ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/meshoptimizer/src/*.cpp) +#add_library(meshoptimizer STATIC ${MESH_OPTIMIZER_SOURCES}) +#target_include_directories(meshoptimizer PUBLIC ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/meshoptimizer/src) add_library(tinydds INTERFACE) target_include_directories(tinydds INTERFACE @@ -141,40 +109,39 @@ add_library(tinyktx INTERFACE) target_include_directories(tinyktx INTERFACE ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/ThirdParty/OpenSource/tinyktx) -# ga input -file(GLOB GAINPUT_SOURCES - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/*.cpp - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/builtin/*.cpp - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/dev/*.cpp - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/gestures/*.cpp - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/keyboard/*.cpp - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/mouse/*.cpp - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/pad/*.cpp - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/recorder/*.cpp - ) - -if(CMAKE_SYSTEM_NAME MATCHES "Darwin") - file(GLOB GAINPUT_SOURCES_MACOS - ${THE_FORGE_DIR}/Common_3/Application/ThirdParts/OpenSource/gainput/lib/source/hidapi/mac/*.c - ${THE_FORGE_DIR}/Common_3/Application/ThirdParts/OpenSource/gainput/lib/source/gainput/*.mm) - list(APPEND GAINPUT_SOURCES ${GAINPUT_SOURCES_MACOS}) -elseif(CMAKE_SYSTEM_NAME MATCHES "Windows") - file(GLOB GAINPUT_SOURCES_WINDOWS - ${THE_FORGE_DIR}/Common_3/Application/ThirdParts/OpenSource/gainput/lib/source/hidapi/windows/*.c - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/hid/*.cpp - ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/hid/hidparsers/*.cpp - ) - list(APPEND GAINPUT_SOURCES ${GAINPUT_SOURCES_WINDOWS}) -elseif(CMAKE_SYSTEM_NAME MATCHES "Linux") - file(GLOB GAINPUT_SOURCES_LINUX - ${THE_FORGE_DIR}/Common_3/Application/ThirdParts/OpenSource/gainput/lib/source/hidapi/linux/*.c) - list(APPEND GAINPUT_SOURCES ${GAINPUT_SOURCES_LINUX}) -endif() - -add_library(ga STATIC ${GAINPUT_SOURCES}) -target_include_directories(ga PUBLIC ${THE_FORGE_DIR}/Common_3/ThirdParty/OpenSource/lua) - +# # ga input +# file(GLOB GAINPUT_SOURCES +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/*.cpp +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/builtin/*.cpp +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/dev/*.cpp +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/gestures/*.cpp +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/keyboard/*.cpp +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/mouse/*.cpp +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/pad/*.cpp +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/recorder/*.cpp +# ) +# +# if(CMAKE_SYSTEM_NAME MATCHES "Darwin") +# file(GLOB GAINPUT_SOURCES_MACOS +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParts/OpenSource/gainput/lib/source/hidapi/mac/*.c +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParts/OpenSource/gainput/lib/source/gainput/*.mm) +# list(APPEND GAINPUT_SOURCES ${GAINPUT_SOURCES_MACOS}) +# elseif(CMAKE_SYSTEM_NAME MATCHES "Windows") +# file(GLOB GAINPUT_SOURCES_WINDOWS +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParts/OpenSource/gainput/lib/source/hidapi/windows/*.c +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/hid/*.cpp +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParty/OpenSource/gainput/lib/source/gainput/hid/hidparsers/*.cpp +# ) +# list(APPEND GAINPUT_SOURCES ${GAINPUT_SOURCES_WINDOWS}) +# elseif(CMAKE_SYSTEM_NAME MATCHES "Linux") +# file(GLOB GAINPUT_SOURCES_LINUX +# ${THE_FORGE_DIR}/Common_3/Application/ThirdParts/OpenSource/gainput/lib/source/hidapi/linux/*.c) +# list(APPEND GAINPUT_SOURCES ${GAINPUT_SOURCES_LINUX}) +# endif() +# +# add_library(ga STATIC ${GAINPUT_SOURCES}) +# target_include_directories(ga PUBLIC ${THE_FORGE_DIR}/Common_3/ThirdParty/OpenSource/lua) file(GLOB THE_FORGE_SOURCES ${THE_FORGE_DIR}/Common_3/Graphics/*.cpp @@ -188,24 +155,27 @@ file(GLOB THE_FORGE_SOURCES ${THE_FORGE_DIR}/Common_3/Resources/ResourceLoader/*.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/FileSystem/FileSystem.cpp - ${THE_FORGE_DIR}/Common_3/Utilities/FileSystem/SystemRun.cpp + ${THE_FORGE_DIR}/Common_3/Utilities/FileSystem/FileSystem.c + ${THE_FORGE_DIR}/Common_3/Utilities/FileSystem/SystemRun.c ${THE_FORGE_DIR}/Common_3/Utilities/Log/*.c ${THE_FORGE_DIR}/Common_3/Utilities/Math/*.c ${THE_FORGE_DIR}/Common_3/Utilities/MemoryTracking/*.c ${THE_FORGE_DIR}/Common_3/Utilities/Threading/*.c ${THE_FORGE_DIR}/Common_3/Utilities/*.c + + ${THE_FORGE_DIR}/Common_3/Renderer/ShaderServer/Network.c + ${THE_FORGE_DIR}/Common_3/Renderer/ShaderServer/ShaderServer.cpp ${THE_FORGE_DIR}/Common_3/Application/InputSystem.cpp - ${THE_FORGE_DIR}/Common_3/Game/Scripting/*.cpp + # ${THE_FORGE_DIR}/Common_3/Game/Scripting/*.cpp ) # volk add_library(volk STATIC ${THE_FORGE_DIR}/Common_3/Graphics/ThirdParty/OpenSource/volk/volk.c) if(WIN32) - target_include_directories(volk PUBLIC ${THE_FORGE_DIR}/Common_3/Graphics/ThirdParty/OpenSource/Vulkan-Headers) + target_include_directories(volk PUBLIC ${THE_FORGE_DIR}/Common_3/Graphics/ThirdParty/OpenSource/VulkanSDK/include) endif() target_include_directories(volk PUBLIC ${THE_FORGE_DIR}/Common_3/Graphics/ThirdParty/OpenSource/volk) @@ -221,7 +191,10 @@ target_include_directories(imgui PUBLIC ${THE_FORGE_DIR}/Common_3/ThirdParty/Ope add_library(TheForge STATIC ${THE_FORGE_SOURCES}) -target_link_libraries(TheForge PUBLIC cpu_features imgui astc-encoder cgltf Bstr basis_universal meshoptimizer tinydds tinyimageformat tinyktx ga) +target_compile_definitions( + TheForge PRIVATE -DSTB_TRUETYPE_IMPLEMENTATION +) +target_link_libraries(TheForge PUBLIC cpu_features imgui cgltf Bstr lz4 zstd_filesystem tinydds tinyimageformat tinyktx) target_include_directories(TheForge PUBLIC ${THE_FORGE_DIR}) IF(CMAKE_SYSTEM_NAME MATCHES "Darwin") @@ -241,7 +214,7 @@ elseif(CMAKE_SYSTEM_NAME MATCHES "Linux") file(GLOB THE_FORGE_OS_LINUX_SOURCES ${THE_FORGE_DIR}/Common_3/OS/Linux/*.cpp ${THE_FORGE_DIR}/Common_3/OS/Linux/*.c - ${THE_FORGE_DIR}/Common_3/Utilities/FileSystem/UnixFileSystem.cpp) + ${THE_FORGE_DIR}/Common_3/Utilities/FileSystem/UnixFileSystem.c) target_sources(TheForge PRIVATE ${THE_FORGE_OS_LINUX_SOURCES}) pkg_check_modules(GTK REQUIRED gtk+-3.0) @@ -269,7 +242,6 @@ set_property(TARGET DirectXShaderCompiler PROPERTY IMPORTED_LOCATION set_property(TARGET DirectXShaderCompiler PROPERTY IMPORTED_IMPLIB ${THE_FORGE_DIR}/Common_3/Graphics/ThirdParty/OpenSource/DirectXShaderCompiler/lib/x64/dxcompiler.lib) - # Nvapi add_library(Nvapi STATIC IMPORTED) set_property(TARGET Nvapi PROPERTY IMPORTED_LOCATION @@ -278,24 +250,22 @@ set_property(TARGET Nvapi PROPERTY IMPORTED_LOCATION if(CMAKE_SYSTEM_NAME MATCHES "Windows") file(GLOB GRAPHICS_D3D12_SOURCE - "${THE_FORGE_DIR}/Common_3/Graphics/Direct3D12/*.cpp") + "${THE_FORGE_DIR}/Common_3/Graphics/Direct3D12/*.cpp" + "${THE_FORGE_DIR}/Common_3/Graphics/Direct3D11/*.cpp" + ) target_sources(TheForge PRIVATE ${GRAPHICS_D3D12_SOURCE}) + target_include_directories(TheForge PRIVATE ${THE_FORGE_DIR}/Common_3/Graphics/ThirdParty/OpenSource/D3D12MemoryAllocator) target_link_libraries(TheForge PRIVATE Nvapi ags) - file(GLOB GRAPHICS_D3D11_SOURCE "${THE_FORGE_DIR}/Common_3/Graphics/Direct3D11/*.cpp") - target_sources(TheForge PRIVATE ${GRAPHICS_D3D11_SOURCE}) + #file(GLOB GRAPHICS_D3D11_SOURCE "${THE_FORGE_DIR}/Common_3/Graphics/Direct3D11/*.cpp") + #target_sources(TheForge PRIVATE ${GRAPHICS_D3D11_SOURCE}) + # "dxguid.lib" target_link_libraries(TheForge PRIVATE DirectXShaderCompiler "d3d11.lib") target_link_libraries(TheForge PRIVATE WinPixEventRuntime) endif() - - -set(HPL_3RDPARTY_TARGETS - Newton - AngelScript - OALWrapper - TheForge -) - +if(CMAKE_SYSTEM_NAME MATCHES "Linux") + find_package(X11 REQUIRED) + target_link_libraries(TheForge PRIVATE X11 X11::Xrandr) +endif() SET(FSL_COMPILER "${THE_FORGE_DIR}/Common_3/Tools/ForgeShadingLanguage/fsl.py" PARENT_SCOPE) -set(_HPL_3RDPARTY_TARGETS_ ${HPL_3RDPARTY_TARGETS} PARENT_SCOPE) diff --git a/external/The-Forge b/external/The-Forge index d652ccdb3..6acb18d1c 160000 --- a/external/The-Forge +++ b/external/The-Forge @@ -1 +1 @@ -Subproject commit d652ccdb321666b286753f5cb2a2fc81354ac739 +Subproject commit 6acb18d1cae3064f7ba812066a7f1f804eaea2aa diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index c2d05b747..e374dc489 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -22,6 +22,7 @@ function(AddToolTarget target) if(APPLE) PostBuildMacBundle(${target} "${HPL2_FRAMEWORKS}" "${HPL2_LIBRARIES}") endif() + hpl_set_output_dir(${target} "") endfunction() @@ -63,6 +64,7 @@ AddToolTarget(ParticleViewer add_executable(MshConverter mshconverter/MshConverter.cpp ) +hpl_set_output_dir(MshConverter "") # Hack to copy resources for tools install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/resources/" diff --git a/tools/editors/common/EditorViewport.cpp b/tools/editors/common/EditorViewport.cpp index 5eddd7b78..622622382 100644 --- a/tools/editors/common/EditorViewport.cpp +++ b/tools/editors/common/EditorViewport.cpp @@ -834,25 +834,21 @@ void iEditorViewport::UpdateViewport() return; auto forgeRenderer = Interface::Get(); - SharedRenderTarget target; - target.Load(forgeRenderer->Rend(), [&](RenderTarget** target) { - ClearValue optimizedColorClearBlack = { { 0.0f, 0.0f, 0.0f, 0.0f } }; - RenderTargetDesc renderTargetDesc = {}; - renderTargetDesc.mArraySize = 1; - renderTargetDesc.mClearValue = optimizedColorClearBlack; - renderTargetDesc.mDepth = 1; - renderTargetDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; - renderTargetDesc.mWidth = mpEngineViewport->GetSize().x; - renderTargetDesc.mHeight = mpEngineViewport->GetSize().y; - renderTargetDesc.mSampleCount = SAMPLE_COUNT_1; - renderTargetDesc.mSampleQuality = 0; - renderTargetDesc.mStartState = RESOURCE_STATE_SHADER_RESOURCE; - renderTargetDesc.mFormat = TinyImageFormat_R8G8B8A8_UNORM; - renderTargetDesc.mDescriptors = DESCRIPTOR_TYPE_RW_TEXTURE | DESCRIPTOR_TYPE_TEXTURE; - addRenderTarget(forgeRenderer->Rend(), &renderTargetDesc, target); - return true; - }); - mpEngineViewport->SetTarget(std::move(target)); + ClearValue optimizedColorClearBlack = { { 0.0f, 0.0f, 0.0f, 0.0f } }; + RenderTargetDesc renderTargetDesc = {}; + renderTargetDesc.mArraySize = 1; + renderTargetDesc.mClearValue = optimizedColorClearBlack; + renderTargetDesc.mDepth = 1; + renderTargetDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; + renderTargetDesc.mWidth = mpEngineViewport->GetSize().x; + renderTargetDesc.mHeight = mpEngineViewport->GetSize().y; + renderTargetDesc.mSampleCount = SAMPLE_COUNT_1; + renderTargetDesc.mSampleQuality = 0; + renderTargetDesc.mStartState = RESOURCE_STATE_SHADER_RESOURCE; + renderTargetDesc.mFormat = TinyImageFormat_R8G8B8A8_UNORM; + renderTargetDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE; + + mpEngineViewport->InitializeTarget(forgeRenderer->Rend(), renderTargetDesc); cGui* pGui = mpGuiSet->GetGui(); //////////////////////////////////////////// @@ -860,7 +856,7 @@ void iEditorViewport::UpdateViewport() cGuiGfxElement* pImg = mpImgViewport->GetImage(); if(pImg) pGui->DestroyGfx(pImg); - pImg = pGui->CreateGfxTexture(mpEngineViewport->GetImage().get(), false, eGuiMaterial_Diffuse, cColor(1,1), true, cVector2f(0,0), cVector2f(1,1), false); + pImg = pGui->CreateGfxTexture(mpEngineViewport, false, eGuiMaterial_Diffuse, cColor(1,1), true, cVector2f(0,0), cVector2f(1,1), false); mpImgViewport->SetImage(pImg); mbViewportNeedsUpdate = false; @@ -931,8 +927,8 @@ void iEditorViewport::SetEngineViewportSize(const cVector2l& avSize) mvEngineViewportSize = avSize; mpEngineViewport->SetSize(mvEngineViewportSize); - auto& image = mpEngineViewport->GetImage(); - const cVector2l vFBSize = cVector2l(image->GetWidth(), image->GetHeight()); + auto size = mpEngineViewport->GetSizeU2(); + const cVector2l vFBSize = cVector2l(size.x, size.y); mvUVSize = cVector2f((float)mvEngineViewportSize.x, (float)mvEngineViewportSize.y) / cVector2f((float)vFBSize.x, (float)vFBSize.y); diff --git a/tools/editors/modeleditor/ModelEditorWindowPhysicsTest.cpp b/tools/editors/modeleditor/ModelEditorWindowPhysicsTest.cpp index 1a645c3d6..d43d9333f 100644 --- a/tools/editors/modeleditor/ModelEditorWindowPhysicsTest.cpp +++ b/tools/editors/modeleditor/ModelEditorWindowPhysicsTest.cpp @@ -474,12 +474,9 @@ void cModelEditorWindowPhysicsTest::OnInitLayout() mpInpBuoyancyAngularViscosity->SetValue(mfBuoyancyAngularViscosity, false); mpInpBuoyancyLinearViscosity->SetValue(mfBuoyancyLinearViscosity, false); - auto& target = mpEngineViewport->Target(); - if(target.IsValid()) { - SetEngineViewportPositionAndSize(0,cVector2l( - target.m_handle->mWidth, target.m_handle->mHeight)); - } - CreateGuiViewport(mpBGFrame); + auto size= mpEngineViewport->GetSizeU2(); + SetEngineViewportPositionAndSize(0, cVector2l(size.x, size.y)); + CreateGuiViewport(mpBGFrame); SetGuiViewportPos(cVector3f(2,55,0.1f)); SetGuiViewportSize(cVector2f(mpBGFrame->GetSize() - cVector2f(4,58))); UpdateViewport(); diff --git a/vcpkg b/vcpkg index 5c82f7e63..6e31ee33c 160000 --- a/vcpkg +++ b/vcpkg @@ -1 +1 @@ -Subproject commit 5c82f7e6372c9b0ea25e1fd829dd50235ef37629 +Subproject commit 6e31ee33cc9fc93599c4ceb38e229098cf339bb7