diff --git a/HelloTexturedCube/HelloTexturedCube.vcxproj b/HelloTexturedCube/HelloTexturedCube.vcxproj index e0896e5..fd78064 100644 --- a/HelloTexturedCube/HelloTexturedCube.vcxproj +++ b/HelloTexturedCube/HelloTexturedCube.vcxproj @@ -45,23 +45,23 @@ - 16.0 + 17.0 Win32Proj {26bd6e61-e36d-464a-a312-4110adf10083} HelloTexturedCube - 10.0.20348.0 + 10.0.22000.0 Application true - v142 + v143 Unicode Application false - v142 + v143 true Unicode @@ -79,12 +79,6 @@ - - true - - - false - Level3 @@ -93,6 +87,7 @@ true Use pch.h + stdcpp20 Windows @@ -113,6 +108,7 @@ xcopy /y $(ProjectDir)src\HelloTexturedCube.dds $(OutDir)Data\Textures\true Use pch.h + stdcpp20 Windows diff --git a/HelloTexturedCube/src/HelloTexturedCubeGame.h b/HelloTexturedCube/src/HelloTexturedCubeGame.h index 1318372..9409771 100644 --- a/HelloTexturedCube/src/HelloTexturedCubeGame.h +++ b/HelloTexturedCube/src/HelloTexturedCubeGame.h @@ -1,55 +1,52 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class HelloTexturedCubeGame : public Singleton, public BaseGame { - class HelloTexturedCubeGame : public Singleton, public BaseGame + struct Vertex { - struct Vertex - { - float _x, _y, _z; - UINT32 _color; - }; - VERUS_TYPEDEFS(Vertex); - - VERUS_UBUFFER_STRUCT UB_ShaderVS - { - mataff _matW; - matrix _matVP; - }; - - VERUS_UBUFFER_STRUCT UB_ShaderFS - { - float _phase; - }; - - Vector3 _rotation = Vector3(0); - CGI::GeometryPwn _geo; - CGI::ShaderPwn _shader; - CGI::PipelinePwn _pipe; - CGI::TexturePwn _tex; - CSZ _shaderCode; - CGI::CSHandle _csh; // Complex set handle. Simple set has one uniform buffer. Complex set additionally has textures. - UB_ShaderVS _ubShaderVS; - UB_ShaderFS _ubShaderFS; - int _vertCount = 0; - int _indexCount = 0; - - public: - HelloTexturedCubeGame(); - ~HelloTexturedCubeGame(); - - virtual void BaseGame_UpdateSettings(App::Window::RDesc windowDesc) override; - virtual void BaseGame_LoadContent() override; - virtual void BaseGame_UnloadContent() override; - virtual void BaseGame_Update() override; - virtual void BaseGame_Draw() override; - virtual void BaseGame_DrawView(CGI::RcViewDesc viewDesc) override; + float _x, _y, _z; + UINT32 _color; }; - VERUS_TYPEDEFS(HelloTexturedCubeGame); - } + VERUS_TYPEDEFS(Vertex); + + VERUS_UBUFFER_STRUCT UB_ShaderVS + { + mataff _matW; + matrix _matVP; + }; + + VERUS_UBUFFER_STRUCT UB_ShaderFS + { + float _phase; + }; + + Vector3 _rotation = Vector3(0); + CGI::GeometryPwn _geo; + CGI::ShaderPwn _shader; + CGI::PipelinePwn _pipe; + CGI::TexturePwn _tex; + CSZ _shaderCode; + CGI::CSHandle _csh; // Complex set handle. Simple set has one uniform buffer. Complex set additionally has textures. + UB_ShaderVS _ubShaderVS; + UB_ShaderFS _ubShaderFS; + int _vertCount = 0; + int _indexCount = 0; + + public: + HelloTexturedCubeGame(); + ~HelloTexturedCubeGame(); + + virtual void BaseGame_UpdateSettings(App::Window::RDesc windowDesc) override; + virtual void BaseGame_LoadContent() override; + virtual void BaseGame_UnloadContent() override; + virtual void BaseGame_Update() override; + virtual void BaseGame_Draw() override; + virtual void BaseGame_DrawView(CGI::RcViewDesc viewDesc) override; + }; + VERUS_TYPEDEFS(HelloTexturedCubeGame); } #define VERUS_QREF_GAME Game::RHelloTexturedCubeGame game = Game::HelloTexturedCubeGame::I() diff --git a/HelloTriangle/HelloTriangle.vcxproj b/HelloTriangle/HelloTriangle.vcxproj index 38b5e84..ff2a6a8 100644 --- a/HelloTriangle/HelloTriangle.vcxproj +++ b/HelloTriangle/HelloTriangle.vcxproj @@ -45,23 +45,23 @@ - 16.0 + 17.0 Win32Proj {bc17acd3-97eb-4d5c-a2c9-574cdaa7576b} HelloTriangle - 10.0.20348.0 + 10.0.22000.0 Application true - v142 + v143 Unicode Application false - v142 + v143 true Unicode @@ -79,12 +79,6 @@ - - true - - - false - Level3 @@ -93,6 +87,7 @@ true Use pch.h + stdcpp20 Windows @@ -109,6 +104,7 @@ true Use pch.h + stdcpp20 Windows diff --git a/HelloTriangle/src/HelloTriangleGame.h b/HelloTriangle/src/HelloTriangleGame.h index 8787cba..39d9ccd 100644 --- a/HelloTriangle/src/HelloTriangleGame.h +++ b/HelloTriangle/src/HelloTriangleGame.h @@ -1,55 +1,52 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + // Epigraph + // "Vulkan – (it takes) 1000 lines to draw a triangle" + // "- I thought you only needed 3 lines to draw a triangle" + // https://www.reddit.com/r/linux/comments/58fyqn/vulkan_1000_lines_to_draw_a_triangle/ + + class HelloTriangleGame : public Singleton, public BaseGame { - // Epigraph - // "Vulkan – (it takes) 1000 lines to draw a triangle" - // "- I thought you only needed 3 lines to draw a triangle" - // https://www.reddit.com/r/linux/comments/58fyqn/vulkan_1000_lines_to_draw_a_triangle/ - - class HelloTriangleGame : public Singleton, public BaseGame + struct Vertex { - struct Vertex - { - float _x, _y, _z; - UINT32 _color; - }; - VERUS_TYPEDEFS(Vertex); - - VERUS_UBUFFER_STRUCT UB_ShaderVS - { - matrix _matWVP; - }; - - VERUS_UBUFFER_STRUCT UB_ShaderFS - { - float _phase; - }; - - CGI::GeometryPwn _geo; - CGI::ShaderPwn _shader; - CGI::PipelinePwn _pipe; - CSZ _shaderCode; - UB_ShaderVS _ubShaderVS; - UB_ShaderFS _ubShaderFS; - int _vertCount = 0; - - public: - HelloTriangleGame(); - ~HelloTriangleGame(); - - virtual void BaseGame_UpdateSettings(App::Window::RDesc windowDesc) override; - virtual void BaseGame_LoadContent() override; - virtual void BaseGame_UnloadContent() override; - virtual void BaseGame_Update() override; - virtual void BaseGame_Draw() override; - virtual void BaseGame_DrawView(CGI::RcViewDesc viewDesc) override; + float _x, _y, _z; + UINT32 _color; }; - VERUS_TYPEDEFS(HelloTriangleGame); - } + VERUS_TYPEDEFS(Vertex); + + VERUS_UBUFFER_STRUCT UB_ShaderVS + { + matrix _matWVP; + }; + + VERUS_UBUFFER_STRUCT UB_ShaderFS + { + float _phase; + }; + + CGI::GeometryPwn _geo; + CGI::ShaderPwn _shader; + CGI::PipelinePwn _pipe; + CSZ _shaderCode; + UB_ShaderVS _ubShaderVS; + UB_ShaderFS _ubShaderFS; + int _vertCount = 0; + + public: + HelloTriangleGame(); + ~HelloTriangleGame(); + + virtual void BaseGame_UpdateSettings(App::Window::RDesc windowDesc) override; + virtual void BaseGame_LoadContent() override; + virtual void BaseGame_UnloadContent() override; + virtual void BaseGame_Update() override; + virtual void BaseGame_Draw() override; + virtual void BaseGame_DrawView(CGI::RcViewDesc viewDesc) override; + }; + VERUS_TYPEDEFS(HelloTriangleGame); } #define VERUS_QREF_GAME Game::RHelloTriangleGame game = Game::HelloTriangleGame::I() diff --git a/PAKBuilder/PAKBuilder.vcxproj b/PAKBuilder/PAKBuilder.vcxproj index 6c1b5ac..b8e12c8 100644 --- a/PAKBuilder/PAKBuilder.vcxproj +++ b/PAKBuilder/PAKBuilder.vcxproj @@ -11,23 +11,23 @@ - 16.0 + 17.0 Win32Proj {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57} PAKBuilder - 10.0.20348.0 + 10.0.22000.0 Application true - v142 + v143 Unicode Application false - v142 + v143 true Unicode @@ -45,18 +45,13 @@ - - true - - - false - Level3 true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true + stdcpp20 Console @@ -71,6 +66,7 @@ true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true + stdcpp20 Console diff --git a/RendererDirect3D11/RendererDirect3D11.vcxproj b/RendererDirect3D11/RendererDirect3D11.vcxproj index 87d0d84..a818c74 100644 --- a/RendererDirect3D11/RendererDirect3D11.vcxproj +++ b/RendererDirect3D11/RendererDirect3D11.vcxproj @@ -11,23 +11,23 @@ - 16.0 + 17.0 Win32Proj {8269dcce-e226-46e4-b9f6-290ab5df2678} RendererDirect3D11 - 10.0.20348.0 + 10.0.22000.0 DynamicLibrary true - v142 + v143 Unicode DynamicLibrary false - v142 + v143 true Unicode @@ -45,12 +45,6 @@ - - true - - - false - Level3 @@ -61,6 +55,7 @@ pch.h Fast $(ProjectDir)src;%(AdditionalIncludeDirectories) + stdcpp20 Windows @@ -80,6 +75,7 @@ pch.h Fast $(ProjectDir)src;%(AdditionalIncludeDirectories) + stdcpp20 Windows diff --git a/RendererDirect3D11/src/CGI/CommandBufferD3D11.h b/RendererDirect3D11/src/CGI/CommandBufferD3D11.h index 8af1185..ba58ffa 100644 --- a/RendererDirect3D11/src/CGI/CommandBufferD3D11.h +++ b/RendererDirect3D11/src/CGI/CommandBufferD3D11.h @@ -1,65 +1,62 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class CommandBufferD3D11 : public BaseCommandBuffer { - class CommandBufferD3D11 : public BaseCommandBuffer - { - ComPtr _pDeviceContext; - RP::PcD3DRenderPass _pRenderPass = nullptr; - RP::PcD3DFramebuffer _pFramebuffer = nullptr; - Vector _vClearValues; - int _subpassIndex = 0; - float _blendFactor[4]; + ComPtr _pDeviceContext; + RP::PcD3DRenderPass _pRenderPass = nullptr; + RP::PcD3DFramebuffer _pFramebuffer = nullptr; + Vector _vClearValues; + int _subpassIndex = 0; + float _blendFactor[4]; - public: - CommandBufferD3D11(); - virtual ~CommandBufferD3D11() override; + public: + CommandBufferD3D11(); + virtual ~CommandBufferD3D11() override; - virtual void Init() override; - virtual void Done() override; + virtual void Init() override; + virtual void Done() override; - virtual void InitOneTimeSubmit() override; - virtual void DoneOneTimeSubmit() override; + virtual void InitOneTimeSubmit() override; + virtual void DoneOneTimeSubmit() override; - virtual void Begin() override; - virtual void End() override; + virtual void Begin() override; + virtual void End() override; - virtual void PipelineImageMemoryBarrier(TexturePtr tex, ImageLayout oldLayout, ImageLayout newLayout, Range mipLevels, Range arrayLayers) override; + virtual void PipelineImageMemoryBarrier(TexturePtr tex, ImageLayout oldLayout, ImageLayout newLayout, Range mipLevels, Range arrayLayers) override; - virtual void BeginRenderPass(RPHandle renderPassHandle, FBHandle framebufferHandle, - std::initializer_list ilClearValues, ViewportScissorFlags vsf) override; - virtual void NextSubpass() override; - virtual void EndRenderPass() override; + virtual void BeginRenderPass(RPHandle renderPassHandle, FBHandle framebufferHandle, + std::initializer_list ilClearValues, ViewportScissorFlags vsf) override; + virtual void NextSubpass() override; + virtual void EndRenderPass() override; - virtual void BindPipeline(PipelinePtr pipe) override; - virtual void SetViewport(std::initializer_list il, float minDepth, float maxDepth) override; - virtual void SetScissor(std::initializer_list il) override; - virtual void SetBlendConstants(const float* p) override; + virtual void BindPipeline(PipelinePtr pipe) override; + virtual void SetViewport(std::initializer_list il, float minDepth, float maxDepth) override; + virtual void SetScissor(std::initializer_list il) override; + virtual void SetBlendConstants(const float* p) override; - virtual void BindVertexBuffers(GeometryPtr geo, UINT32 bindingsFilter) override; - virtual void BindIndexBuffer(GeometryPtr geo) override; + virtual void BindVertexBuffers(GeometryPtr geo, UINT32 bindingsFilter) override; + virtual void BindIndexBuffer(GeometryPtr geo) override; - virtual bool BindDescriptors(ShaderPtr shader, int setNumber, CSHandle complexSetHandle) override; - virtual bool BindDescriptors(ShaderPtr shader, int setNumber, GeometryPtr geo, int sbIndex) override; - virtual void PushConstants(ShaderPtr shader, int offset, int size, const void* p, ShaderStageFlags stageFlags) override; + virtual bool BindDescriptors(ShaderPtr shader, int setNumber, CSHandle complexSetHandle) override; + virtual bool BindDescriptors(ShaderPtr shader, int setNumber, GeometryPtr geo, int sbIndex) override; + virtual void PushConstants(ShaderPtr shader, int offset, int size, const void* p, ShaderStageFlags stageFlags) override; - virtual void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) override; - virtual void DrawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) override; - virtual void Dispatch(int groupCountX, int groupCountY, int groupCountZ) override; - virtual void DispatchMesh(int groupCountX, int groupCountY, int groupCountZ) override; - virtual void TraceRays(int width, int height, int depth) override; + virtual void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) override; + virtual void DrawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) override; + virtual void Dispatch(int groupCountX, int groupCountY, int groupCountZ) override; + virtual void DispatchMesh(int groupCountX, int groupCountY, int groupCountZ) override; + virtual void TraceRays(int width, int height, int depth) override; - // - // D3D11 - // + // + // D3D11 + // - ID3D11DeviceContext* GetD3DDeviceContext() const; + ID3D11DeviceContext* GetD3DDeviceContext() const; - void PrepareSubpass(); - }; - VERUS_TYPEDEFS(CommandBufferD3D11); - } + void PrepareSubpass(); + }; + VERUS_TYPEDEFS(CommandBufferD3D11); } diff --git a/RendererDirect3D11/src/CGI/ExtRealityD3D11.h b/RendererDirect3D11/src/CGI/ExtRealityD3D11.h index 434e420..dc0ca82 100644 --- a/RendererDirect3D11/src/CGI/ExtRealityD3D11.h +++ b/RendererDirect3D11/src/CGI/ExtRealityD3D11.h @@ -1,66 +1,63 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class RendererD3D11; + + class ExtRealityD3D11 : public BaseExtReality { - class RendererD3D11; - - class ExtRealityD3D11 : public BaseExtReality + struct SwapChainEx { - struct SwapChainEx - { - XrSwapchain _handle = XR_NULL_HANDLE; - int32_t _width = 0; - int32_t _height = 0; - Vector _vImages; - Vector> _vImageViews; - }; - - Vector _vSwapChains; - LUID _adapterLuid; - D3D_FEATURE_LEVEL _minFeatureLevel = D3D_FEATURE_LEVEL_11_0; - - public: - ExtRealityD3D11(); - virtual ~ExtRealityD3D11() override; - - virtual void Init() override; - virtual void Done() override; - - void InitByRenderer(RendererD3D11* pRenderer); - - private: - void GetSystem(); - void CreateSwapChains(ID3D11Device* pDevice, int64_t format); - ComPtr CreateImageView(ID3D11Device* pDevice, int64_t format, XrSwapchainImageD3D11KHR& image); - virtual XrSwapchain GetSwapChain(int viewIndex) override; - virtual void GetSwapChainSize(int viewIndex, int32_t& w, int32_t& h) override; - - public: - LUID GetAdapterLuid() const { return _adapterLuid; } - D3D_FEATURE_LEVEL GetMinFeatureLevel() const { return _minFeatureLevel; } - ID3D11RenderTargetView* GetRTV(int viewIndex, int imageIndex) const; - - virtual void CreateActions() override; - virtual void PollEvents() override; - virtual void SyncActions(UINT32 activeActionSetsMask) override; - - virtual bool GetActionStateBoolean(int actionIndex, bool& currentState, bool* pChangedState, int subaction) override; - virtual bool GetActionStateFloat(int actionIndex, float& currentState, bool* pChangedState, int subaction) override; - virtual bool GetActionStatePose(int actionIndex, bool& currentState, Math::RPose pose, int subaction) override; - - virtual void BeginFrame() override; - virtual int LocateViews() override; - virtual void BeginView(int viewIndex, RViewDesc viewDesc) override; - virtual void AcquireSwapChainImage() override; - virtual void EndView(int viewIndex) override; - virtual void EndFrame() override; - - virtual void BeginAreaUpdate() override; - virtual void EndAreaUpdate(PcVector4 pUserOffset) override; + XrSwapchain _handle = XR_NULL_HANDLE; + int32_t _width = 0; + int32_t _height = 0; + Vector _vImages; + Vector> _vImageViews; }; - VERUS_TYPEDEFS(ExtRealityD3D11); - } + + Vector _vSwapChains; + LUID _adapterLuid; + D3D_FEATURE_LEVEL _minFeatureLevel = D3D_FEATURE_LEVEL_11_0; + + public: + ExtRealityD3D11(); + virtual ~ExtRealityD3D11() override; + + virtual void Init() override; + virtual void Done() override; + + void InitByRenderer(RendererD3D11* pRenderer); + + private: + void GetSystem(); + void CreateSwapChains(ID3D11Device* pDevice, int64_t format); + ComPtr CreateImageView(ID3D11Device* pDevice, int64_t format, XrSwapchainImageD3D11KHR& image); + virtual XrSwapchain GetSwapChain(int viewIndex) override; + virtual void GetSwapChainSize(int viewIndex, int32_t& w, int32_t& h) override; + + public: + LUID GetAdapterLuid() const { return _adapterLuid; } + D3D_FEATURE_LEVEL GetMinFeatureLevel() const { return _minFeatureLevel; } + ID3D11RenderTargetView* GetRTV(int viewIndex, int imageIndex) const; + + virtual void CreateActions() override; + virtual void PollEvents() override; + virtual void SyncActions(UINT32 activeActionSetsMask) override; + + virtual bool GetActionStateBoolean(int actionIndex, bool& currentState, bool* pChangedState, int subaction) override; + virtual bool GetActionStateFloat(int actionIndex, float& currentState, bool* pChangedState, int subaction) override; + virtual bool GetActionStatePose(int actionIndex, bool& currentState, Math::RPose pose, int subaction) override; + + virtual void BeginFrame() override; + virtual int LocateViews() override; + virtual void BeginView(int viewIndex, RViewDesc viewDesc) override; + virtual void AcquireSwapChainImage() override; + virtual void EndView(int viewIndex) override; + virtual void EndFrame() override; + + virtual void BeginAreaUpdate() override; + virtual void EndAreaUpdate(PcVector4 pUserOffset) override; + }; + VERUS_TYPEDEFS(ExtRealityD3D11); } diff --git a/RendererDirect3D11/src/CGI/GeometryD3D11.h b/RendererDirect3D11/src/CGI/GeometryD3D11.h index bff91e3..2a79f4d 100644 --- a/RendererDirect3D11/src/CGI/GeometryD3D11.h +++ b/RendererDirect3D11/src/CGI/GeometryD3D11.h @@ -1,61 +1,58 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class GeometryD3D11 : public BaseGeometry { - class GeometryD3D11 : public BaseGeometry + struct BufferEx { - struct BufferEx - { - ComPtr _pBuffer; - UINT64 _bufferSize = 0; - }; - - struct StructuredBufferEx : BufferEx - { - ComPtr _pSRV; - int _structSize = 0; - }; - - Vector _vVertexBuffers; - BufferEx _indexBuffer; - Vector _vStructuredBuffers; - Vector _vInputElementDescs; - Vector _vStrides; - - public: - GeometryD3D11(); - virtual ~GeometryD3D11() override; - - virtual void Init(RcGeometryDesc desc) override; - virtual void Done() override; - - virtual void CreateVertexBuffer(int count, int binding) override; - virtual void UpdateVertexBuffer(const void* p, int binding, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - - virtual void CreateIndexBuffer(int count) override; - virtual void UpdateIndexBuffer(const void* p, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - - virtual void CreateStorageBuffer(int count, int structSize, int sbIndex, ShaderStageFlags stageFlags) override; - virtual void UpdateStorageBuffer(const void* p, int sbIndex, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - virtual int GetStorageBufferStructSize(int sbIndex) const override; - - virtual Continue Scheduled_Update() override; - - // - // D3D11 - // - - void GetD3DInputElementDescs(UINT32 bindingsFilter, Vector& vInputElementDescs) const; - int GetStride(int binding) const { return _vStrides[binding]; } - - int GetVertexBufferCount() const { return Utils::Cast32(_vVertexBuffers.size()); } - ID3D11Buffer* GetD3DVertexBuffer(int binding) const { return _vVertexBuffers[binding]._pBuffer.Get(); } - ID3D11Buffer* GetD3DIndexBuffer() const { return _indexBuffer._pBuffer.Get(); } - ID3D11ShaderResourceView* GetD3DStructuredBufferSRV(int sbIndex) const { return _vStructuredBuffers[sbIndex]._pSRV.Get(); } + ComPtr _pBuffer; + UINT64 _bufferSize = 0; }; - VERUS_TYPEDEFS(GeometryD3D11); - } + + struct StructuredBufferEx : BufferEx + { + ComPtr _pSRV; + int _structSize = 0; + }; + + Vector _vVertexBuffers; + BufferEx _indexBuffer; + Vector _vStructuredBuffers; + Vector _vInputElementDescs; + Vector _vStrides; + + public: + GeometryD3D11(); + virtual ~GeometryD3D11() override; + + virtual void Init(RcGeometryDesc desc) override; + virtual void Done() override; + + virtual void CreateVertexBuffer(int count, int binding) override; + virtual void UpdateVertexBuffer(const void* p, int binding, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + + virtual void CreateIndexBuffer(int count) override; + virtual void UpdateIndexBuffer(const void* p, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + + virtual void CreateStorageBuffer(int count, int structSize, int sbIndex, ShaderStageFlags stageFlags) override; + virtual void UpdateStorageBuffer(const void* p, int sbIndex, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + virtual int GetStorageBufferStructSize(int sbIndex) const override; + + virtual Continue Scheduled_Update() override; + + // + // D3D11 + // + + void GetD3DInputElementDescs(UINT32 bindingsFilter, Vector& vInputElementDescs) const; + int GetStride(int binding) const { return _vStrides[binding]; } + + int GetVertexBufferCount() const { return Utils::Cast32(_vVertexBuffers.size()); } + ID3D11Buffer* GetD3DVertexBuffer(int binding) const { return _vVertexBuffers[binding]._pBuffer.Get(); } + ID3D11Buffer* GetD3DIndexBuffer() const { return _indexBuffer._pBuffer.Get(); } + ID3D11ShaderResourceView* GetD3DStructuredBufferSRV(int sbIndex) const { return _vStructuredBuffers[sbIndex]._pSRV.Get(); } + }; + VERUS_TYPEDEFS(GeometryD3D11); } diff --git a/RendererDirect3D11/src/CGI/Native.h b/RendererDirect3D11/src/CGI/Native.h index eb30bc8..2b62394 100644 --- a/RendererDirect3D11/src/CGI/Native.h +++ b/RendererDirect3D11/src/CGI/Native.h @@ -1,24 +1,21 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI - { - D3D11_COMPARISON_FUNC ToNativeCompareOp(CompareOp compareOp); + D3D11_COMPARISON_FUNC ToNativeCompareOp(CompareOp compareOp); - UINT ToNativeCubeMapFace(CubeMapFace face); + UINT ToNativeCubeMapFace(CubeMapFace face); - D3D11_FILL_MODE ToNativePolygonMode(PolygonMode polygonMode); + D3D11_FILL_MODE ToNativePolygonMode(PolygonMode polygonMode); - D3D11_CULL_MODE ToNativeCullMode(CullMode cullMode); + D3D11_CULL_MODE ToNativeCullMode(CullMode cullMode); - D3D_PRIMITIVE_TOPOLOGY ToNativePrimitiveTopology(PrimitiveTopology primitiveTopology); + D3D_PRIMITIVE_TOPOLOGY ToNativePrimitiveTopology(PrimitiveTopology primitiveTopology); - DXGI_FORMAT ToNativeFormat(Format format, bool typeless); - DXGI_FORMAT ToNativeSampledDepthFormat(Format format); + DXGI_FORMAT ToNativeFormat(Format format, bool typeless); + DXGI_FORMAT ToNativeSampledDepthFormat(Format format); - CSZ ToNativeSemanticName(ViaUsage usage); - DXGI_FORMAT ToNativeFormat(ViaUsage usage, ViaType type, int components); - } + CSZ ToNativeSemanticName(ViaUsage usage); + DXGI_FORMAT ToNativeFormat(ViaUsage usage, ViaType type, int components); } diff --git a/RendererDirect3D11/src/CGI/PipelineD3D11.h b/RendererDirect3D11/src/CGI/PipelineD3D11.h index f14ccb5..d3fbc1d 100644 --- a/RendererDirect3D11/src/CGI/PipelineD3D11.h +++ b/RendererDirect3D11/src/CGI/PipelineD3D11.h @@ -1,55 +1,52 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class PipelineD3D11 : public BasePipeline { - class PipelineD3D11 : public BasePipeline - { - ComPtr _pVS; - ComPtr _pHS; - ComPtr _pDS; - ComPtr _pGS; - ComPtr _pPS; - ComPtr _pCS; - ComPtr _pBlendState; - ComPtr _pRasterizerState; - ComPtr _pDepthStencilState; - ComPtr _pInputLayout; - UINT _sampleMask = UINT_MAX; - UINT _stencilRef = 0; - D3D_PRIMITIVE_TOPOLOGY _topology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; - bool _compute = false; + ComPtr _pVS; + ComPtr _pHS; + ComPtr _pDS; + ComPtr _pGS; + ComPtr _pPS; + ComPtr _pCS; + ComPtr _pBlendState; + ComPtr _pRasterizerState; + ComPtr _pDepthStencilState; + ComPtr _pInputLayout; + UINT _sampleMask = UINT_MAX; + UINT _stencilRef = 0; + D3D_PRIMITIVE_TOPOLOGY _topology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; + bool _compute = false; - public: - PipelineD3D11(); - virtual ~PipelineD3D11() override; + public: + PipelineD3D11(); + virtual ~PipelineD3D11() override; - virtual void Init(RcPipelineDesc desc) override; - virtual void Done() override; + virtual void Init(RcPipelineDesc desc) override; + virtual void Done() override; - // - // D3D11 - // + // + // D3D11 + // - VERUS_P(void InitCompute(RcPipelineDesc desc)); - bool IsCompute() const { return _compute; } - ID3D11VertexShader* GetD3DVS() const { return _pVS.Get(); } - ID3D11HullShader* GetD3DHS() const { return _pHS.Get(); } - ID3D11DomainShader* GetD3DDS() const { return _pDS.Get(); } - ID3D11GeometryShader* GetD3DGS() const { return _pGS.Get(); } - ID3D11PixelShader* GetD3DPS() const { return _pPS.Get(); } - ID3D11ComputeShader* GetD3DCS() const { return _pCS.Get(); } - ID3D11BlendState* GetD3DBlendState() const { return _pBlendState.Get(); } - ID3D11RasterizerState* GetD3DRasterizerState() const { return _pRasterizerState.Get(); } - ID3D11DepthStencilState* GetD3DDepthStencilState() const { return _pDepthStencilState.Get(); } - ID3D11InputLayout* GetD3DInputLayout() const { return _pInputLayout.Get(); } - UINT GetSampleMask() const { return _sampleMask; } - UINT GetStencilRef() const { return _stencilRef; } - D3D_PRIMITIVE_TOPOLOGY GetD3DPrimitiveTopology() const { return _topology; } - void FillBlendStateRenderTargets(RcPipelineDesc desc, int attachmentCount, D3D11_BLEND_DESC& blendDesc); - }; - VERUS_TYPEDEFS(PipelineD3D11); - } + VERUS_P(void InitCompute(RcPipelineDesc desc)); + bool IsCompute() const { return _compute; } + ID3D11VertexShader* GetD3DVS() const { return _pVS.Get(); } + ID3D11HullShader* GetD3DHS() const { return _pHS.Get(); } + ID3D11DomainShader* GetD3DDS() const { return _pDS.Get(); } + ID3D11GeometryShader* GetD3DGS() const { return _pGS.Get(); } + ID3D11PixelShader* GetD3DPS() const { return _pPS.Get(); } + ID3D11ComputeShader* GetD3DCS() const { return _pCS.Get(); } + ID3D11BlendState* GetD3DBlendState() const { return _pBlendState.Get(); } + ID3D11RasterizerState* GetD3DRasterizerState() const { return _pRasterizerState.Get(); } + ID3D11DepthStencilState* GetD3DDepthStencilState() const { return _pDepthStencilState.Get(); } + ID3D11InputLayout* GetD3DInputLayout() const { return _pInputLayout.Get(); } + UINT GetSampleMask() const { return _sampleMask; } + UINT GetStencilRef() const { return _stencilRef; } + D3D_PRIMITIVE_TOPOLOGY GetD3DPrimitiveTopology() const { return _topology; } + void FillBlendStateRenderTargets(RcPipelineDesc desc, int attachmentCount, D3D11_BLEND_DESC& blendDesc); + }; + VERUS_TYPEDEFS(PipelineD3D11); } diff --git a/RendererDirect3D11/src/CGI/RenderPass.h b/RendererDirect3D11/src/CGI/RenderPass.h index 27b3391..3e7d232 100644 --- a/RendererDirect3D11/src/CGI/RenderPass.h +++ b/RendererDirect3D11/src/CGI/RenderPass.h @@ -1,76 +1,70 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI::RP { - namespace CGI + class D3DAttachment { - namespace RP - { - class D3DAttachment - { - public: - Format _format = Format::unormR8G8B8A8; - int _sampleCount = 1; - Attachment::LoadOp _loadOp = Attachment::LoadOp::load; - Attachment::StoreOp _storeOp = Attachment::StoreOp::store; - Attachment::LoadOp _stencilLoadOp = Attachment::LoadOp::dontCare; - Attachment::StoreOp _stencilStoreOp = Attachment::StoreOp::dontCare; - int _clearSubpassIndex = -1; - }; - VERUS_TYPEDEFS(D3DAttachment); + public: + Format _format = Format::unormR8G8B8A8; + int _sampleCount = 1; + Attachment::LoadOp _loadOp = Attachment::LoadOp::load; + Attachment::StoreOp _storeOp = Attachment::StoreOp::store; + Attachment::LoadOp _stencilLoadOp = Attachment::LoadOp::dontCare; + Attachment::StoreOp _stencilStoreOp = Attachment::StoreOp::dontCare; + int _clearSubpassIndex = -1; + }; + VERUS_TYPEDEFS(D3DAttachment); - class D3DRef - { - public: - int _index = -1; - }; - VERUS_TYPEDEFS(D3DRef); + class D3DRef + { + public: + int _index = -1; + }; + VERUS_TYPEDEFS(D3DRef); - class D3DSubpass - { - public: - Vector _vInput; - Vector _vColor; - Vector _vResolve; - Vector _vPreserve; - D3DRef _depthStencil; - bool _depthStencilReadOnly = false; - }; - VERUS_TYPEDEFS(D3DSubpass); + class D3DSubpass + { + public: + Vector _vInput; + Vector _vColor; + Vector _vResolve; + Vector _vPreserve; + D3DRef _depthStencil; + bool _depthStencilReadOnly = false; + }; + VERUS_TYPEDEFS(D3DSubpass); - class D3DDependency - { - public: - }; - VERUS_TYPEDEFS(D3DDependency); + class D3DDependency + { + public: + }; + VERUS_TYPEDEFS(D3DDependency); - class D3DRenderPass - { - public: - Vector _vAttachments; - Vector _vSubpasses; - }; - VERUS_TYPEDEFS(D3DRenderPass); + class D3DRenderPass + { + public: + Vector _vAttachments; + Vector _vSubpasses; + }; + VERUS_TYPEDEFS(D3DRenderPass); - class D3DFramebufferSubpass - { - public: - Vector _vRTVs; - ID3D11DepthStencilView* _pDSV = nullptr; - }; - VERUS_TYPEDEFS(D3DFramebufferSubpass); + class D3DFramebufferSubpass + { + public: + Vector _vRTVs; + ID3D11DepthStencilView* _pDSV = nullptr; + }; + VERUS_TYPEDEFS(D3DFramebufferSubpass); - class D3DFramebuffer - { - public: - Vector _vSubpasses; - int _width = 0; - int _height = 0; - int _mipLevels = 1; - CubeMapFace _cubeMapFace = CubeMapFace::none; - }; - VERUS_TYPEDEFS(D3DFramebuffer); - } - } + class D3DFramebuffer + { + public: + Vector _vSubpasses; + int _width = 0; + int _height = 0; + int _mipLevels = 1; + CubeMapFace _cubeMapFace = CubeMapFace::none; + }; + VERUS_TYPEDEFS(D3DFramebuffer); } diff --git a/RendererDirect3D11/src/CGI/RendererD3D11.h b/RendererDirect3D11/src/CGI/RendererD3D11.h index b691a69..4590bfc 100644 --- a/RendererDirect3D11/src/CGI/RendererD3D11.h +++ b/RendererDirect3D11/src/CGI/RendererD3D11.h @@ -1,99 +1,96 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + typedef Store TStoreCommandBuffers; + typedef Store TStoreGeometry; + typedef Store TStorePipelines; + typedef Store TStoreShaders; + typedef Store TStoreTextures; + class RendererD3D11 : public Singleton, public BaseRenderer, + private TStoreCommandBuffers, private TStoreGeometry, private TStorePipelines, private TStoreShaders, private TStoreTextures { - typedef Store TStoreCommandBuffers; - typedef Store TStoreGeometry; - typedef Store TStorePipelines; - typedef Store TStoreShaders; - typedef Store TStoreTextures; - class RendererD3D11 : public Singleton, public BaseRenderer, - private TStoreCommandBuffers, private TStoreGeometry, private TStorePipelines, private TStoreShaders, private TStoreTextures - { - ExtRealityD3D11 _extReality; - ComPtr _pDevice; - ComPtr _pDeviceContext; - ComPtr _pSwapChain; - ComPtr _pSwapChainBuffer; - ComPtr _pSwapChainBufferRTV; + ExtRealityD3D11 _extReality; + ComPtr _pDevice; + ComPtr _pDeviceContext; + ComPtr _pSwapChain; + ComPtr _pSwapChainBuffer; + ComPtr _pSwapChainBufferRTV; - Vector> _vSamplers; - Vector _vRenderPasses; - Vector _vFramebuffers; - D3D_FEATURE_LEVEL _featureLevel = D3D_FEATURE_LEVEL_11_0; - DXGI_SWAP_CHAIN_DESC _swapChainDesc = {}; + Vector> _vSamplers; + Vector _vRenderPasses; + Vector _vFramebuffers; + D3D_FEATURE_LEVEL _featureLevel = D3D_FEATURE_LEVEL_11_0; + DXGI_SWAP_CHAIN_DESC _swapChainDesc = {}; - public: - RendererD3D11(); - ~RendererD3D11(); + public: + RendererD3D11(); + ~RendererD3D11(); - virtual void ReleaseMe() override; + virtual void ReleaseMe() override; - void Init(); - void Done(); + void Init(); + void Done(); - private: - static ComPtr CreateFactory(); - ComPtr GetAdapter(ComPtr pFactory) const; - void CreateSwapChainBufferRTV(); - void InitD3D(); + private: + static ComPtr CreateFactory(); + ComPtr GetAdapter(ComPtr pFactory) const; + void CreateSwapChainBufferRTV(); + void InitD3D(); - public: - // - void CreateSamplers(); + public: + // + void CreateSamplers(); - ID3D11Device* GetD3DDevice() const { return _pDevice.Get(); } - ID3D11DeviceContext* GetD3DDeviceContext() const { return _pDeviceContext.Get(); } - ID3D11SamplerState* GetD3DSamplerState(Sampler s) const; - // + ID3D11Device* GetD3DDevice() const { return _pDevice.Get(); } + ID3D11DeviceContext* GetD3DDeviceContext() const { return _pDeviceContext.Get(); } + ID3D11SamplerState* GetD3DSamplerState(Sampler s) const; + // - virtual void ImGuiInit(RPHandle renderPassHandle) override; - virtual void ImGuiRenderDrawData() override; + virtual void ImGuiInit(RPHandle renderPassHandle) override; + virtual void ImGuiRenderDrawData() override; - virtual void ResizeSwapChain() override; + virtual void ResizeSwapChain() override; - virtual PBaseExtReality GetExtReality() override; + virtual PBaseExtReality GetExtReality() override; - // Which graphics API? - virtual Gapi GetGapi() override { return Gapi::direct3D11; } + // Which graphics API? + virtual Gapi GetGapi() override { return Gapi::direct3D11; } - // - virtual void BeginFrame() override; - virtual void AcquireSwapChainImage() override; - virtual void EndFrame() override; - virtual void WaitIdle() override; - virtual void OnMinimized() override; - // + // + virtual void BeginFrame() override; + virtual void AcquireSwapChainImage() override; + virtual void EndFrame() override; + virtual void WaitIdle() override; + virtual void OnMinimized() override; + // - // - virtual PBaseCommandBuffer InsertCommandBuffer() override; - virtual PBaseGeometry InsertGeometry() override; - virtual PBasePipeline InsertPipeline() override; - virtual PBaseShader InsertShader() override; - virtual PBaseTexture InsertTexture() override; + // + virtual PBaseCommandBuffer InsertCommandBuffer() override; + virtual PBaseGeometry InsertGeometry() override; + virtual PBasePipeline InsertPipeline() override; + virtual PBaseShader InsertShader() override; + virtual PBaseTexture InsertTexture() override; - virtual void DeleteCommandBuffer(PBaseCommandBuffer p) override; - virtual void DeleteGeometry(PBaseGeometry p) override; - virtual void DeletePipeline(PBasePipeline p) override; - virtual void DeleteShader(PBaseShader p) override; - virtual void DeleteTexture(PBaseTexture p) override; + virtual void DeleteCommandBuffer(PBaseCommandBuffer p) override; + virtual void DeleteGeometry(PBaseGeometry p) override; + virtual void DeletePipeline(PBasePipeline p) override; + virtual void DeleteShader(PBaseShader p) override; + virtual void DeleteTexture(PBaseTexture p) override; - virtual RPHandle CreateRenderPass(std::initializer_list ilA, std::initializer_list ilS, std::initializer_list ilD) override; - virtual FBHandle CreateFramebuffer(RPHandle renderPassHandle, std::initializer_list il, int w, int h, - int swapChainBufferIndex = -1, CubeMapFace cubeMapFace = CubeMapFace::none) override; - virtual void DeleteRenderPass(RPHandle handle) override; - virtual void DeleteFramebuffer(FBHandle handle) override; - int GetNextRenderPassIndex() const; - int GetNextFramebufferIndex() const; - RP::RcD3DRenderPass GetRenderPass(RPHandle handle) const; - RP::RcD3DFramebuffer GetFramebuffer(FBHandle handle) const; - // - }; - VERUS_TYPEDEFS(RendererD3D11); - } + virtual RPHandle CreateRenderPass(std::initializer_list ilA, std::initializer_list ilS, std::initializer_list ilD) override; + virtual FBHandle CreateFramebuffer(RPHandle renderPassHandle, std::initializer_list il, int w, int h, + int swapChainBufferIndex = -1, CubeMapFace cubeMapFace = CubeMapFace::none) override; + virtual void DeleteRenderPass(RPHandle handle) override; + virtual void DeleteFramebuffer(FBHandle handle) override; + int GetNextRenderPassIndex() const; + int GetNextFramebufferIndex() const; + RP::RcD3DRenderPass GetRenderPass(RPHandle handle) const; + RP::RcD3DFramebuffer GetFramebuffer(FBHandle handle) const; + // + }; + VERUS_TYPEDEFS(RendererD3D11); } #define VERUS_QREF_RENDERER_D3D11 CGI::PRendererD3D11 pRendererD3D11 = CGI::RendererD3D11::P() diff --git a/RendererDirect3D11/src/CGI/ShaderD3D11.cpp b/RendererDirect3D11/src/CGI/ShaderD3D11.cpp index afec405..c1f9e11 100644 --- a/RendererDirect3D11/src/CGI/ShaderD3D11.cpp +++ b/RendererDirect3D11/src/CGI/ShaderD3D11.cpp @@ -59,13 +59,13 @@ void ShaderD3D11::Init(CSZ source, CSZ sourceName, CSZ* branches) ComPtr pBlob; auto CheckErrorMsgs = [this](ComPtr& pErrorMsgs) - { - if (pErrorMsgs) { - OnError(static_cast(pErrorMsgs->GetBufferPointer())); - pErrorMsgs.Reset(); - } - }; + if (pErrorMsgs) + { + OnError(static_cast(pErrorMsgs->GetBufferPointer())); + pErrorMsgs.Reset(); + } + }; while (*branches) { @@ -191,10 +191,10 @@ void ShaderD3D11::Done() for (auto& dsd : _vDescriptorSetDesc) dsd._pConstantBuffer.Reset(); - for (auto& x : _mapCompiled) + for (auto& [key, value] : _mapCompiled) { VERUS_FOR(i, +Stage::count) - x.second._pBlobs[i].Reset(); + value._pBlobs[i].Reset(); } VERUS_DONE(ShaderD3D11); diff --git a/RendererDirect3D11/src/CGI/ShaderD3D11.h b/RendererDirect3D11/src/CGI/ShaderD3D11.h index e48ed25..dd272d6 100644 --- a/RendererDirect3D11/src/CGI/ShaderD3D11.h +++ b/RendererDirect3D11/src/CGI/ShaderD3D11.h @@ -1,108 +1,105 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + struct ShaderInclude : public ID3DInclude { - struct ShaderInclude : public ID3DInclude + public: + virtual HRESULT STDMETHODCALLTYPE Open( + D3D_INCLUDE_TYPE IncludeType, + LPCSTR pFileName, + LPCVOID pParentData, + LPCVOID* ppData, + UINT* pBytes) override; + virtual HRESULT STDMETHODCALLTYPE Close(LPCVOID pData) override; + }; + VERUS_TYPEDEFS(ShaderInclude); + + struct ShaderResources + { + UINT _srvCount = 0; + UINT _uavCount = 0; + UINT _srvStartSlot = 0; + UINT _uavStartSlot = 0; + ID3D11ShaderResourceView* _srvs[VERUS_MAX_FB_ATTACH]; + ID3D11UnorderedAccessView* _uavs[VERUS_MAX_FB_ATTACH]; + ID3D11SamplerState* _samplers[VERUS_MAX_FB_ATTACH]; + }; + VERUS_TYPEDEFS(ShaderResources); + + class ShaderD3D11 : public BaseShader + { + public: + struct Compiled { - public: - virtual HRESULT STDMETHODCALLTYPE Open( - D3D_INCLUDE_TYPE IncludeType, - LPCSTR pFileName, - LPCVOID pParentData, - LPCVOID* ppData, - UINT* pBytes) override; - virtual HRESULT STDMETHODCALLTYPE Close(LPCVOID pData) override; + ComPtr _pBlobs[+Stage::count]; + String _entry; + int _stageCount = 0; }; - VERUS_TYPEDEFS(ShaderInclude); + VERUS_TYPEDEFS(Compiled); - struct ShaderResources + private: + typedef Map TMapCompiled; + + struct DescriptorSetDesc { - UINT _srvCount = 0; - UINT _uavCount = 0; - UINT _srvStartSlot = 0; - UINT _uavStartSlot = 0; - ID3D11ShaderResourceView* _srvs[VERUS_MAX_FB_ATTACH]; - ID3D11UnorderedAccessView* _uavs[VERUS_MAX_FB_ATTACH]; - ID3D11SamplerState* _samplers[VERUS_MAX_FB_ATTACH]; + Vector _vSamplers; + ComPtr _pConstantBuffer; + const void* _pSrc = nullptr; + int _size = 0; + int _alignedSize = 0; + int _capacity = 1; + int _capacityInBytes = 0; + UINT _srvCount = 0; + UINT _uavCount = 0; + UINT _srvStartSlot = 0; + UINT _uavStartSlot = 0; + ShaderStageFlags _stageFlags = ShaderStageFlags::vs_fs; }; - VERUS_TYPEDEFS(ShaderResources); - class ShaderD3D11 : public BaseShader + struct ComplexSet { - public: - struct Compiled - { - ComPtr _pBlobs[+Stage::count]; - String _entry; - int _stageCount = 0; - }; - VERUS_TYPEDEFS(Compiled); - - private: - typedef Map TMapCompiled; - - struct DescriptorSetDesc - { - Vector _vSamplers; - ComPtr _pConstantBuffer; - const void* _pSrc = nullptr; - int _size = 0; - int _alignedSize = 0; - int _capacity = 1; - int _capacityInBytes = 0; - UINT _srvCount = 0; - UINT _uavCount = 0; - UINT _srvStartSlot = 0; - UINT _uavStartSlot = 0; - ShaderStageFlags _stageFlags = ShaderStageFlags::vs_fs; - }; - - struct ComplexSet - { - Vector _vTextures; - Vector _vSRVs; - Vector _vUAVs; - }; - VERUS_TYPEDEFS(ComplexSet); - - TMapCompiled _mapCompiled; - Vector _vDescriptorSetDesc; - Vector _vComplexSets; - bool _compute = false; - - public: - ShaderD3D11(); - virtual ~ShaderD3D11() override; - - virtual void Init(CSZ source, CSZ sourceName, CSZ* branches) override; - virtual void Done() override; - - virtual void CreateDescriptorSet(int setNumber, const void* pSrc, int size, int capacity, std::initializer_list il, ShaderStageFlags stageFlags) override; - virtual void CreatePipelineLayout() override; - virtual CSHandle BindDescriptorSetTextures(int setNumber, std::initializer_list il, const int* pMipLevels, const int* pArrayLayers) override; - virtual void FreeDescriptorSet(CSHandle& complexSetHandle) override; - - virtual void BeginBindDescriptors() override; - virtual void EndBindDescriptors() override; - - // - // D3D11 - // - - RcCompiled GetCompiled(CSZ branch) const { return _mapCompiled.at(branch); } - - ID3D11Buffer* UpdateConstantBuffer(int setNumber) const; - ShaderStageFlags GetShaderStageFlags(int setNumber) const; - void GetShaderResources(int setNumber, int complexSetHandle, RShaderResources shaderResources) const; - void GetSamplers(int setNumber, int complexSetHandle, RShaderResources shaderResources) const; - int GetDescriptorSetCount() const { return static_cast(_vDescriptorSetDesc.size()); } - bool IsCompute() const { return _compute; } - - void OnError(CSZ s) const; + Vector _vTextures; + Vector _vSRVs; + Vector _vUAVs; }; - VERUS_TYPEDEFS(ShaderD3D11); - } + VERUS_TYPEDEFS(ComplexSet); + + TMapCompiled _mapCompiled; + Vector _vDescriptorSetDesc; + Vector _vComplexSets; + bool _compute = false; + + public: + ShaderD3D11(); + virtual ~ShaderD3D11() override; + + virtual void Init(CSZ source, CSZ sourceName, CSZ* branches) override; + virtual void Done() override; + + virtual void CreateDescriptorSet(int setNumber, const void* pSrc, int size, int capacity, std::initializer_list il, ShaderStageFlags stageFlags) override; + virtual void CreatePipelineLayout() override; + virtual CSHandle BindDescriptorSetTextures(int setNumber, std::initializer_list il, const int* pMipLevels, const int* pArrayLayers) override; + virtual void FreeDescriptorSet(CSHandle& complexSetHandle) override; + + virtual void BeginBindDescriptors() override; + virtual void EndBindDescriptors() override; + + // + // D3D11 + // + + RcCompiled GetCompiled(CSZ branch) const { return _mapCompiled.at(branch); } + + ID3D11Buffer* UpdateConstantBuffer(int setNumber) const; + ShaderStageFlags GetShaderStageFlags(int setNumber) const; + void GetShaderResources(int setNumber, int complexSetHandle, RShaderResources shaderResources) const; + void GetSamplers(int setNumber, int complexSetHandle, RShaderResources shaderResources) const; + int GetDescriptorSetCount() const { return static_cast(_vDescriptorSetDesc.size()); } + bool IsCompute() const { return _compute; } + + void OnError(CSZ s) const; + }; + VERUS_TYPEDEFS(ShaderD3D11); } diff --git a/RendererDirect3D11/src/CGI/TextureD3D11.h b/RendererDirect3D11/src/CGI/TextureD3D11.h index c758e22..44f1a31 100644 --- a/RendererDirect3D11/src/CGI/TextureD3D11.h +++ b/RendererDirect3D11/src/CGI/TextureD3D11.h @@ -1,56 +1,53 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class TextureD3D11 : public BaseTexture { - class TextureD3D11 : public BaseTexture - { - ComPtr _pTexture2D; - ComPtr _pTexture3D; - ComPtr _pUaTexture; - Vector> _vReadbackTextures; - Vector _vCshGenerateMips; - ComPtr _pSRV; - Vector> _vUAVs; - Vector> _vRTVs; - ComPtr _pDSV[2]; - ComPtr _pSamplerState; + ComPtr _pTexture2D; + ComPtr _pTexture3D; + ComPtr _pUaTexture; + Vector> _vReadbackTextures; + Vector _vCshGenerateMips; + ComPtr _pSRV; + Vector> _vUAVs; + Vector> _vRTVs; + ComPtr _pDSV[2]; + ComPtr _pSamplerState; - public: - TextureD3D11(); - virtual ~TextureD3D11() override; + public: + TextureD3D11(); + virtual ~TextureD3D11() override; - virtual void Init(RcTextureDesc desc) override; - virtual void Done() override; + virtual void Init(RcTextureDesc desc) override; + virtual void Done() override; - virtual void UpdateSubresource(const void* p, int mipLevel, int arrayLayer, PBaseCommandBuffer pCB) override; - virtual bool ReadbackSubresource(void* p, bool recordCopyCommand, PBaseCommandBuffer pCB) override; + virtual void UpdateSubresource(const void* p, int mipLevel, int arrayLayer, PBaseCommandBuffer pCB) override; + virtual bool ReadbackSubresource(void* p, bool recordCopyCommand, PBaseCommandBuffer pCB) override; - virtual void GenerateMips(PBaseCommandBuffer pCB) override; - void GenerateCubeMapMips(PBaseCommandBuffer pCB); + virtual void GenerateMips(PBaseCommandBuffer pCB) override; + void GenerateCubeMapMips(PBaseCommandBuffer pCB); - virtual Continue Scheduled_Update() override; + virtual Continue Scheduled_Update() override; - // - // D3D11 - // + // + // D3D11 + // - void ClearCshGenerateMips(); + void ClearCshGenerateMips(); - void CreateSampler(); + void CreateSampler(); - ID3D11Resource* GetD3DResource() const; + ID3D11Resource* GetD3DResource() const; - ID3D11ShaderResourceView* GetSRV() const { return _pSRV.Get(); } - ID3D11UnorderedAccessView* GetUAV(int index = 0) const { return _vUAVs[index].Get(); } - ID3D11RenderTargetView* GetRTV(int index = 0) const { return _vRTVs[index].Get(); } - ID3D11DepthStencilView* GetDSV(bool readOnly = false) const { return readOnly ? _pDSV[1].Get() : _pDSV[0].Get(); } - ID3D11SamplerState* GetD3DSamplerState() const { return _pSamplerState.Get(); } + ID3D11ShaderResourceView* GetSRV() const { return _pSRV.Get(); } + ID3D11UnorderedAccessView* GetUAV(int index = 0) const { return _vUAVs[index].Get(); } + ID3D11RenderTargetView* GetRTV(int index = 0) const { return _vRTVs[index].Get(); } + ID3D11DepthStencilView* GetDSV(bool readOnly = false) const { return readOnly ? _pDSV[1].Get() : _pDSV[0].Get(); } + ID3D11SamplerState* GetD3DSamplerState() const { return _pSamplerState.Get(); } - static DXGI_FORMAT RemoveSRGB(DXGI_FORMAT format); - }; - VERUS_TYPEDEFS(TextureD3D11); - } + static DXGI_FORMAT RemoveSRGB(DXGI_FORMAT format); + }; + VERUS_TYPEDEFS(TextureD3D11); } diff --git a/RendererDirect3D12/RendererDirect3D12.vcxproj b/RendererDirect3D12/RendererDirect3D12.vcxproj index 7d88163..56a2abd 100644 --- a/RendererDirect3D12/RendererDirect3D12.vcxproj +++ b/RendererDirect3D12/RendererDirect3D12.vcxproj @@ -11,23 +11,23 @@ - 16.0 + 17.0 Win32Proj {53923514-84B2-4B78-889A-8709C6BFA3A5} RendererDirect3D12 - 10.0.20348.0 + 10.0.22000.0 DynamicLibrary true - v142 + v143 Unicode DynamicLibrary false - v142 + v143 true Unicode @@ -45,12 +45,6 @@ - - true - - - false - Level3 @@ -61,6 +55,7 @@ pch.h Fast $(ProjectDir)src;%(AdditionalIncludeDirectories) + stdcpp20 Windows @@ -80,6 +75,7 @@ pch.h Fast $(ProjectDir)src;%(AdditionalIncludeDirectories) + stdcpp20 Windows diff --git a/RendererDirect3D12/src/CGI/CommandBufferD3D12.h b/RendererDirect3D12/src/CGI/CommandBufferD3D12.h index 7bbf5a1..3f5ba0b 100644 --- a/RendererDirect3D12/src/CGI/CommandBufferD3D12.h +++ b/RendererDirect3D12/src/CGI/CommandBufferD3D12.h @@ -1,71 +1,68 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class CommandBufferD3D12 : public BaseCommandBuffer { - class CommandBufferD3D12 : public BaseCommandBuffer - { - ComPtr _pOneTimeCommandAllocator; - ComPtr _pCommandLists[BaseRenderer::s_ringBufferSize]; - RP::PcD3DRenderPass _pRenderPass = nullptr; - RP::PcD3DFramebuffer _pFramebuffer = nullptr; - Vector _vClearValues; - Vector _vAttachmentStates; - Vector _vBarriers; - int _subpassIndex = 0; + ComPtr _pOneTimeCommandAllocator; + ComPtr _pCommandLists[BaseRenderer::s_ringBufferSize]; + RP::PcD3DRenderPass _pRenderPass = nullptr; + RP::PcD3DFramebuffer _pFramebuffer = nullptr; + Vector _vClearValues; + Vector _vAttachmentStates; + Vector _vBarriers; + int _subpassIndex = 0; - public: - CommandBufferD3D12(); - virtual ~CommandBufferD3D12() override; + public: + CommandBufferD3D12(); + virtual ~CommandBufferD3D12() override; - virtual void Init() override; - virtual void Done() override; + virtual void Init() override; + virtual void Done() override; - virtual void InitOneTimeSubmit() override; - virtual void DoneOneTimeSubmit() override; + virtual void InitOneTimeSubmit() override; + virtual void DoneOneTimeSubmit() override; - virtual void Begin() override; - virtual void End() override; + virtual void Begin() override; + virtual void End() override; - virtual void PipelineImageMemoryBarrier(TexturePtr tex, ImageLayout oldLayout, ImageLayout newLayout, Range mipLevels, Range arrayLayers) override; + virtual void PipelineImageMemoryBarrier(TexturePtr tex, ImageLayout oldLayout, ImageLayout newLayout, Range mipLevels, Range arrayLayers) override; - virtual void BeginRenderPass(RPHandle renderPassHandle, FBHandle framebufferHandle, - std::initializer_list ilClearValues, ViewportScissorFlags vsf) override; - virtual void NextSubpass() override; - virtual void EndRenderPass() override; + virtual void BeginRenderPass(RPHandle renderPassHandle, FBHandle framebufferHandle, + std::initializer_list ilClearValues, ViewportScissorFlags vsf) override; + virtual void NextSubpass() override; + virtual void EndRenderPass() override; - virtual void BindPipeline(PipelinePtr pipe) override; - virtual void SetViewport(std::initializer_list il, float minDepth, float maxDepth) override; - virtual void SetScissor(std::initializer_list il) override; - virtual void SetBlendConstants(const float* p) override; + virtual void BindPipeline(PipelinePtr pipe) override; + virtual void SetViewport(std::initializer_list il, float minDepth, float maxDepth) override; + virtual void SetScissor(std::initializer_list il) override; + virtual void SetBlendConstants(const float* p) override; - virtual void BindVertexBuffers(GeometryPtr geo, UINT32 bindingsFilter) override; - virtual void BindIndexBuffer(GeometryPtr geo) override; + virtual void BindVertexBuffers(GeometryPtr geo, UINT32 bindingsFilter) override; + virtual void BindIndexBuffer(GeometryPtr geo) override; - virtual bool BindDescriptors(ShaderPtr shader, int setNumber, CSHandle complexSetHandle) override; - virtual bool BindDescriptors(ShaderPtr shader, int setNumber, GeometryPtr geo, int sbIndex) override; - virtual void PushConstants(ShaderPtr shader, int offset, int size, const void* p, ShaderStageFlags stageFlags) override; + virtual bool BindDescriptors(ShaderPtr shader, int setNumber, CSHandle complexSetHandle) override; + virtual bool BindDescriptors(ShaderPtr shader, int setNumber, GeometryPtr geo, int sbIndex) override; + virtual void PushConstants(ShaderPtr shader, int offset, int size, const void* p, ShaderStageFlags stageFlags) override; - virtual void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) override; - virtual void DrawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) override; - virtual void Dispatch(int groupCountX, int groupCountY, int groupCountZ) override; - virtual void DispatchMesh(int groupCountX, int groupCountY, int groupCountZ) override; - virtual void TraceRays(int width, int height, int depth) override; + virtual void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) override; + virtual void DrawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) override; + virtual void Dispatch(int groupCountX, int groupCountY, int groupCountZ) override; + virtual void DispatchMesh(int groupCountX, int groupCountY, int groupCountZ) override; + virtual void TraceRays(int width, int height, int depth) override; - virtual void ProfilerBeginEvent(UINT32 color, CSZ text) override; - virtual void ProfilerEndEvent() override; - virtual void ProfilerSetMarker(UINT32 color, CSZ text) override; + virtual void ProfilerBeginEvent(UINT32 color, CSZ text) override; + virtual void ProfilerEndEvent() override; + virtual void ProfilerSetMarker(UINT32 color, CSZ text) override; - // - // D3D12 - // + // + // D3D12 + // - ID3D12GraphicsCommandList3* GetD3DGraphicsCommandList() const; + ID3D12GraphicsCommandList3* GetD3DGraphicsCommandList() const; - void PrepareSubpass(); - }; - VERUS_TYPEDEFS(CommandBufferD3D12); - } + void PrepareSubpass(); + }; + VERUS_TYPEDEFS(CommandBufferD3D12); } diff --git a/RendererDirect3D12/src/CGI/DescriptorHeap.h b/RendererDirect3D12/src/CGI/DescriptorHeap.h index 41bb70b..5bb3c76 100644 --- a/RendererDirect3D12/src/CGI/DescriptorHeap.h +++ b/RendererDirect3D12/src/CGI/DescriptorHeap.h @@ -1,61 +1,58 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class DescriptorHeap { - class DescriptorHeap - { - ComPtr _pDescriptorHeap; - CD3DX12_CPU_DESCRIPTOR_HANDLE _hCPUHandleForHeapStart; - CD3DX12_GPU_DESCRIPTOR_HANDLE _hGPUHandleForHeapStart; - D3D12_DESCRIPTOR_HEAP_TYPE _type = D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; - UINT _handleIncrementSize = 0; + ComPtr _pDescriptorHeap; + CD3DX12_CPU_DESCRIPTOR_HANDLE _hCPUHandleForHeapStart; + CD3DX12_GPU_DESCRIPTOR_HANDLE _hGPUHandleForHeapStart; + D3D12_DESCRIPTOR_HEAP_TYPE _type = D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; + UINT _handleIncrementSize = 0; - public: - void Reset() { VERUS_COM_RELEASE_CHECK(_pDescriptorHeap.Get()); _pDescriptorHeap.Reset(); } + public: + void Reset() { VERUS_COM_RELEASE_CHECK(_pDescriptorHeap.Get()); _pDescriptorHeap.Reset(); } - ID3D12DescriptorHeap* GetD3DDescriptorHeap() const { return _pDescriptorHeap.Get(); } + ID3D12DescriptorHeap* GetD3DDescriptorHeap() const { return _pDescriptorHeap.Get(); } - void Create(ID3D12Device* pDevice, D3D12_DESCRIPTOR_HEAP_TYPE type, int count, bool shaderVisible = false); + void Create(ID3D12Device* pDevice, D3D12_DESCRIPTOR_HEAP_TYPE type, int count, bool shaderVisible = false); - CD3DX12_CPU_DESCRIPTOR_HANDLE AtCPU(int index) const; - CD3DX12_GPU_DESCRIPTOR_HANDLE AtGPU(int index) const; + CD3DX12_CPU_DESCRIPTOR_HANDLE AtCPU(int index) const; + CD3DX12_GPU_DESCRIPTOR_HANDLE AtGPU(int index) const; - D3D12_DESCRIPTOR_HEAP_TYPE GetType() const { return _type; } - UINT GetHandleIncrementSize() const { return _handleIncrementSize; } - }; - VERUS_TYPEDEFS(DescriptorHeap); + D3D12_DESCRIPTOR_HEAP_TYPE GetType() const { return _type; } + UINT GetHandleIncrementSize() const { return _handleIncrementSize; } + }; + VERUS_TYPEDEFS(DescriptorHeap); - struct HandlePair - { - CD3DX12_CPU_DESCRIPTOR_HANDLE _hCPU; - CD3DX12_GPU_DESCRIPTOR_HANDLE _hGPU; + struct HandlePair + { + CD3DX12_CPU_DESCRIPTOR_HANDLE _hCPU; + CD3DX12_GPU_DESCRIPTOR_HANDLE _hGPU; - HandlePair( - CD3DX12_CPU_DESCRIPTOR_HANDLE hCPU = D3D12_DEFAULT, - CD3DX12_GPU_DESCRIPTOR_HANDLE hGPU = D3D12_DEFAULT) : _hCPU(hCPU), _hGPU(hGPU) {} - }; - VERUS_TYPEDEFS(HandlePair); + HandlePair( + CD3DX12_CPU_DESCRIPTOR_HANDLE hCPU = D3D12_DEFAULT, + CD3DX12_GPU_DESCRIPTOR_HANDLE hGPU = D3D12_DEFAULT) : _hCPU(hCPU), _hGPU(hGPU) {} + }; + VERUS_TYPEDEFS(HandlePair); - // This descriptor heap should be refilled every frame: - class DynamicDescriptorHeap : public DescriptorHeap - { - int _capacity = 0; - int _offset = 0; - UINT64 _currentFrame = UINT64_MAX; - UINT64 _peakLoad = 0; + // This descriptor heap should be refilled every frame: + class DynamicDescriptorHeap : public DescriptorHeap + { + int _capacity = 0; + int _offset = 0; + UINT64 _currentFrame = UINT64_MAX; + UINT64 _peakLoad = 0; - public: - void Create(ID3D12Device* pDevice, D3D12_DESCRIPTOR_HEAP_TYPE type, int count, int staticCount = 0, bool shaderVisible = false); + public: + void Create(ID3D12Device* pDevice, D3D12_DESCRIPTOR_HEAP_TYPE type, int count, int staticCount = 0, bool shaderVisible = false); - HandlePair GetNextHandlePair(int count = 1); - HandlePair GetStaticHandlePair(int index); + HandlePair GetNextHandlePair(int count = 1); + HandlePair GetStaticHandlePair(int index); - int GetCapacity() const { return _capacity; } - int GetOffset() const { return _offset; } - }; - VERUS_TYPEDEFS(DynamicDescriptorHeap); - } + int GetCapacity() const { return _capacity; } + int GetOffset() const { return _offset; } + }; + VERUS_TYPEDEFS(DynamicDescriptorHeap); } diff --git a/RendererDirect3D12/src/CGI/ExtRealityD3D12.h b/RendererDirect3D12/src/CGI/ExtRealityD3D12.h index 5998f08..29beae0 100644 --- a/RendererDirect3D12/src/CGI/ExtRealityD3D12.h +++ b/RendererDirect3D12/src/CGI/ExtRealityD3D12.h @@ -1,67 +1,64 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class RendererD3D12; + + class ExtRealityD3D12 : public BaseExtReality { - class RendererD3D12; - - class ExtRealityD3D12 : public BaseExtReality + struct SwapChainEx { - struct SwapChainEx - { - XrSwapchain _handle = XR_NULL_HANDLE; - int32_t _width = 0; - int32_t _height = 0; - Vector _vImages; - DescriptorHeap _dhImageViews; - }; - - Vector _vSwapChains; - LUID _adapterLuid; - D3D_FEATURE_LEVEL _minFeatureLevel = D3D_FEATURE_LEVEL_11_0; - - public: - ExtRealityD3D12(); - virtual ~ExtRealityD3D12() override; - - virtual void Init() override; - virtual void Done() override; - - void InitByRenderer(RendererD3D12* pRenderer); - - private: - void GetSystem(); - void CreateSwapChains(ID3D12Device* pDevice, int64_t format); - void CreateImageView(ID3D12Device* pDevice, int64_t format, XrSwapchainImageD3D12KHR& image, D3D12_CPU_DESCRIPTOR_HANDLE handle); - virtual XrSwapchain GetSwapChain(int viewIndex) override; - virtual void GetSwapChainSize(int viewIndex, int32_t& w, int32_t& h) override; - - public: - LUID GetAdapterLuid() const { return _adapterLuid; } - D3D_FEATURE_LEVEL GetMinFeatureLevel() const { return _minFeatureLevel; } - ID3D12Resource* GetD3DResource(int viewIndex, int imageIndex) const; - D3D12_CPU_DESCRIPTOR_HANDLE GetRTV(int viewIndex, int imageIndex) const; - - virtual void CreateActions() override; - virtual void PollEvents() override; - virtual void SyncActions(UINT32 activeActionSetsMask) override; - - virtual bool GetActionStateBoolean(int actionIndex, bool& currentState, bool* pChangedState, int subaction) override; - virtual bool GetActionStateFloat(int actionIndex, float& currentState, bool* pChangedState, int subaction) override; - virtual bool GetActionStatePose(int actionIndex, bool& currentState, Math::RPose pose, int subaction) override; - - virtual void BeginFrame() override; - virtual int LocateViews() override; - virtual void BeginView(int viewIndex, RViewDesc viewDesc) override; - virtual void AcquireSwapChainImage() override; - virtual void EndView(int viewIndex) override; - virtual void EndFrame() override; - - virtual void BeginAreaUpdate() override; - virtual void EndAreaUpdate(PcVector4 pUserOffset) override; + XrSwapchain _handle = XR_NULL_HANDLE; + int32_t _width = 0; + int32_t _height = 0; + Vector _vImages; + DescriptorHeap _dhImageViews; }; - VERUS_TYPEDEFS(ExtRealityD3D12); - } + + Vector _vSwapChains; + LUID _adapterLuid; + D3D_FEATURE_LEVEL _minFeatureLevel = D3D_FEATURE_LEVEL_11_0; + + public: + ExtRealityD3D12(); + virtual ~ExtRealityD3D12() override; + + virtual void Init() override; + virtual void Done() override; + + void InitByRenderer(RendererD3D12* pRenderer); + + private: + void GetSystem(); + void CreateSwapChains(ID3D12Device* pDevice, int64_t format); + void CreateImageView(ID3D12Device* pDevice, int64_t format, XrSwapchainImageD3D12KHR& image, D3D12_CPU_DESCRIPTOR_HANDLE handle); + virtual XrSwapchain GetSwapChain(int viewIndex) override; + virtual void GetSwapChainSize(int viewIndex, int32_t& w, int32_t& h) override; + + public: + LUID GetAdapterLuid() const { return _adapterLuid; } + D3D_FEATURE_LEVEL GetMinFeatureLevel() const { return _minFeatureLevel; } + ID3D12Resource* GetD3DResource(int viewIndex, int imageIndex) const; + D3D12_CPU_DESCRIPTOR_HANDLE GetRTV(int viewIndex, int imageIndex) const; + + virtual void CreateActions() override; + virtual void PollEvents() override; + virtual void SyncActions(UINT32 activeActionSetsMask) override; + + virtual bool GetActionStateBoolean(int actionIndex, bool& currentState, bool* pChangedState, int subaction) override; + virtual bool GetActionStateFloat(int actionIndex, float& currentState, bool* pChangedState, int subaction) override; + virtual bool GetActionStatePose(int actionIndex, bool& currentState, Math::RPose pose, int subaction) override; + + virtual void BeginFrame() override; + virtual int LocateViews() override; + virtual void BeginView(int viewIndex, RViewDesc viewDesc) override; + virtual void AcquireSwapChainImage() override; + virtual void EndView(int viewIndex) override; + virtual void EndFrame() override; + + virtual void BeginAreaUpdate() override; + virtual void EndAreaUpdate(PcVector4 pUserOffset) override; + }; + VERUS_TYPEDEFS(ExtRealityD3D12); } diff --git a/RendererDirect3D12/src/CGI/GeometryD3D12.h b/RendererDirect3D12/src/CGI/GeometryD3D12.h index 0e2b067..2ce658a 100644 --- a/RendererDirect3D12/src/CGI/GeometryD3D12.h +++ b/RendererDirect3D12/src/CGI/GeometryD3D12.h @@ -1,72 +1,69 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class GeometryD3D12 : public BaseGeometry { - class GeometryD3D12 : public BaseGeometry + struct BufferEx { - struct BufferEx - { - D3D12MA::Allocation* _pMaAllocation = nullptr; - ComPtr _pBuffer; - UINT64 _bufferSize = 0; - INT64 _utilization = -1; - }; - - struct VertexBufferEx : BufferEx - { - D3D12_VERTEX_BUFFER_VIEW _bufferView[BaseRenderer::s_ringBufferSize] = {}; - }; - - struct StructuredBufferEx : BufferEx - { - DescriptorHeap _dhDynamicOffsets; - int _structSize = 0; - }; - - Vector _vVertexBuffers; - BufferEx _indexBuffer; - Vector _vStagingVertexBuffers; - BufferEx _stagingIndexBuffer; - Vector _vStructuredBuffers; - D3D12_INDEX_BUFFER_VIEW _indexBufferView[BaseRenderer::s_ringBufferSize] = {}; - Vector _vInputElementDescs; - Vector _vStrides; - - public: - GeometryD3D12(); - virtual ~GeometryD3D12() override; - - virtual void Init(RcGeometryDesc desc) override; - virtual void Done() override; - - virtual void CreateVertexBuffer(int count, int binding) override; - virtual void UpdateVertexBuffer(const void* p, int binding, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - - virtual void CreateIndexBuffer(int count) override; - virtual void UpdateIndexBuffer(const void* p, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - - virtual void CreateStorageBuffer(int count, int structSize, int sbIndex, ShaderStageFlags stageFlags) override; - virtual void UpdateStorageBuffer(const void* p, int sbIndex, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - virtual int GetStorageBufferStructSize(int sbIndex) const override; - - virtual Continue Scheduled_Update() override; - - // - // D3D12 - // - - D3D12_INPUT_LAYOUT_DESC GetD3DInputLayoutDesc(UINT32 bindingsFilter, Vector& vInputElementDescs) const; - - int GetVertexBufferCount() const { return Utils::Cast32(_vVertexBuffers.size()); } - const D3D12_VERTEX_BUFFER_VIEW* GetD3DVertexBufferView(int binding) const; - const D3D12_INDEX_BUFFER_VIEW* GetD3DIndexBufferView() const; - CD3DX12_GPU_DESCRIPTOR_HANDLE CopyStructuredBufferView(int sbIndex) const; - - void UpdateUtilization() const; + D3D12MA::Allocation* _pMaAllocation = nullptr; + ComPtr _pBuffer; + UINT64 _bufferSize = 0; + INT64 _utilization = -1; }; - VERUS_TYPEDEFS(GeometryD3D12); - } + + struct VertexBufferEx : BufferEx + { + D3D12_VERTEX_BUFFER_VIEW _bufferView[BaseRenderer::s_ringBufferSize] = {}; + }; + + struct StructuredBufferEx : BufferEx + { + DescriptorHeap _dhDynamicOffsets; + int _structSize = 0; + }; + + Vector _vVertexBuffers; + BufferEx _indexBuffer; + Vector _vStagingVertexBuffers; + BufferEx _stagingIndexBuffer; + Vector _vStructuredBuffers; + D3D12_INDEX_BUFFER_VIEW _indexBufferView[BaseRenderer::s_ringBufferSize] = {}; + Vector _vInputElementDescs; + Vector _vStrides; + + public: + GeometryD3D12(); + virtual ~GeometryD3D12() override; + + virtual void Init(RcGeometryDesc desc) override; + virtual void Done() override; + + virtual void CreateVertexBuffer(int count, int binding) override; + virtual void UpdateVertexBuffer(const void* p, int binding, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + + virtual void CreateIndexBuffer(int count) override; + virtual void UpdateIndexBuffer(const void* p, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + + virtual void CreateStorageBuffer(int count, int structSize, int sbIndex, ShaderStageFlags stageFlags) override; + virtual void UpdateStorageBuffer(const void* p, int sbIndex, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + virtual int GetStorageBufferStructSize(int sbIndex) const override; + + virtual Continue Scheduled_Update() override; + + // + // D3D12 + // + + D3D12_INPUT_LAYOUT_DESC GetD3DInputLayoutDesc(UINT32 bindingsFilter, Vector& vInputElementDescs) const; + + int GetVertexBufferCount() const { return Utils::Cast32(_vVertexBuffers.size()); } + const D3D12_VERTEX_BUFFER_VIEW* GetD3DVertexBufferView(int binding) const; + const D3D12_INDEX_BUFFER_VIEW* GetD3DIndexBufferView() const; + CD3DX12_GPU_DESCRIPTOR_HANDLE CopyStructuredBufferView(int sbIndex) const; + + void UpdateUtilization() const; + }; + VERUS_TYPEDEFS(GeometryD3D12); } diff --git a/RendererDirect3D12/src/CGI/Native.h b/RendererDirect3D12/src/CGI/Native.h index 5a0155b..685d026 100644 --- a/RendererDirect3D12/src/CGI/Native.h +++ b/RendererDirect3D12/src/CGI/Native.h @@ -1,27 +1,24 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI - { - D3D12_COMPARISON_FUNC ToNativeCompareOp(CompareOp compareOp); + D3D12_COMPARISON_FUNC ToNativeCompareOp(CompareOp compareOp); - UINT ToNativeCubeMapFace(CubeMapFace face); + UINT ToNativeCubeMapFace(CubeMapFace face); - D3D12_FILL_MODE ToNativePolygonMode(PolygonMode polygonMode); + D3D12_FILL_MODE ToNativePolygonMode(PolygonMode polygonMode); - D3D12_CULL_MODE ToNativeCullMode(CullMode cullMode); + D3D12_CULL_MODE ToNativeCullMode(CullMode cullMode); - D3D_PRIMITIVE_TOPOLOGY ToNativePrimitiveTopology(PrimitiveTopology primitiveTopology); - D3D12_PRIMITIVE_TOPOLOGY_TYPE ToNativePrimitiveTopologyType(PrimitiveTopology primitiveTopology); + D3D_PRIMITIVE_TOPOLOGY ToNativePrimitiveTopology(PrimitiveTopology primitiveTopology); + D3D12_PRIMITIVE_TOPOLOGY_TYPE ToNativePrimitiveTopologyType(PrimitiveTopology primitiveTopology); - D3D12_RESOURCE_STATES ToNativeImageLayout(ImageLayout layout); + D3D12_RESOURCE_STATES ToNativeImageLayout(ImageLayout layout); - DXGI_FORMAT ToNativeFormat(Format format, bool typeless); - DXGI_FORMAT ToNativeSampledDepthFormat(Format format); + DXGI_FORMAT ToNativeFormat(Format format, bool typeless); + DXGI_FORMAT ToNativeSampledDepthFormat(Format format); - CSZ ToNativeSemanticName(ViaUsage usage); - DXGI_FORMAT ToNativeFormat(ViaUsage usage, ViaType type, int components); - } + CSZ ToNativeSemanticName(ViaUsage usage); + DXGI_FORMAT ToNativeFormat(ViaUsage usage, ViaType type, int components); } diff --git a/RendererDirect3D12/src/CGI/PipelineD3D12.h b/RendererDirect3D12/src/CGI/PipelineD3D12.h index 28bf067..ff8344b 100644 --- a/RendererDirect3D12/src/CGI/PipelineD3D12.h +++ b/RendererDirect3D12/src/CGI/PipelineD3D12.h @@ -1,37 +1,34 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class PipelineD3D12 : public BasePipeline { - class PipelineD3D12 : public BasePipeline - { - ComPtr _pPipelineState; - ID3D12RootSignature* _pRootSignature = nullptr; - D3D_PRIMITIVE_TOPOLOGY _topology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; - bool _compute = false; + ComPtr _pPipelineState; + ID3D12RootSignature* _pRootSignature = nullptr; + D3D_PRIMITIVE_TOPOLOGY _topology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; + bool _compute = false; - public: - PipelineD3D12(); - virtual ~PipelineD3D12() override; + public: + PipelineD3D12(); + virtual ~PipelineD3D12() override; - virtual void Init(RcPipelineDesc desc) override; - virtual void Done() override; + virtual void Init(RcPipelineDesc desc) override; + virtual void Done() override; - // - // D3D12 - // + // + // D3D12 + // - VERUS_P(void InitCompute(RcPipelineDesc desc)); - VERUS_P(void InitMeshShading(RcPipelineDesc desc)); - D3D12_SHADER_BYTECODE ToBytecode(ID3DBlob* pBlob); - bool IsCompute() const { return _compute; } - ID3D12PipelineState* GetD3DPipelineState() const { return _pPipelineState.Get(); } - ID3D12RootSignature* GetD3DRootSignature() const { return _pRootSignature; } - D3D_PRIMITIVE_TOPOLOGY GetD3DPrimitiveTopology() const { return _topology; } - void FillBlendStateRenderTargets(RcPipelineDesc desc, int attachmentCount, D3D12_BLEND_DESC& blendDesc); - }; - VERUS_TYPEDEFS(PipelineD3D12); - } + VERUS_P(void InitCompute(RcPipelineDesc desc)); + VERUS_P(void InitMeshShading(RcPipelineDesc desc)); + D3D12_SHADER_BYTECODE ToBytecode(ID3DBlob* pBlob); + bool IsCompute() const { return _compute; } + ID3D12PipelineState* GetD3DPipelineState() const { return _pPipelineState.Get(); } + ID3D12RootSignature* GetD3DRootSignature() const { return _pRootSignature; } + D3D_PRIMITIVE_TOPOLOGY GetD3DPrimitiveTopology() const { return _topology; } + void FillBlendStateRenderTargets(RcPipelineDesc desc, int attachmentCount, D3D12_BLEND_DESC& blendDesc); + }; + VERUS_TYPEDEFS(PipelineD3D12); } diff --git a/RendererDirect3D12/src/CGI/RenderPass.h b/RendererDirect3D12/src/CGI/RenderPass.h index e30b204..1e42977 100644 --- a/RendererDirect3D12/src/CGI/RenderPass.h +++ b/RendererDirect3D12/src/CGI/RenderPass.h @@ -1,80 +1,74 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI::RP { - namespace CGI + class D3DAttachment { - namespace RP - { - class D3DAttachment - { - public: - Format _format = Format::unormR8G8B8A8; - int _sampleCount = 1; - Attachment::LoadOp _loadOp = Attachment::LoadOp::load; - Attachment::StoreOp _storeOp = Attachment::StoreOp::store; - Attachment::LoadOp _stencilLoadOp = Attachment::LoadOp::dontCare; - Attachment::StoreOp _stencilStoreOp = Attachment::StoreOp::dontCare; - D3D12_RESOURCE_STATES _initialState = D3D12_RESOURCE_STATE_COMMON; - D3D12_RESOURCE_STATES _finalState = D3D12_RESOURCE_STATE_COMMON; - int _clearSubpassIndex = -1; - }; - VERUS_TYPEDEFS(D3DAttachment); + public: + Format _format = Format::unormR8G8B8A8; + int _sampleCount = 1; + Attachment::LoadOp _loadOp = Attachment::LoadOp::load; + Attachment::StoreOp _storeOp = Attachment::StoreOp::store; + Attachment::LoadOp _stencilLoadOp = Attachment::LoadOp::dontCare; + Attachment::StoreOp _stencilStoreOp = Attachment::StoreOp::dontCare; + D3D12_RESOURCE_STATES _initialState = D3D12_RESOURCE_STATE_COMMON; + D3D12_RESOURCE_STATES _finalState = D3D12_RESOURCE_STATE_COMMON; + int _clearSubpassIndex = -1; + }; + VERUS_TYPEDEFS(D3DAttachment); - class D3DRef - { - public: - int _index = -1; - D3D12_RESOURCE_STATES _state = D3D12_RESOURCE_STATE_COMMON; - }; - VERUS_TYPEDEFS(D3DRef); + class D3DRef + { + public: + int _index = -1; + D3D12_RESOURCE_STATES _state = D3D12_RESOURCE_STATE_COMMON; + }; + VERUS_TYPEDEFS(D3DRef); - class D3DSubpass - { - public: - Vector _vInput; - Vector _vColor; - Vector _vResolve; - Vector _vPreserve; - D3DRef _depthStencil; - }; - VERUS_TYPEDEFS(D3DSubpass); + class D3DSubpass + { + public: + Vector _vInput; + Vector _vColor; + Vector _vResolve; + Vector _vPreserve; + D3DRef _depthStencil; + }; + VERUS_TYPEDEFS(D3DSubpass); - class D3DDependency - { - public: - }; - VERUS_TYPEDEFS(D3DDependency); + class D3DDependency + { + public: + }; + VERUS_TYPEDEFS(D3DDependency); - class D3DRenderPass - { - public: - Vector _vAttachments; - Vector _vSubpasses; - }; - VERUS_TYPEDEFS(D3DRenderPass); + class D3DRenderPass + { + public: + Vector _vAttachments; + Vector _vSubpasses; + }; + VERUS_TYPEDEFS(D3DRenderPass); - class D3DFramebufferSubpass - { - public: - Vector _vResources; - DescriptorHeap _dhRTVs; - DescriptorHeap _dhDSV; - }; - VERUS_TYPEDEFS(D3DFramebufferSubpass); + class D3DFramebufferSubpass + { + public: + Vector _vResources; + DescriptorHeap _dhRTVs; + DescriptorHeap _dhDSV; + }; + VERUS_TYPEDEFS(D3DFramebufferSubpass); - class D3DFramebuffer - { - public: - Vector _vResources; - Vector _vSubpasses; - int _width = 0; - int _height = 0; - int _mipLevels = 1; - CubeMapFace _cubeMapFace = CubeMapFace::none; - }; - VERUS_TYPEDEFS(D3DFramebuffer); - } - } + class D3DFramebuffer + { + public: + Vector _vResources; + Vector _vSubpasses; + int _width = 0; + int _height = 0; + int _mipLevels = 1; + CubeMapFace _cubeMapFace = CubeMapFace::none; + }; + VERUS_TYPEDEFS(D3DFramebuffer); } diff --git a/RendererDirect3D12/src/CGI/RendererD3D12.h b/RendererDirect3D12/src/CGI/RendererD3D12.h index c42efc5..d49ee77 100644 --- a/RendererDirect3D12/src/CGI/RendererD3D12.h +++ b/RendererDirect3D12/src/CGI/RendererD3D12.h @@ -1,129 +1,126 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + typedef Store TStoreCommandBuffers; + typedef Store TStoreGeometry; + typedef Store TStorePipelines; + typedef Store TStoreShaders; + typedef Store TStoreTextures; + class RendererD3D12 : public Singleton, public BaseRenderer, + private TStoreCommandBuffers, private TStoreGeometry, private TStorePipelines, private TStoreShaders, private TStoreTextures { - typedef Store TStoreCommandBuffers; - typedef Store TStoreGeometry; - typedef Store TStorePipelines; - typedef Store TStoreShaders; - typedef Store TStoreTextures; - class RendererD3D12 : public Singleton, public BaseRenderer, - private TStoreCommandBuffers, private TStoreGeometry, private TStorePipelines, private TStoreShaders, private TStoreTextures - { - typedef Map> TMapCommandAllocators; + typedef Map> TMapCommandAllocators; - D3D12MA::Allocator* _pMaAllocator = nullptr; - ExtRealityD3D12 _extReality; - ComPtr _pDevice; - ComPtr _pCommandQueue; - ComPtr _pSwapChain; - Vector> _vSwapChainBuffers; - DescriptorHeap _dhSwapChainBuffersRTVs; + D3D12MA::Allocator* _pMaAllocator = nullptr; + ExtRealityD3D12 _extReality; + ComPtr _pDevice; + ComPtr _pCommandQueue; + ComPtr _pSwapChain; + Vector> _vSwapChainBuffers; + DescriptorHeap _dhSwapChainBuffersRTVs; - DynamicDescriptorHeap _dhViews; - DynamicDescriptorHeap _dhSamplers; - TMapCommandAllocators _mapCommandAllocators[s_ringBufferSize]; - ComPtr _pFence; - HANDLE _hFence = INVALID_HANDLE_VALUE; - HANDLE _hFrameLatencyWaitableObject = INVALID_HANDLE_VALUE; - UINT64 _nextFenceValue = 1; - UINT64 _fenceValues[s_ringBufferSize] = {}; + DynamicDescriptorHeap _dhViews; + DynamicDescriptorHeap _dhSamplers; + TMapCommandAllocators _mapCommandAllocators[s_ringBufferSize]; + ComPtr _pFence; + HANDLE _hFence = INVALID_HANDLE_VALUE; + HANDLE _hFrameLatencyWaitableObject = INVALID_HANDLE_VALUE; + UINT64 _nextFenceValue = 1; + UINT64 _fenceValues[s_ringBufferSize] = {}; - Vector _vSamplers; - Vector _vRenderPasses; - Vector _vFramebuffers; - D3D_FEATURE_LEVEL _featureLevel = D3D_FEATURE_LEVEL_11_0; - DXGI_SWAP_CHAIN_DESC1 _swapChainDesc = {}; + Vector _vSamplers; + Vector _vRenderPasses; + Vector _vFramebuffers; + D3D_FEATURE_LEVEL _featureLevel = D3D_FEATURE_LEVEL_11_0; + DXGI_SWAP_CHAIN_DESC1 _swapChainDesc = {}; - public: - RendererD3D12(); - ~RendererD3D12(); + public: + RendererD3D12(); + ~RendererD3D12(); - virtual void ReleaseMe() override; + virtual void ReleaseMe() override; - void Init(); - void Done(); + void Init(); + void Done(); - private: - static void EnableDebugLayer(); - static ComPtr CreateFactory(); - ComPtr GetAdapter(ComPtr pFactory, D3D_FEATURE_LEVEL featureLevel) const; - static bool CheckFeatureSupportAllowTearing(ComPtr pFactory); - void CreateSwapChainBuffersRTVs(); - void InitD3D(); - void WaitForFrameLatencyWaitableObject(); + private: + static void EnableDebugLayer(); + static ComPtr CreateFactory(); + ComPtr GetAdapter(ComPtr pFactory, D3D_FEATURE_LEVEL featureLevel) const; + static bool CheckFeatureSupportAllowTearing(ComPtr pFactory); + void CreateSwapChainBuffersRTVs(); + void InitD3D(); + void WaitForFrameLatencyWaitableObject(); - public: - // - ComPtr CreateD3DCommandQueue(D3D12_COMMAND_LIST_TYPE type); - ComPtr CreateD3DCommandAllocator(D3D12_COMMAND_LIST_TYPE type); - ComPtr CreateD3DCommandList(D3D12_COMMAND_LIST_TYPE type, ComPtr pCommandAllocator); - ComPtr CreateD3DFence(); - UINT64 QueueSignal(); - void WaitForFenceValue(UINT64 value); - void QueueWaitIdle(); - void CreateSamplers(); + public: + // + ComPtr CreateD3DCommandQueue(D3D12_COMMAND_LIST_TYPE type); + ComPtr CreateD3DCommandAllocator(D3D12_COMMAND_LIST_TYPE type); + ComPtr CreateD3DCommandList(D3D12_COMMAND_LIST_TYPE type, ComPtr pCommandAllocator); + ComPtr CreateD3DFence(); + UINT64 QueueSignal(); + void WaitForFenceValue(UINT64 value); + void QueueWaitIdle(); + void CreateSamplers(); - ID3D12Device3* GetD3DDevice() const { return _pDevice.Get(); } - ID3D12CommandQueue* GetD3DCommandQueue() const { return _pCommandQueue.Get(); } - D3D12MA::Allocator* GetMaAllocator() const { return _pMaAllocator; } - ID3D12CommandAllocator* GetD3DCommandAllocator(int ringBufferIndex) const { return _mapCommandAllocators[ringBufferIndex].at(std::this_thread::get_id()).Get(); } - D3D12_STATIC_SAMPLER_DESC GetD3DStaticSamplerDesc(Sampler s) const; - // + ID3D12Device3* GetD3DDevice() const { return _pDevice.Get(); } + ID3D12CommandQueue* GetD3DCommandQueue() const { return _pCommandQueue.Get(); } + D3D12MA::Allocator* GetMaAllocator() const { return _pMaAllocator; } + ID3D12CommandAllocator* GetD3DCommandAllocator(int ringBufferIndex) const { return _mapCommandAllocators[ringBufferIndex].at(std::this_thread::get_id()).Get(); } + D3D12_STATIC_SAMPLER_DESC GetD3DStaticSamplerDesc(Sampler s) const; + // - virtual void ImGuiInit(RPHandle renderPassHandle) override; - virtual void ImGuiRenderDrawData() override; + virtual void ImGuiInit(RPHandle renderPassHandle) override; + virtual void ImGuiRenderDrawData() override; - virtual void ResizeSwapChain() override; + virtual void ResizeSwapChain() override; - virtual PBaseExtReality GetExtReality() override; + virtual PBaseExtReality GetExtReality() override; - // Which graphics API? - virtual Gapi GetGapi() override { return Gapi::direct3D12; } + // Which graphics API? + virtual Gapi GetGapi() override { return Gapi::direct3D12; } - // - virtual void BeginFrame() override; - virtual void AcquireSwapChainImage() override; - virtual void EndFrame() override; - virtual void WaitIdle() override; - virtual void OnMinimized() override; - // + // + virtual void BeginFrame() override; + virtual void AcquireSwapChainImage() override; + virtual void EndFrame() override; + virtual void WaitIdle() override; + virtual void OnMinimized() override; + // - // - virtual PBaseCommandBuffer InsertCommandBuffer() override; - virtual PBaseGeometry InsertGeometry() override; - virtual PBasePipeline InsertPipeline() override; - virtual PBaseShader InsertShader() override; - virtual PBaseTexture InsertTexture() override; + // + virtual PBaseCommandBuffer InsertCommandBuffer() override; + virtual PBaseGeometry InsertGeometry() override; + virtual PBasePipeline InsertPipeline() override; + virtual PBaseShader InsertShader() override; + virtual PBaseTexture InsertTexture() override; - virtual void DeleteCommandBuffer(PBaseCommandBuffer p) override; - virtual void DeleteGeometry(PBaseGeometry p) override; - virtual void DeletePipeline(PBasePipeline p) override; - virtual void DeleteShader(PBaseShader p) override; - virtual void DeleteTexture(PBaseTexture p) override; + virtual void DeleteCommandBuffer(PBaseCommandBuffer p) override; + virtual void DeleteGeometry(PBaseGeometry p) override; + virtual void DeletePipeline(PBasePipeline p) override; + virtual void DeleteShader(PBaseShader p) override; + virtual void DeleteTexture(PBaseTexture p) override; - virtual RPHandle CreateRenderPass(std::initializer_list ilA, std::initializer_list ilS, std::initializer_list ilD) override; - virtual FBHandle CreateFramebuffer(RPHandle renderPassHandle, std::initializer_list il, int w, int h, - int swapChainBufferIndex = -1, CubeMapFace cubeMapFace = CubeMapFace::none) override; - virtual void DeleteRenderPass(RPHandle handle) override; - virtual void DeleteFramebuffer(FBHandle handle) override; - int GetNextRenderPassIndex() const; - int GetNextFramebufferIndex() const; - RP::RcD3DRenderPass GetRenderPass(RPHandle handle) const; - RP::RcD3DFramebuffer GetFramebuffer(FBHandle handle) const; - // + virtual RPHandle CreateRenderPass(std::initializer_list ilA, std::initializer_list ilS, std::initializer_list ilD) override; + virtual FBHandle CreateFramebuffer(RPHandle renderPassHandle, std::initializer_list il, int w, int h, + int swapChainBufferIndex = -1, CubeMapFace cubeMapFace = CubeMapFace::none) override; + virtual void DeleteRenderPass(RPHandle handle) override; + virtual void DeleteFramebuffer(FBHandle handle) override; + int GetNextRenderPassIndex() const; + int GetNextFramebufferIndex() const; + RP::RcD3DRenderPass GetRenderPass(RPHandle handle) const; + RP::RcD3DFramebuffer GetFramebuffer(FBHandle handle) const; + // - RDynamicDescriptorHeap GetViewHeap() { return _dhViews; } - RDynamicDescriptorHeap GetSamplerHeap() { return _dhSamplers; } - void SetDescriptorHeaps(PBaseCommandBuffer p); + RDynamicDescriptorHeap GetViewHeap() { return _dhViews; } + RDynamicDescriptorHeap GetSamplerHeap() { return _dhSamplers; } + void SetDescriptorHeaps(PBaseCommandBuffer p); - virtual void UpdateUtilization() override; - }; - VERUS_TYPEDEFS(RendererD3D12); - } + virtual void UpdateUtilization() override; + }; + VERUS_TYPEDEFS(RendererD3D12); } #define VERUS_QREF_RENDERER_D3D12 CGI::PRendererD3D12 pRendererD3D12 = CGI::RendererD3D12::P() diff --git a/RendererDirect3D12/src/CGI/ShaderD3D12.cpp b/RendererDirect3D12/src/CGI/ShaderD3D12.cpp index 48112b8..41bc1b5 100644 --- a/RendererDirect3D12/src/CGI/ShaderD3D12.cpp +++ b/RendererDirect3D12/src/CGI/ShaderD3D12.cpp @@ -58,13 +58,13 @@ void ShaderD3D12::Init(CSZ source, CSZ sourceName, CSZ* branches) ComPtr pErrorMsgs; auto CheckErrorMsgs = [this](ComPtr& pErrorMsgs) - { - if (pErrorMsgs) { - OnError(static_cast(pErrorMsgs->GetBufferPointer())); - pErrorMsgs.Reset(); - } - }; + if (pErrorMsgs) + { + OnError(static_cast(pErrorMsgs->GetBufferPointer())); + pErrorMsgs.Reset(); + } + }; while (*branches) { @@ -197,12 +197,12 @@ void ShaderD3D12::Done() _pRootSignature.Reset(); // Can be shared with another shader, don't check ref count. - for (auto& x : _mapCompiled) + for (auto& [key, value] : _mapCompiled) { VERUS_FOR(i, +Stage::count) { - VERUS_COM_RELEASE_CHECK(x.second._pBlobs[i].Get()); - x.second._pBlobs[i].Reset(); + VERUS_COM_RELEASE_CHECK(value._pBlobs[i].Get()); + value._pBlobs[i].Reset(); } } @@ -693,19 +693,19 @@ void ShaderD3D12::UpdateDebugInfo( StringStream ss; auto PrintShaderVisibility = [&ss](D3D12_SHADER_VISIBILITY shaderVisibility) - { - switch (shaderVisibility) { - case D3D12_SHADER_VISIBILITY_ALL: ss << "All"; break; - case D3D12_SHADER_VISIBILITY_VERTEX: ss << "V"; break; - case D3D12_SHADER_VISIBILITY_HULL: ss << "H"; break; - case D3D12_SHADER_VISIBILITY_DOMAIN: ss << "D"; break; - case D3D12_SHADER_VISIBILITY_GEOMETRY: ss << "G"; break; - case D3D12_SHADER_VISIBILITY_PIXEL: ss << "P"; break; - case D3D12_SHADER_VISIBILITY_AMPLIFICATION: ss << "A"; break; - case D3D12_SHADER_VISIBILITY_MESH: ss << "M"; break; - } - }; + switch (shaderVisibility) + { + case D3D12_SHADER_VISIBILITY_ALL: ss << "All"; break; + case D3D12_SHADER_VISIBILITY_VERTEX: ss << "V"; break; + case D3D12_SHADER_VISIBILITY_HULL: ss << "H"; break; + case D3D12_SHADER_VISIBILITY_DOMAIN: ss << "D"; break; + case D3D12_SHADER_VISIBILITY_GEOMETRY: ss << "G"; break; + case D3D12_SHADER_VISIBILITY_PIXEL: ss << "P"; break; + case D3D12_SHADER_VISIBILITY_AMPLIFICATION: ss << "A"; break; + case D3D12_SHADER_VISIBILITY_MESH: ss << "M"; break; + } + }; int totalSize = 0; int index = 0; diff --git a/RendererDirect3D12/src/CGI/ShaderD3D12.h b/RendererDirect3D12/src/CGI/ShaderD3D12.h index b06de3d..c10673d 100644 --- a/RendererDirect3D12/src/CGI/ShaderD3D12.h +++ b/RendererDirect3D12/src/CGI/ShaderD3D12.h @@ -1,117 +1,114 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + struct ShaderInclude : public ID3DInclude { - struct ShaderInclude : public ID3DInclude + public: + virtual HRESULT STDMETHODCALLTYPE Open( + D3D_INCLUDE_TYPE IncludeType, + LPCSTR pFileName, + LPCVOID pParentData, + LPCVOID* ppData, + UINT* pBytes) override; + virtual HRESULT STDMETHODCALLTYPE Close(LPCVOID pData) override; + }; + VERUS_TYPEDEFS(ShaderInclude); + + class ShaderD3D12 : public BaseShader + { + public: + enum SET_MOD { - public: - virtual HRESULT STDMETHODCALLTYPE Open( - D3D_INCLUDE_TYPE IncludeType, - LPCSTR pFileName, - LPCVOID pParentData, - LPCVOID* ppData, - UINT* pBytes) override; - virtual HRESULT STDMETHODCALLTYPE Close(LPCVOID pData) override; + SET_MOD_TO_VIEW_HEAP = 0x10000 }; - VERUS_TYPEDEFS(ShaderInclude); - class ShaderD3D12 : public BaseShader + struct Compiled { - public: - enum SET_MOD - { - SET_MOD_TO_VIEW_HEAP = 0x10000 - }; - - struct Compiled - { - ComPtr _pBlobs[+Stage::count]; - String _entry; - int _stageCount = 0; - }; - VERUS_TYPEDEFS(Compiled); - - private: - typedef Map TMapCompiled; - - struct DescriptorSetDesc - { - Vector _vSamplers; - ComPtr _pConstantBuffer; - D3D12MA::Allocation* _pMaAllocation = nullptr; - DescriptorHeap _dhDynamicOffsets; - BYTE* _pMappedData = nullptr; - const void* _pSrc = nullptr; - int _size = 0; - int _alignedSize = 0; - int _capacity = 1; - int _capacityInBytes = 0; - int _offset = 0; - int _peakLoad = 0; - int _index = 0; - ShaderStageFlags _stageFlags = ShaderStageFlags::vs_fs; - bool _staticSamplersOnly = true; - }; - - struct ComplexSet - { - Vector _vTextures; - DescriptorHeap _dhViews; - DescriptorHeap _dhSamplers; - HandlePair _hpBase; - }; - VERUS_TYPEDEFS(ComplexSet); - - TMapCompiled _mapCompiled; - Vector _vDescriptorSetDesc; - Vector _vComplexSets; - ComPtr _pRootSignature; - String _debugInfo; - UINT64 _currentFrame = UINT64_MAX; - bool _compute = false; - - public: - ShaderD3D12(); - virtual ~ShaderD3D12() override; - - virtual void Init(CSZ source, CSZ sourceName, CSZ* branches) override; - virtual void Done() override; - - virtual void CreateDescriptorSet(int setNumber, const void* pSrc, int size, int capacity, std::initializer_list il, ShaderStageFlags stageFlags) override; - virtual void CreatePipelineLayout() override; - virtual CSHandle BindDescriptorSetTextures(int setNumber, std::initializer_list il, const int* pMipLevels, const int* pArrayLayers) override; - virtual void FreeDescriptorSet(CSHandle& complexSetHandle) override; - - virtual void BeginBindDescriptors() override; - virtual void EndBindDescriptors() override; - - // - // D3D12 - // - - RcCompiled GetCompiled(CSZ branch) const { return _mapCompiled.at(branch); } - - ID3D12RootSignature* GetD3DRootSignature() const { return _pRootSignature.Get(); } - - UINT ToRootParameterIndex(int setNumber) const; - bool TryRootConstants(int setNumber, RBaseCommandBuffer cb) const; - CD3DX12_GPU_DESCRIPTOR_HANDLE UpdateConstantBuffer(int setNumber, int complexSetHandle); - CD3DX12_GPU_DESCRIPTOR_HANDLE UpdateSamplers(int setNumber, int complexSetHandle) const; - int GetDescriptorSetCount() const { return static_cast(_vDescriptorSetDesc.size()); } - bool IsCompute() const { return _compute; } - - void OnError(CSZ s) const; - - void UpdateDebugInfo( - const Vector& vRootParams, - const Vector& vStaticSamplers, - D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags); - - void UpdateUtilization() const; + ComPtr _pBlobs[+Stage::count]; + String _entry; + int _stageCount = 0; }; - VERUS_TYPEDEFS(ShaderD3D12); - } + VERUS_TYPEDEFS(Compiled); + + private: + typedef Map TMapCompiled; + + struct DescriptorSetDesc + { + Vector _vSamplers; + ComPtr _pConstantBuffer; + D3D12MA::Allocation* _pMaAllocation = nullptr; + DescriptorHeap _dhDynamicOffsets; + BYTE* _pMappedData = nullptr; + const void* _pSrc = nullptr; + int _size = 0; + int _alignedSize = 0; + int _capacity = 1; + int _capacityInBytes = 0; + int _offset = 0; + int _peakLoad = 0; + int _index = 0; + ShaderStageFlags _stageFlags = ShaderStageFlags::vs_fs; + bool _staticSamplersOnly = true; + }; + + struct ComplexSet + { + Vector _vTextures; + DescriptorHeap _dhViews; + DescriptorHeap _dhSamplers; + HandlePair _hpBase; + }; + VERUS_TYPEDEFS(ComplexSet); + + TMapCompiled _mapCompiled; + Vector _vDescriptorSetDesc; + Vector _vComplexSets; + ComPtr _pRootSignature; + String _debugInfo; + UINT64 _currentFrame = UINT64_MAX; + bool _compute = false; + + public: + ShaderD3D12(); + virtual ~ShaderD3D12() override; + + virtual void Init(CSZ source, CSZ sourceName, CSZ* branches) override; + virtual void Done() override; + + virtual void CreateDescriptorSet(int setNumber, const void* pSrc, int size, int capacity, std::initializer_list il, ShaderStageFlags stageFlags) override; + virtual void CreatePipelineLayout() override; + virtual CSHandle BindDescriptorSetTextures(int setNumber, std::initializer_list il, const int* pMipLevels, const int* pArrayLayers) override; + virtual void FreeDescriptorSet(CSHandle& complexSetHandle) override; + + virtual void BeginBindDescriptors() override; + virtual void EndBindDescriptors() override; + + // + // D3D12 + // + + RcCompiled GetCompiled(CSZ branch) const { return _mapCompiled.at(branch); } + + ID3D12RootSignature* GetD3DRootSignature() const { return _pRootSignature.Get(); } + + UINT ToRootParameterIndex(int setNumber) const; + bool TryRootConstants(int setNumber, RBaseCommandBuffer cb) const; + CD3DX12_GPU_DESCRIPTOR_HANDLE UpdateConstantBuffer(int setNumber, int complexSetHandle); + CD3DX12_GPU_DESCRIPTOR_HANDLE UpdateSamplers(int setNumber, int complexSetHandle) const; + int GetDescriptorSetCount() const { return static_cast(_vDescriptorSetDesc.size()); } + bool IsCompute() const { return _compute; } + + void OnError(CSZ s) const; + + void UpdateDebugInfo( + const Vector& vRootParams, + const Vector& vStaticSamplers, + D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags); + + void UpdateUtilization() const; + }; + VERUS_TYPEDEFS(ShaderD3D12); } diff --git a/RendererDirect3D12/src/CGI/TextureD3D12.h b/RendererDirect3D12/src/CGI/TextureD3D12.h index d2bb70c..0434fa4 100644 --- a/RendererDirect3D12/src/CGI/TextureD3D12.h +++ b/RendererDirect3D12/src/CGI/TextureD3D12.h @@ -1,62 +1,59 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class TextureD3D12 : public BaseTexture { - class TextureD3D12 : public BaseTexture + struct ResourceEx { - struct ResourceEx - { - ComPtr _pResource; - D3D12MA::Allocation* _pMaAllocation = nullptr; - }; - - ResourceEx _resource; - ResourceEx _uaResource; - Vector _vStagingBuffers; - Vector _vReadbackBuffers; - Vector _vCshGenerateMips; - DescriptorHeap _dhSRV; - DescriptorHeap _dhUAV; - DescriptorHeap _dhRTV; - DescriptorHeap _dhDSV; - DescriptorHeap _dhSampler; - - public: - TextureD3D12(); - virtual ~TextureD3D12() override; - - virtual void Init(RcTextureDesc desc) override; - virtual void Done() override; - - virtual void UpdateSubresource(const void* p, int mipLevel, int arrayLayer, PBaseCommandBuffer pCB) override; - virtual bool ReadbackSubresource(void* p, bool recordCopyCommand, PBaseCommandBuffer pCB) override; - - virtual void GenerateMips(PBaseCommandBuffer pCB) override; - void GenerateCubeMapMips(PBaseCommandBuffer pCB); - - virtual Continue Scheduled_Update() override; - - // - // D3D12 - // - - void ClearCshGenerateMips(); - - void CreateSampler(); - - ID3D12Resource* GetD3DResource() const { return _resource._pResource.Get(); } - - RcDescriptorHeap GetDescriptorHeapSRV() const { return _dhSRV; } - RcDescriptorHeap GetDescriptorHeapUAV() const { return _dhUAV; } - RcDescriptorHeap GetDescriptorHeapRTV() const { return _dhRTV; } - RcDescriptorHeap GetDescriptorHeapDSV() const { return _dhDSV; } - RcDescriptorHeap GetDescriptorHeapSampler() const { return _dhSampler; }; - - static DXGI_FORMAT RemoveSRGB(DXGI_FORMAT format); + ComPtr _pResource; + D3D12MA::Allocation* _pMaAllocation = nullptr; }; - VERUS_TYPEDEFS(TextureD3D12); - } + + ResourceEx _resource; + ResourceEx _uaResource; + Vector _vStagingBuffers; + Vector _vReadbackBuffers; + Vector _vCshGenerateMips; + DescriptorHeap _dhSRV; + DescriptorHeap _dhUAV; + DescriptorHeap _dhRTV; + DescriptorHeap _dhDSV; + DescriptorHeap _dhSampler; + + public: + TextureD3D12(); + virtual ~TextureD3D12() override; + + virtual void Init(RcTextureDesc desc) override; + virtual void Done() override; + + virtual void UpdateSubresource(const void* p, int mipLevel, int arrayLayer, PBaseCommandBuffer pCB) override; + virtual bool ReadbackSubresource(void* p, bool recordCopyCommand, PBaseCommandBuffer pCB) override; + + virtual void GenerateMips(PBaseCommandBuffer pCB) override; + void GenerateCubeMapMips(PBaseCommandBuffer pCB); + + virtual Continue Scheduled_Update() override; + + // + // D3D12 + // + + void ClearCshGenerateMips(); + + void CreateSampler(); + + ID3D12Resource* GetD3DResource() const { return _resource._pResource.Get(); } + + RcDescriptorHeap GetDescriptorHeapSRV() const { return _dhSRV; } + RcDescriptorHeap GetDescriptorHeapUAV() const { return _dhUAV; } + RcDescriptorHeap GetDescriptorHeapRTV() const { return _dhRTV; } + RcDescriptorHeap GetDescriptorHeapDSV() const { return _dhDSV; } + RcDescriptorHeap GetDescriptorHeapSampler() const { return _dhSampler; }; + + static DXGI_FORMAT RemoveSRGB(DXGI_FORMAT format); + }; + VERUS_TYPEDEFS(TextureD3D12); } diff --git a/RendererVulkan/RendererVulkan.vcxproj b/RendererVulkan/RendererVulkan.vcxproj index 3f2d778..0fcf100 100644 --- a/RendererVulkan/RendererVulkan.vcxproj +++ b/RendererVulkan/RendererVulkan.vcxproj @@ -11,23 +11,23 @@ - 16.0 + 17.0 Win32Proj {C9195A1C-9224-4B40-BBBC-AA90EF3BE3E0} RendererVulkan - 10.0.20348.0 + 10.0.22000.0 DynamicLibrary true - v142 + v143 Unicode DynamicLibrary false - v142 + v143 true Unicode @@ -45,12 +45,6 @@ - - true - - - false - Level3 @@ -61,6 +55,7 @@ pch.h Fast $(ProjectDir)src;%(AdditionalIncludeDirectories) + stdcpp20 Windows @@ -80,6 +75,7 @@ pch.h Fast $(ProjectDir)src;%(AdditionalIncludeDirectories) + stdcpp20 Windows diff --git a/RendererVulkan/src/CGI/CommandBufferVulkan.h b/RendererVulkan/src/CGI/CommandBufferVulkan.h index e7a92fa..92def67 100644 --- a/RendererVulkan/src/CGI/CommandBufferVulkan.h +++ b/RendererVulkan/src/CGI/CommandBufferVulkan.h @@ -1,58 +1,55 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class CommandBufferVulkan : public BaseCommandBuffer { - class CommandBufferVulkan : public BaseCommandBuffer - { - VkCommandBuffer _commandBuffers[BaseRenderer::s_ringBufferSize] = {}; - bool _oneTimeSubmit = false; + VkCommandBuffer _commandBuffers[BaseRenderer::s_ringBufferSize] = {}; + bool _oneTimeSubmit = false; - public: - CommandBufferVulkan(); - virtual ~CommandBufferVulkan() override; + public: + CommandBufferVulkan(); + virtual ~CommandBufferVulkan() override; - virtual void Init() override; - virtual void Done() override; + virtual void Init() override; + virtual void Done() override; - virtual void InitOneTimeSubmit() override; - virtual void DoneOneTimeSubmit() override; + virtual void InitOneTimeSubmit() override; + virtual void DoneOneTimeSubmit() override; - virtual void Begin() override; - virtual void End() override; + virtual void Begin() override; + virtual void End() override; - virtual void PipelineImageMemoryBarrier(TexturePtr tex, ImageLayout oldLayout, ImageLayout newLayout, Range mipLevels, Range arrayLayers) override; + virtual void PipelineImageMemoryBarrier(TexturePtr tex, ImageLayout oldLayout, ImageLayout newLayout, Range mipLevels, Range arrayLayers) override; - virtual void BeginRenderPass(RPHandle renderPassHandle, FBHandle framebufferHandle, - std::initializer_list ilClearValues, ViewportScissorFlags vsf) override; - virtual void NextSubpass() override; - virtual void EndRenderPass() override; + virtual void BeginRenderPass(RPHandle renderPassHandle, FBHandle framebufferHandle, + std::initializer_list ilClearValues, ViewportScissorFlags vsf) override; + virtual void NextSubpass() override; + virtual void EndRenderPass() override; - virtual void BindPipeline(PipelinePtr pipe) override; - virtual void SetViewport(std::initializer_list il, float minDepth, float maxDepth) override; - virtual void SetScissor(std::initializer_list il) override; - virtual void SetBlendConstants(const float* p) override; + virtual void BindPipeline(PipelinePtr pipe) override; + virtual void SetViewport(std::initializer_list il, float minDepth, float maxDepth) override; + virtual void SetScissor(std::initializer_list il) override; + virtual void SetBlendConstants(const float* p) override; - virtual void BindVertexBuffers(GeometryPtr geo, UINT32 bindingsFilter) override; - virtual void BindIndexBuffer(GeometryPtr geo) override; + virtual void BindVertexBuffers(GeometryPtr geo, UINT32 bindingsFilter) override; + virtual void BindIndexBuffer(GeometryPtr geo) override; - virtual bool BindDescriptors(ShaderPtr shader, int setNumber, CSHandle complexSetHandle) override; - virtual bool BindDescriptors(ShaderPtr shader, int setNumber, GeometryPtr geo, int sbIndex) override; - virtual void PushConstants(ShaderPtr shader, int offset, int size, const void* p, ShaderStageFlags stageFlags) override; + virtual bool BindDescriptors(ShaderPtr shader, int setNumber, CSHandle complexSetHandle) override; + virtual bool BindDescriptors(ShaderPtr shader, int setNumber, GeometryPtr geo, int sbIndex) override; + virtual void PushConstants(ShaderPtr shader, int offset, int size, const void* p, ShaderStageFlags stageFlags) override; - virtual void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) override; - virtual void DrawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) override; - virtual void Dispatch(int groupCountX, int groupCountY, int groupCountZ) override; - virtual void TraceRays(int width, int height, int depth) override; + virtual void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) override; + virtual void DrawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) override; + virtual void Dispatch(int groupCountX, int groupCountY, int groupCountZ) override; + virtual void TraceRays(int width, int height, int depth) override; - // - // Vulkan - // + // + // Vulkan + // - VkCommandBuffer GetVkCommandBuffer() const; - }; - VERUS_TYPEDEFS(CommandBufferVulkan); - } + VkCommandBuffer GetVkCommandBuffer() const; + }; + VERUS_TYPEDEFS(CommandBufferVulkan); } diff --git a/RendererVulkan/src/CGI/Descriptors.cpp b/RendererVulkan/src/CGI/Descriptors.cpp index 3f19b54..b0dde11 100644 --- a/RendererVulkan/src/CGI/Descriptors.cpp +++ b/RendererVulkan/src/CGI/Descriptors.cpp @@ -98,18 +98,18 @@ bool Descriptors::CreatePool(bool freeDescriptorSet) vkdpci.flags = freeDescriptorSet ? VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT : 0; Vector vDescriptorPoolSizes; vDescriptorPoolSizes.reserve(_mapTypeCount.size()); - for (const auto& kv : _mapTypeCount) + for (const auto& [key, value] : _mapTypeCount) { VkDescriptorPoolSize vkdps; - vkdps.type = kv.first; - vkdps.descriptorCount = kv.second; + vkdps.type = key; + vkdps.descriptorCount = value; vDescriptorPoolSizes.push_back(vkdps); - switch (kv.first) + switch (key) { case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: - vkdpci.maxSets += kv.second; + vkdpci.maxSets += value; } } vkdpci.poolSizeCount = Utils::Cast32(vDescriptorPoolSizes.size()); diff --git a/RendererVulkan/src/CGI/Descriptors.h b/RendererVulkan/src/CGI/Descriptors.h index 34adfeb..00f5fc2 100644 --- a/RendererVulkan/src/CGI/Descriptors.h +++ b/RendererVulkan/src/CGI/Descriptors.h @@ -1,67 +1,64 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class Descriptors : public Object { - class Descriptors : public Object + typedef Map TMapTypeCount; + + struct SetLayoutDesc { - typedef Map TMapTypeCount; - - struct SetLayoutDesc - { - Vector _vSetLayoutBindings; - int _capacity = 0; - }; - - TMapTypeCount _mapTypeCount; - Vector _vSetLayoutDesc; - Vector _vSetLayouts; - Vector _vBufferInfo; - Vector _vImageInfo; - Vector _vWriteSet; - VkDescriptorPool _pool = VK_NULL_HANDLE; - VkDescriptorSet _activeSet = VK_NULL_HANDLE; - int _activeSetNumber = 0; - int _complexCapacity = 0; - - public: - Descriptors(); - ~Descriptors(); - - void Init(); - void Done(); - - void BeginCreateSetLayout(int setNumber, int capacity); - void SetLayoutBinding(int binding, VkDescriptorType type, int count, VkShaderStageFlags stageFlags, const VkSampler* pImmutableSampler = nullptr); - void EndCreateSetLayout(); - - bool CreatePool(bool freeDescriptorSet); - - bool BeginAllocateSet(int setNumber); - void BufferInfo(int binding, VkBuffer buffer, VkDeviceSize range, VkDeviceSize offset = 0); - void ImageInfo(int binding, VkSampler sampler, VkImageView imageView, VkImageLayout imageLayout); - VkDescriptorSet EndAllocateSet(); - - void IncreaseComplexCapacityBy(int capacity) { _complexCapacity += capacity; } - int GetComplexCapacity() const { return _complexCapacity; } - - int GetSetLayoutCount() const; - const VkDescriptorSetLayout* GetSetLayouts() const; - - VkDescriptorPool GetPool() const { return _pool; } - - template - void ForEach(int setNumber, const T& fn) - { - for (auto& x : _vSetLayoutDesc[setNumber]._vSetLayoutBindings) - { - if (Continue::no == fn(x)) - break; - } - } + Vector _vSetLayoutBindings; + int _capacity = 0; }; - VERUS_TYPEDEFS(Descriptors); - } + + TMapTypeCount _mapTypeCount; + Vector _vSetLayoutDesc; + Vector _vSetLayouts; + Vector _vBufferInfo; + Vector _vImageInfo; + Vector _vWriteSet; + VkDescriptorPool _pool = VK_NULL_HANDLE; + VkDescriptorSet _activeSet = VK_NULL_HANDLE; + int _activeSetNumber = 0; + int _complexCapacity = 0; + + public: + Descriptors(); + ~Descriptors(); + + void Init(); + void Done(); + + void BeginCreateSetLayout(int setNumber, int capacity); + void SetLayoutBinding(int binding, VkDescriptorType type, int count, VkShaderStageFlags stageFlags, const VkSampler* pImmutableSampler = nullptr); + void EndCreateSetLayout(); + + bool CreatePool(bool freeDescriptorSet); + + bool BeginAllocateSet(int setNumber); + void BufferInfo(int binding, VkBuffer buffer, VkDeviceSize range, VkDeviceSize offset = 0); + void ImageInfo(int binding, VkSampler sampler, VkImageView imageView, VkImageLayout imageLayout); + VkDescriptorSet EndAllocateSet(); + + void IncreaseComplexCapacityBy(int capacity) { _complexCapacity += capacity; } + int GetComplexCapacity() const { return _complexCapacity; } + + int GetSetLayoutCount() const; + const VkDescriptorSetLayout* GetSetLayouts() const; + + VkDescriptorPool GetPool() const { return _pool; } + + template + void ForEach(int setNumber, const T& fn) + { + for (auto& x : _vSetLayoutDesc[setNumber]._vSetLayoutBindings) + { + if (Continue::no == fn(x)) + break; + } + } + }; + VERUS_TYPEDEFS(Descriptors); } diff --git a/RendererVulkan/src/CGI/ExtRealityVulkan.h b/RendererVulkan/src/CGI/ExtRealityVulkan.h index 8873622..255b095 100644 --- a/RendererVulkan/src/CGI/ExtRealityVulkan.h +++ b/RendererVulkan/src/CGI/ExtRealityVulkan.h @@ -1,65 +1,62 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class RendererVulkan; + + class ExtRealityVulkan : public BaseExtReality { - class RendererVulkan; - - class ExtRealityVulkan : public BaseExtReality + struct SwapChainEx { - struct SwapChainEx - { - XrSwapchain _handle = XR_NULL_HANDLE; - int32_t _width = 0; - int32_t _height = 0; - Vector _vImages; - Vector _vImageViews; - }; - - Vector _vSwapChains; - - public: - ExtRealityVulkan(); - virtual ~ExtRealityVulkan() override; - - virtual void Init() override; - virtual void Done() override; - - VkResult CreateVulkanInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkInstance* pInstance); - VkPhysicalDevice GetVulkanGraphicsDevice(VkInstance vulkanInstance); - VkResult CreateVulkanDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDevice* pDevice); - void InitByRenderer(RendererVulkan* pRenderer); - - private: - void GetSystem(); - void CreateSwapChains(RendererVulkan* pRenderer, int64_t format); - VkImageView CreateImageView(RendererVulkan* pRenderer, int64_t format, XrSwapchainImageVulkan2KHR& image); - virtual XrSwapchain GetSwapChain(int viewIndex) override; - virtual void GetSwapChainSize(int viewIndex, int32_t& w, int32_t& h) override; - - public: - VkImageView GetVkImageView(int viewIndex, int imageIndex) const; - - virtual void CreateActions() override; - virtual void PollEvents() override; - virtual void SyncActions(UINT32 activeActionSetsMask) override; - - virtual bool GetActionStateBoolean(int actionIndex, bool& currentState, bool* pChangedState, int subaction) override; - virtual bool GetActionStateFloat(int actionIndex, float& currentState, bool* pChangedState, int subaction) override; - virtual bool GetActionStatePose(int actionIndex, bool& currentState, Math::RPose pose, int subaction) override; - - virtual void BeginFrame() override; - virtual int LocateViews() override; - virtual void BeginView(int viewIndex, RViewDesc viewDesc) override; - virtual void AcquireSwapChainImage() override; - virtual void EndView(int viewIndex) override; - virtual void EndFrame() override; - - virtual void BeginAreaUpdate() override; - virtual void EndAreaUpdate(PcVector4 pUserOffset) override; + XrSwapchain _handle = XR_NULL_HANDLE; + int32_t _width = 0; + int32_t _height = 0; + Vector _vImages; + Vector _vImageViews; }; - VERUS_TYPEDEFS(ExtRealityVulkan); - } + + Vector _vSwapChains; + + public: + ExtRealityVulkan(); + virtual ~ExtRealityVulkan() override; + + virtual void Init() override; + virtual void Done() override; + + VkResult CreateVulkanInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkInstance* pInstance); + VkPhysicalDevice GetVulkanGraphicsDevice(VkInstance vulkanInstance); + VkResult CreateVulkanDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDevice* pDevice); + void InitByRenderer(RendererVulkan* pRenderer); + + private: + void GetSystem(); + void CreateSwapChains(RendererVulkan* pRenderer, int64_t format); + VkImageView CreateImageView(RendererVulkan* pRenderer, int64_t format, XrSwapchainImageVulkan2KHR& image); + virtual XrSwapchain GetSwapChain(int viewIndex) override; + virtual void GetSwapChainSize(int viewIndex, int32_t& w, int32_t& h) override; + + public: + VkImageView GetVkImageView(int viewIndex, int imageIndex) const; + + virtual void CreateActions() override; + virtual void PollEvents() override; + virtual void SyncActions(UINT32 activeActionSetsMask) override; + + virtual bool GetActionStateBoolean(int actionIndex, bool& currentState, bool* pChangedState, int subaction) override; + virtual bool GetActionStateFloat(int actionIndex, float& currentState, bool* pChangedState, int subaction) override; + virtual bool GetActionStatePose(int actionIndex, bool& currentState, Math::RPose pose, int subaction) override; + + virtual void BeginFrame() override; + virtual int LocateViews() override; + virtual void BeginView(int viewIndex, RViewDesc viewDesc) override; + virtual void AcquireSwapChainImage() override; + virtual void EndView(int viewIndex) override; + virtual void EndFrame() override; + + virtual void BeginAreaUpdate() override; + virtual void EndAreaUpdate(PcVector4 pUserOffset) override; + }; + VERUS_TYPEDEFS(ExtRealityVulkan); } diff --git a/RendererVulkan/src/CGI/GeometryVulkan.h b/RendererVulkan/src/CGI/GeometryVulkan.h index e00b0aa..427a2f5 100644 --- a/RendererVulkan/src/CGI/GeometryVulkan.h +++ b/RendererVulkan/src/CGI/GeometryVulkan.h @@ -1,76 +1,73 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class GeometryVulkan : public BaseGeometry { - class GeometryVulkan : public BaseGeometry + static const int s_maxStorageBuffers = 8; + + struct BufferEx { - static const int s_maxStorageBuffers = 8; - - struct BufferEx - { - VmaAllocation _vmaAllocation = VK_NULL_HANDLE; - VkBuffer _buffer = VK_NULL_HANDLE; - VkDeviceSize _bufferSize = 0; - INT64 _utilization = -1; - }; - - struct StorageBufferEx : BufferEx - { - VkDescriptorSet _descriptorSet = VK_NULL_HANDLE; - int _structSize = 0; - }; - - Vector _vVertexBuffers; - BufferEx _indexBuffer; - Vector _vStagingVertexBuffers; - BufferEx _stagingIndexBuffer; - Vector _vStorageBuffers; - Vector _vVertexInputBindingDesc; - Vector _vVertexInputAttributeDesc; - Vector _vStrides; - Descriptors _descriptors; - - public: - GeometryVulkan(); - virtual ~GeometryVulkan() override; - - virtual void Init(RcGeometryDesc desc) override; - virtual void Done() override; - - virtual void CreateVertexBuffer(int count, int binding) override; - virtual void UpdateVertexBuffer(const void* p, int binding, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - - virtual void CreateIndexBuffer(int count) override; - virtual void UpdateIndexBuffer(const void* p, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - - virtual void CreateStorageBuffer(int count, int structSize, int sbIndex, ShaderStageFlags stageFlags) override; - virtual void UpdateStorageBuffer(const void* p, int sbIndex, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; - virtual int GetStorageBufferStructSize(int sbIndex) const override; - - virtual Continue Scheduled_Update() override; - - // - // Vulkan - // - - VkPipelineVertexInputStateCreateInfo GetVkPipelineVertexInputStateCreateInfo(UINT32 bindingsFilter, - Vector& vVertexInputBindingDesc, Vector& vVertexInputAttributeDesc) const; - - int GetVertexBufferCount() const { return Utils::Cast32(_vVertexBuffers.size()); } - VkBuffer GetVkVertexBuffer(int binding) const { return _vVertexBuffers[binding]._buffer; } - VkDeviceSize GetVkVertexBufferOffset(int binding) const; - - VkBuffer GetVkIndexBuffer() const { return _indexBuffer._buffer; } - VkDeviceSize GetVkIndexBufferOffset() const; - - VkDescriptorSet GetVkDescriptorSet(int sbIndex) const { return _vStorageBuffers[sbIndex]._descriptorSet; } - VkDeviceSize GetVkStorageBufferOffset(int sbIndex) const; - - void UpdateUtilization() const;; + VmaAllocation _vmaAllocation = VK_NULL_HANDLE; + VkBuffer _buffer = VK_NULL_HANDLE; + VkDeviceSize _bufferSize = 0; + INT64 _utilization = -1; }; - VERUS_TYPEDEFS(GeometryVulkan); - } + + struct StorageBufferEx : BufferEx + { + VkDescriptorSet _descriptorSet = VK_NULL_HANDLE; + int _structSize = 0; + }; + + Vector _vVertexBuffers; + BufferEx _indexBuffer; + Vector _vStagingVertexBuffers; + BufferEx _stagingIndexBuffer; + Vector _vStorageBuffers; + Vector _vVertexInputBindingDesc; + Vector _vVertexInputAttributeDesc; + Vector _vStrides; + Descriptors _descriptors; + + public: + GeometryVulkan(); + virtual ~GeometryVulkan() override; + + virtual void Init(RcGeometryDesc desc) override; + virtual void Done() override; + + virtual void CreateVertexBuffer(int count, int binding) override; + virtual void UpdateVertexBuffer(const void* p, int binding, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + + virtual void CreateIndexBuffer(int count) override; + virtual void UpdateIndexBuffer(const void* p, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + + virtual void CreateStorageBuffer(int count, int structSize, int sbIndex, ShaderStageFlags stageFlags) override; + virtual void UpdateStorageBuffer(const void* p, int sbIndex, PBaseCommandBuffer pCB, INT64 size, INT64 offset) override; + virtual int GetStorageBufferStructSize(int sbIndex) const override; + + virtual Continue Scheduled_Update() override; + + // + // Vulkan + // + + VkPipelineVertexInputStateCreateInfo GetVkPipelineVertexInputStateCreateInfo(UINT32 bindingsFilter, + Vector& vVertexInputBindingDesc, Vector& vVertexInputAttributeDesc) const; + + int GetVertexBufferCount() const { return Utils::Cast32(_vVertexBuffers.size()); } + VkBuffer GetVkVertexBuffer(int binding) const { return _vVertexBuffers[binding]._buffer; } + VkDeviceSize GetVkVertexBufferOffset(int binding) const; + + VkBuffer GetVkIndexBuffer() const { return _indexBuffer._buffer; } + VkDeviceSize GetVkIndexBufferOffset() const; + + VkDescriptorSet GetVkDescriptorSet(int sbIndex) const { return _vStorageBuffers[sbIndex]._descriptorSet; } + VkDeviceSize GetVkStorageBufferOffset(int sbIndex) const; + + void UpdateUtilization() const;; + }; + VERUS_TYPEDEFS(GeometryVulkan); } diff --git a/RendererVulkan/src/CGI/Native.h b/RendererVulkan/src/CGI/Native.h index ecfb255..6b2dd53 100644 --- a/RendererVulkan/src/CGI/Native.h +++ b/RendererVulkan/src/CGI/Native.h @@ -1,29 +1,26 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI - { - VkCompareOp ToNativeCompareOp(CompareOp compareOp); + VkCompareOp ToNativeCompareOp(CompareOp compareOp); - uint32_t ToNativeCubeMapFace(CubeMapFace face); + uint32_t ToNativeCubeMapFace(CubeMapFace face); - VkPolygonMode ToNativePolygonMode(PolygonMode polygonMode); + VkPolygonMode ToNativePolygonMode(PolygonMode polygonMode); - VkCullModeFlagBits ToNativeCullMode(CullMode cullMode); + VkCullModeFlagBits ToNativeCullMode(CullMode cullMode); - VkPrimitiveTopology ToNativePrimitiveTopology(PrimitiveTopology primitiveTopology); + VkPrimitiveTopology ToNativePrimitiveTopology(PrimitiveTopology primitiveTopology); - VkImageLayout ToNativeImageLayout(ImageLayout layout); + VkImageLayout ToNativeImageLayout(ImageLayout layout); - VkShaderStageFlags ToNativeStageFlags(ShaderStageFlags stageFlags); + VkShaderStageFlags ToNativeStageFlags(ShaderStageFlags stageFlags); - VkSampleCountFlagBits ToNativeSampleCount(int sampleCount); + VkSampleCountFlagBits ToNativeSampleCount(int sampleCount); - VkFormat ToNativeFormat(Format format); + VkFormat ToNativeFormat(Format format); - int ToNativeLocation(ViaUsage usage, int usageIndex); - VkFormat ToNativeFormat(ViaUsage usage, ViaType type, int components); - } + int ToNativeLocation(ViaUsage usage, int usageIndex); + VkFormat ToNativeFormat(ViaUsage usage, ViaType type, int components); } diff --git a/RendererVulkan/src/CGI/PipelineVulkan.h b/RendererVulkan/src/CGI/PipelineVulkan.h index 133ed50..8361b7e 100644 --- a/RendererVulkan/src/CGI/PipelineVulkan.h +++ b/RendererVulkan/src/CGI/PipelineVulkan.h @@ -1,31 +1,28 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class PipelineVulkan : public BasePipeline { - class PipelineVulkan : public BasePipeline - { - VkPipeline _pipeline = VK_NULL_HANDLE; - bool _compute = false; + VkPipeline _pipeline = VK_NULL_HANDLE; + bool _compute = false; - public: - PipelineVulkan(); - virtual ~PipelineVulkan() override; + public: + PipelineVulkan(); + virtual ~PipelineVulkan() override; - virtual void Init(RcPipelineDesc desc) override; - virtual void Done() override; + virtual void Init(RcPipelineDesc desc) override; + virtual void Done() override; - // - // Vulkan - // + // + // Vulkan + // - VERUS_P(void InitCompute(RcPipelineDesc desc)); - bool IsCompute() const { return _compute; } - VkPipeline GetVkPipeline() const { return _pipeline; } - void FillColorBlendAttachmentStates(RcPipelineDesc desc, int attachmentCount, VkPipelineColorBlendAttachmentState vkpcbas[]); - }; - VERUS_TYPEDEFS(PipelineVulkan); - } + VERUS_P(void InitCompute(RcPipelineDesc desc)); + bool IsCompute() const { return _compute; } + VkPipeline GetVkPipeline() const { return _pipeline; } + void FillColorBlendAttachmentStates(RcPipelineDesc desc, int attachmentCount, VkPipelineColorBlendAttachmentState vkpcbas[]); + }; + VERUS_TYPEDEFS(PipelineVulkan); } diff --git a/RendererVulkan/src/CGI/RendererVulkan.h b/RendererVulkan/src/CGI/RendererVulkan.h index a44f150..5faf237 100644 --- a/RendererVulkan/src/CGI/RendererVulkan.h +++ b/RendererVulkan/src/CGI/RendererVulkan.h @@ -1,217 +1,214 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + enum class HostAccess : int { - enum class HostAccess : int + forbidden, + sequentialWrite, + random + }; + + struct BaseShaderInclude + { + virtual void Open(CSZ filename, void** ppData, UINT32* pBytes) = 0; + virtual void Close(void* pData) = 0; + }; + + typedef Store TStoreCommandBuffers; + typedef Store TStoreGeometry; + typedef Store TStorePipelines; + typedef Store TStoreShaders; + typedef Store TStoreTextures; + class RendererVulkan : public Singleton, public BaseRenderer, + private TStoreCommandBuffers, private TStoreGeometry, private TStorePipelines, private TStoreShaders, private TStoreTextures + { + public: + struct Framebuffer { - forbidden, - sequentialWrite, - random + VkFramebuffer _framebuffer = VK_NULL_HANDLE; + int _width = 0; + int _height = 0; + }; + VERUS_TYPEDEFS(Framebuffer); + + private: + struct QueueFamilyIndices + { + int _graphicsFamilyIndex = -1; + int _presentFamilyIndex = -1; + + bool IsComplete() const + { + return _graphicsFamilyIndex >= 0 && _presentFamilyIndex >= 0; + } + + bool IsSameQueue() const + { + return _graphicsFamilyIndex == _presentFamilyIndex; + } }; - struct BaseShaderInclude + struct SwapChainInfo { - virtual void Open(CSZ filename, void** ppData, UINT32* pBytes) = 0; - virtual void Close(void* pData) = 0; + VkSurfaceCapabilitiesKHR _surfaceCapabilities = {}; + Vector _vSurfaceFormats; + Vector _vSurfacePresentModes; }; - typedef Store TStoreCommandBuffers; - typedef Store TStoreGeometry; - typedef Store TStorePipelines; - typedef Store TStoreShaders; - typedef Store TStoreTextures; - class RendererVulkan : public Singleton, public BaseRenderer, - private TStoreCommandBuffers, private TStoreGeometry, private TStorePipelines, private TStoreShaders, private TStoreTextures - { - public: - struct Framebuffer - { - VkFramebuffer _framebuffer = VK_NULL_HANDLE; - int _width = 0; - int _height = 0; - }; - VERUS_TYPEDEFS(Framebuffer); + static const uint32_t s_apiVersion = VK_API_VERSION_1_1; - private: - struct QueueFamilyIndices - { - int _graphicsFamilyIndex = -1; - int _presentFamilyIndex = -1; + static CSZ s_requiredValidationLayers[]; + static CSZ s_requiredDeviceExtensions[]; - bool IsComplete() const - { - return _graphicsFamilyIndex >= 0 && _presentFamilyIndex >= 0; - } + ExtRealityVulkan _extReality; + VkInstance _instance = VK_NULL_HANDLE; + VkDebugUtilsMessengerEXT _debugUtilsMessenger = VK_NULL_HANDLE; + VkSurfaceKHR _surface = VK_NULL_HANDLE; + VkPhysicalDevice _physicalDevice = VK_NULL_HANDLE; + VkDevice _device = VK_NULL_HANDLE; + VkQueue _graphicsQueue = VK_NULL_HANDLE; + VkQueue _presentQueue = VK_NULL_HANDLE; + VmaAllocator _vmaAllocator = VK_NULL_HANDLE; + VkSwapchainKHR _swapChain = VK_NULL_HANDLE; + Vector _vSwapChainImages; + Vector _vSwapChainImageViews; + VkCommandPool _commandPools[s_ringBufferSize] = {}; + VkSemaphore _acquireNextImageSemaphores[s_ringBufferSize] = {}; + VkSemaphore _queueSubmitSemaphores[s_ringBufferSize] = {}; + VkSemaphore _acquireNextImageSemaphore = VK_NULL_HANDLE; + VkSemaphore _queueSubmitSemaphore = VK_NULL_HANDLE; + VkFence _queueSubmitFences[s_ringBufferSize] = {}; + QueueFamilyIndices _queueFamilyIndices; + VkDescriptorPool _descriptorPoolImGui = VK_NULL_HANDLE; + Vector _vSamplers; + Vector _vRenderPasses; + Vector _vFramebuffers; + bool _advancedLineRasterization = false; - bool IsSameQueue() const - { - return _graphicsFamilyIndex == _presentFamilyIndex; - } - }; + public: + RendererVulkan(); + ~RendererVulkan(); - struct SwapChainInfo - { - VkSurfaceCapabilitiesKHR _surfaceCapabilities = {}; - Vector _vSurfaceFormats; - Vector _vSurfacePresentModes; - }; + virtual void ReleaseMe() override; - static const uint32_t s_apiVersion = VK_API_VERSION_1_1; + void Init(); + void Done(); - static CSZ s_requiredValidationLayers[]; - static CSZ s_requiredDeviceExtensions[]; + static void VulkanCompilerInit(); + static void VulkanCompilerDone(); + static bool VulkanCompile(CSZ source, CSZ sourceName, CSZ* defines, BaseShaderInclude* pInclude, + CSZ entryPoint, CSZ target, UINT32 flags, UINT32** ppCode, UINT32* pSize, CSZ* ppErrorMsgs); - ExtRealityVulkan _extReality; - VkInstance _instance = VK_NULL_HANDLE; - VkDebugUtilsMessengerEXT _debugUtilsMessenger = VK_NULL_HANDLE; - VkSurfaceKHR _surface = VK_NULL_HANDLE; - VkPhysicalDevice _physicalDevice = VK_NULL_HANDLE; - VkDevice _device = VK_NULL_HANDLE; - VkQueue _graphicsQueue = VK_NULL_HANDLE; - VkQueue _presentQueue = VK_NULL_HANDLE; - VmaAllocator _vmaAllocator = VK_NULL_HANDLE; - VkSwapchainKHR _swapChain = VK_NULL_HANDLE; - Vector _vSwapChainImages; - Vector _vSwapChainImageViews; - VkCommandPool _commandPools[s_ringBufferSize] = {}; - VkSemaphore _acquireNextImageSemaphores[s_ringBufferSize] = {}; - VkSemaphore _queueSubmitSemaphores[s_ringBufferSize] = {}; - VkSemaphore _acquireNextImageSemaphore = VK_NULL_HANDLE; - VkSemaphore _queueSubmitSemaphore = VK_NULL_HANDLE; - VkFence _queueSubmitFences[s_ringBufferSize] = {}; - QueueFamilyIndices _queueFamilyIndices; - VkDescriptorPool _descriptorPoolImGui = VK_NULL_HANDLE; - Vector _vSamplers; - Vector _vRenderPasses; - Vector _vFramebuffers; - bool _advancedLineRasterization = false; + private: + static VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtilsMessengerCallback( + VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverityFlagBits, + VkDebugUtilsMessageTypeFlagsEXT messageTypeFlags, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, + void* pUserData); + bool CheckRequiredValidationLayers(); + Vector GetRequiredExtensions(); + void CreateInstance(); + void FillDebugUtilsMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& vkdumci); + void CreateDebugUtilsMessenger(); + void CreateSurface(); + QueueFamilyIndices FindQueueFamilyIndices(VkPhysicalDevice device); + bool CheckRequiredDeviceExtensions(VkPhysicalDevice device); + bool IsDeviceSuitable(VkPhysicalDevice device); + void PickPhysicalDevice(); + void CreateDevice(); + SwapChainInfo GetSwapChainInfo(VkPhysicalDevice device); + void CreateSwapChain(VkSwapchainKHR oldSwapchain = VK_NULL_HANDLE); + void CreateImageViews(); + void CreateCommandPools(); + void CreateSyncObjects(); + void CreateSamplers(); - public: - RendererVulkan(); - ~RendererVulkan(); + public: + // + VkCommandBuffer CreateVkCommandBuffer(VkCommandPool commandPool); - virtual void ReleaseMe() override; + VkInstance GetVkInstance() const { return _instance; } + VkPhysicalDevice GetVkPhysicalDevice() const { return _physicalDevice; } + VkDevice GetVkDevice() const { return _device; } + int GetGraphicsQueueFamilyIndex() const { return _queueFamilyIndices._graphicsFamilyIndex; } + VkQueue GetVkGraphicsQueue() const { return _graphicsQueue; } + const VkAllocationCallbacks* GetAllocator() const { return nullptr; } + VmaAllocator GetVmaAllocator() const { return _vmaAllocator; } + VkCommandPool GetVkCommandPool(int ringBufferIndex) const { return _commandPools[ringBufferIndex]; } + const VkSampler* GetImmutableSampler(Sampler s) const; + // - void Init(); - void Done(); + static void ImGuiCheckVkResultFn(VkResult res); + virtual void ImGuiInit(RPHandle renderPassHandle) override; + virtual void ImGuiRenderDrawData() override; - static void VulkanCompilerInit(); - static void VulkanCompilerDone(); - static bool VulkanCompile(CSZ source, CSZ sourceName, CSZ* defines, BaseShaderInclude* pInclude, - CSZ entryPoint, CSZ target, UINT32 flags, UINT32** ppCode, UINT32* pSize, CSZ* ppErrorMsgs); + virtual void ResizeSwapChain() override; - private: - static VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtilsMessengerCallback( - VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverityFlagBits, - VkDebugUtilsMessageTypeFlagsEXT messageTypeFlags, - const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, - void* pUserData); - bool CheckRequiredValidationLayers(); - Vector GetRequiredExtensions(); - void CreateInstance(); - void FillDebugUtilsMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& vkdumci); - void CreateDebugUtilsMessenger(); - void CreateSurface(); - QueueFamilyIndices FindQueueFamilyIndices(VkPhysicalDevice device); - bool CheckRequiredDeviceExtensions(VkPhysicalDevice device); - bool IsDeviceSuitable(VkPhysicalDevice device); - void PickPhysicalDevice(); - void CreateDevice(); - SwapChainInfo GetSwapChainInfo(VkPhysicalDevice device); - void CreateSwapChain(VkSwapchainKHR oldSwapchain = VK_NULL_HANDLE); - void CreateImageViews(); - void CreateCommandPools(); - void CreateSyncObjects(); - void CreateSamplers(); + virtual PBaseExtReality GetExtReality() override; - public: - // - VkCommandBuffer CreateVkCommandBuffer(VkCommandPool commandPool); + // Which graphics API? + virtual Gapi GetGapi() override { return Gapi::vulkan; } - VkInstance GetVkInstance() const { return _instance; } - VkPhysicalDevice GetVkPhysicalDevice() const { return _physicalDevice; } - VkDevice GetVkDevice() const { return _device; } - int GetGraphicsQueueFamilyIndex() const { return _queueFamilyIndices._graphicsFamilyIndex; } - VkQueue GetVkGraphicsQueue() const { return _graphicsQueue; } - const VkAllocationCallbacks* GetAllocator() const { return nullptr; } - VmaAllocator GetVmaAllocator() const { return _vmaAllocator; } - VkCommandPool GetVkCommandPool(int ringBufferIndex) const { return _commandPools[ringBufferIndex]; } - const VkSampler* GetImmutableSampler(Sampler s) const; - // + // + virtual void BeginFrame() override; + virtual void AcquireSwapChainImage() override; + virtual void EndFrame() override; + virtual void WaitIdle() override; + virtual void OnMinimized() override; + // - static void ImGuiCheckVkResultFn(VkResult res); - virtual void ImGuiInit(RPHandle renderPassHandle) override; - virtual void ImGuiRenderDrawData() override; + // + virtual PBaseCommandBuffer InsertCommandBuffer() override; + virtual PBaseGeometry InsertGeometry() override; + virtual PBasePipeline InsertPipeline() override; + virtual PBaseShader InsertShader() override; + virtual PBaseTexture InsertTexture() override; - virtual void ResizeSwapChain() override; + virtual void DeleteCommandBuffer(PBaseCommandBuffer p) override; + virtual void DeleteGeometry(PBaseGeometry p) override; + virtual void DeletePipeline(PBasePipeline p) override; + virtual void DeleteShader(PBaseShader p) override; + virtual void DeleteTexture(PBaseTexture p) override; - virtual PBaseExtReality GetExtReality() override; + virtual RPHandle CreateRenderPass(std::initializer_list ilA, std::initializer_list ilS, std::initializer_list ilD) override; + virtual FBHandle CreateFramebuffer(RPHandle renderPassHandle, std::initializer_list il, int w, int h, + int swapChainBufferIndex = -1, CubeMapFace cubeMapFace = CubeMapFace::none) override; + virtual void DeleteRenderPass(RPHandle handle) override; + virtual void DeleteFramebuffer(FBHandle handle) override; + int GetNextRenderPassIndex() const; + int GetNextFramebufferIndex() const; + VkRenderPass GetRenderPass(RPHandle handle) const; + RcFramebuffer GetFramebuffer(FBHandle handle) const; + // - // Which graphics API? - virtual Gapi GetGapi() override { return Gapi::vulkan; } + // + void CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, HostAccess hostAccess, VkBuffer& buffer, VmaAllocation& vmaAllocation); + void CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size, PBaseCommandBuffer pCB = nullptr); + void CreateImage(const VkImageCreateInfo* pImageCreateInfo, HostAccess hostAccess, VkImage& image, VmaAllocation& vmaAllocation); + void CopyImage( + VkImage srcImage, uint32_t srcMipLevel, uint32_t srcArrayLayer, + VkImage dstImage, uint32_t dstMipLevel, uint32_t dstArrayLayer, + uint32_t width, uint32_t height, + PBaseCommandBuffer pCB = nullptr); + void CopyBufferToImage( + VkBuffer buffer, + VkImage image, uint32_t mipLevel, uint32_t arrayLayer, + uint32_t width, uint32_t height, + PBaseCommandBuffer pCB = nullptr); + void CopyImageToBuffer( + VkImage image, uint32_t mipLevel, uint32_t arrayLayer, + uint32_t width, uint32_t height, + VkBuffer buffer, + PBaseCommandBuffer pCB = nullptr); + // - // - virtual void BeginFrame() override; - virtual void AcquireSwapChainImage() override; - virtual void EndFrame() override; - virtual void WaitIdle() override; - virtual void OnMinimized() override; - // + virtual void UpdateUtilization() override; - // - virtual PBaseCommandBuffer InsertCommandBuffer() override; - virtual PBaseGeometry InsertGeometry() override; - virtual PBasePipeline InsertPipeline() override; - virtual PBaseShader InsertShader() override; - virtual PBaseTexture InsertTexture() override; - - virtual void DeleteCommandBuffer(PBaseCommandBuffer p) override; - virtual void DeleteGeometry(PBaseGeometry p) override; - virtual void DeletePipeline(PBasePipeline p) override; - virtual void DeleteShader(PBaseShader p) override; - virtual void DeleteTexture(PBaseTexture p) override; - - virtual RPHandle CreateRenderPass(std::initializer_list ilA, std::initializer_list ilS, std::initializer_list ilD) override; - virtual FBHandle CreateFramebuffer(RPHandle renderPassHandle, std::initializer_list il, int w, int h, - int swapChainBufferIndex = -1, CubeMapFace cubeMapFace = CubeMapFace::none) override; - virtual void DeleteRenderPass(RPHandle handle) override; - virtual void DeleteFramebuffer(FBHandle handle) override; - int GetNextRenderPassIndex() const; - int GetNextFramebufferIndex() const; - VkRenderPass GetRenderPass(RPHandle handle) const; - RcFramebuffer GetFramebuffer(FBHandle handle) const; - // - - // - void CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, HostAccess hostAccess, VkBuffer& buffer, VmaAllocation& vmaAllocation); - void CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size, PBaseCommandBuffer pCB = nullptr); - void CreateImage(const VkImageCreateInfo* pImageCreateInfo, HostAccess hostAccess, VkImage& image, VmaAllocation& vmaAllocation); - void CopyImage( - VkImage srcImage, uint32_t srcMipLevel, uint32_t srcArrayLayer, - VkImage dstImage, uint32_t dstMipLevel, uint32_t dstArrayLayer, - uint32_t width, uint32_t height, - PBaseCommandBuffer pCB = nullptr); - void CopyBufferToImage( - VkBuffer buffer, - VkImage image, uint32_t mipLevel, uint32_t arrayLayer, - uint32_t width, uint32_t height, - PBaseCommandBuffer pCB = nullptr); - void CopyImageToBuffer( - VkImage image, uint32_t mipLevel, uint32_t arrayLayer, - uint32_t width, uint32_t height, - VkBuffer buffer, - PBaseCommandBuffer pCB = nullptr); - // - - virtual void UpdateUtilization() override; - - bool IsAdvancedLineRasterizationSupported() const { return _advancedLineRasterization; } - }; - VERUS_TYPEDEFS(RendererVulkan); - } + bool IsAdvancedLineRasterizationSupported() const { return _advancedLineRasterization; } + }; + VERUS_TYPEDEFS(RendererVulkan); extern "C" { diff --git a/RendererVulkan/src/CGI/ShaderVulkan.cpp b/RendererVulkan/src/CGI/ShaderVulkan.cpp index c699460..034b1e5 100644 --- a/RendererVulkan/src/CGI/ShaderVulkan.cpp +++ b/RendererVulkan/src/CGI/ShaderVulkan.cpp @@ -209,12 +209,12 @@ void ShaderVulkan::Done() for (auto& x : _vDescriptorSetDesc) VERUS_VULKAN_DESTROY(x._buffer, vmaDestroyBuffer(pRendererVulkan->GetVmaAllocator(), x._buffer, x._vmaAllocation)); _vDescriptorSetDesc.clear(); - for (auto& kv : _mapCompiled) + for (auto& [key, value] : _mapCompiled) { VERUS_FOR(i, +Stage::count) { - VERUS_VULKAN_DESTROY(kv.second._shaderModules[i], - vkDestroyShaderModule(pRendererVulkan->GetVkDevice(), kv.second._shaderModules[i], pRendererVulkan->GetAllocator())); + VERUS_VULKAN_DESTROY(value._shaderModules[i], + vkDestroyShaderModule(pRendererVulkan->GetVkDevice(), value._shaderModules[i], pRendererVulkan->GetAllocator())); } } _mapCompiled.clear(); diff --git a/RendererVulkan/src/CGI/ShaderVulkan.h b/RendererVulkan/src/CGI/ShaderVulkan.h index ceed2c3..5a1f8f6 100644 --- a/RendererVulkan/src/CGI/ShaderVulkan.h +++ b/RendererVulkan/src/CGI/ShaderVulkan.h @@ -1,86 +1,83 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class ShaderVulkan : public BaseShader { - class ShaderVulkan : public BaseShader + public: + struct Compiled { - public: - struct Compiled - { - VkShaderModule _shaderModules[+Stage::count] = {}; - String _entry; - int _stageCount = 0; - }; - VERUS_TYPEDEFS(Compiled); - - private: - typedef Map TMapCompiled; - - struct DescriptorSetDesc - { - Vector _vSamplers; - VkBuffer _buffer = VK_NULL_HANDLE; - VmaAllocation _vmaAllocation = VK_NULL_HANDLE; - VkDescriptorSet _descriptorSet = VK_NULL_HANDLE; - BYTE* _pMappedData = nullptr; - const void* _pSrc = nullptr; - int _size = 0; - int _alignedSize = 0; - int _capacity = 1; - int _capacityInBytes = 0; - int _offset = 0; - int _peakLoad = 0; - VkShaderStageFlags _stageFlags = 0; - }; - - TMapCompiled _mapCompiled; - Vector _vDescriptorSetDesc; - Vector _vComplexDescriptorSets; - Descriptors _descriptors; - VkPipelineLayout _pipelineLayout = VK_NULL_HANDLE; - String _debugInfo; - UINT64 _currentFrame = UINT64_MAX; - bool _compute = false; - - public: - ShaderVulkan(); - virtual ~ShaderVulkan() override; - - virtual void Init(CSZ source, CSZ sourceName, CSZ* branches) override; - virtual void Done() override; - - virtual void CreateDescriptorSet(int setNumber, const void* pSrc, int size, int capacity, std::initializer_list il, ShaderStageFlags stageFlags) override; - virtual void CreatePipelineLayout() override; - virtual CSHandle BindDescriptorSetTextures(int setNumber, std::initializer_list il, const int* pMipLevels, const int* pArrayLayers) override; - virtual void FreeDescriptorSet(CSHandle& complexSetHandle) override; - - virtual void BeginBindDescriptors() override; - virtual void EndBindDescriptors() override; - - // - // Vulkan - // - - void CreateDescriptorSets(); - VkDescriptorSet GetVkDescriptorSet(int setNumber) const; - VkDescriptorSet GetComplexVkDescriptorSet(CSHandle descSetID) const; - - RcCompiled GetCompiled(CSZ branch) const { return _mapCompiled.at(branch); } - - VkPipelineLayout GetVkPipelineLayout() const { return _pipelineLayout; } - - bool TryPushConstants(int setNumber, RBaseCommandBuffer cb) const; - int UpdateUniformBuffer(int setNumber); - - bool IsCompute() const { return _compute; } - - void OnError(CSZ s) const; - - void UpdateUtilization() const; + VkShaderModule _shaderModules[+Stage::count] = {}; + String _entry; + int _stageCount = 0; }; - VERUS_TYPEDEFS(ShaderVulkan); - } + VERUS_TYPEDEFS(Compiled); + + private: + typedef Map TMapCompiled; + + struct DescriptorSetDesc + { + Vector _vSamplers; + VkBuffer _buffer = VK_NULL_HANDLE; + VmaAllocation _vmaAllocation = VK_NULL_HANDLE; + VkDescriptorSet _descriptorSet = VK_NULL_HANDLE; + BYTE* _pMappedData = nullptr; + const void* _pSrc = nullptr; + int _size = 0; + int _alignedSize = 0; + int _capacity = 1; + int _capacityInBytes = 0; + int _offset = 0; + int _peakLoad = 0; + VkShaderStageFlags _stageFlags = 0; + }; + + TMapCompiled _mapCompiled; + Vector _vDescriptorSetDesc; + Vector _vComplexDescriptorSets; + Descriptors _descriptors; + VkPipelineLayout _pipelineLayout = VK_NULL_HANDLE; + String _debugInfo; + UINT64 _currentFrame = UINT64_MAX; + bool _compute = false; + + public: + ShaderVulkan(); + virtual ~ShaderVulkan() override; + + virtual void Init(CSZ source, CSZ sourceName, CSZ* branches) override; + virtual void Done() override; + + virtual void CreateDescriptorSet(int setNumber, const void* pSrc, int size, int capacity, std::initializer_list il, ShaderStageFlags stageFlags) override; + virtual void CreatePipelineLayout() override; + virtual CSHandle BindDescriptorSetTextures(int setNumber, std::initializer_list il, const int* pMipLevels, const int* pArrayLayers) override; + virtual void FreeDescriptorSet(CSHandle& complexSetHandle) override; + + virtual void BeginBindDescriptors() override; + virtual void EndBindDescriptors() override; + + // + // Vulkan + // + + void CreateDescriptorSets(); + VkDescriptorSet GetVkDescriptorSet(int setNumber) const; + VkDescriptorSet GetComplexVkDescriptorSet(CSHandle descSetID) const; + + RcCompiled GetCompiled(CSZ branch) const { return _mapCompiled.at(branch); } + + VkPipelineLayout GetVkPipelineLayout() const { return _pipelineLayout; } + + bool TryPushConstants(int setNumber, RBaseCommandBuffer cb) const; + int UpdateUniformBuffer(int setNumber); + + bool IsCompute() const { return _compute; } + + void OnError(CSZ s) const; + + void UpdateUtilization() const; + }; + VERUS_TYPEDEFS(ShaderVulkan); } diff --git a/RendererVulkan/src/CGI/TextureVulkan.h b/RendererVulkan/src/CGI/TextureVulkan.h index 6f11a91..f689d0e 100644 --- a/RendererVulkan/src/CGI/TextureVulkan.h +++ b/RendererVulkan/src/CGI/TextureVulkan.h @@ -1,63 +1,60 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class TextureVulkan : public BaseTexture { - class TextureVulkan : public BaseTexture + struct BufferEx { - struct BufferEx - { - VkBuffer _buffer = VK_NULL_HANDLE; - VmaAllocation _vmaAllocation = VK_NULL_HANDLE; - }; - - VkImage _image = VK_NULL_HANDLE; - VmaAllocation _vmaAllocation = VK_NULL_HANDLE; - VkImage _storageImage = VK_NULL_HANDLE; - VmaAllocation _storageVmaAllocation = VK_NULL_HANDLE; - VkImageView _imageView = VK_NULL_HANDLE; - VkImageView _imageViewForFramebuffer[+CubeMapFace::count] = {}; - VkSampler _sampler = VK_NULL_HANDLE; - Vector _vDefinedSubresources; - Vector _vStorageImageViews; - Vector _vStagingBuffers; - Vector _vReadbackBuffers; - Vector _vCshGenerateMips; - bool _definedStorage = false; - - public: - TextureVulkan(); - virtual ~TextureVulkan() override; - - virtual void Init(RcTextureDesc desc) override; - virtual void Done() override; - - virtual void UpdateSubresource(const void* p, int mipLevel, int arrayLayer, PBaseCommandBuffer pCB) override; - virtual bool ReadbackSubresource(void* p, bool recordCopyCommand, PBaseCommandBuffer pCB) override; - - virtual void GenerateMips(PBaseCommandBuffer pCB) override; - void GenerateCubeMapMips(PBaseCommandBuffer pCB); - - virtual Continue Scheduled_Update() override; - - // - // Vulkan - // - - void CreateSampler(); - - VkImage GetVkImage() const { return _image; } - VkImageView GetVkImageView() const { return _imageView; } - VkImageView GetVkImageViewForFramebuffer(CubeMapFace face) const; - VkImageView GetStorageVkImageView(int mipLevel, int arrayLayer) const { return _vStorageImageViews[mipLevel + arrayLayer * (_desc._mipLevels - 1)]; } - VkSampler GetVkSampler() const { return _sampler; } - ImageLayout GetSubresourceMainLayout(int mipLevel, int arrayLayer) const; - void MarkSubresourceDefined(int mipLevel, int arrayLayer); - - static VkFormat RemoveSRGB(VkFormat format); + VkBuffer _buffer = VK_NULL_HANDLE; + VmaAllocation _vmaAllocation = VK_NULL_HANDLE; }; - VERUS_TYPEDEFS(TextureVulkan); - } + + VkImage _image = VK_NULL_HANDLE; + VmaAllocation _vmaAllocation = VK_NULL_HANDLE; + VkImage _storageImage = VK_NULL_HANDLE; + VmaAllocation _storageVmaAllocation = VK_NULL_HANDLE; + VkImageView _imageView = VK_NULL_HANDLE; + VkImageView _imageViewForFramebuffer[+CubeMapFace::count] = {}; + VkSampler _sampler = VK_NULL_HANDLE; + Vector _vDefinedSubresources; + Vector _vStorageImageViews; + Vector _vStagingBuffers; + Vector _vReadbackBuffers; + Vector _vCshGenerateMips; + bool _definedStorage = false; + + public: + TextureVulkan(); + virtual ~TextureVulkan() override; + + virtual void Init(RcTextureDesc desc) override; + virtual void Done() override; + + virtual void UpdateSubresource(const void* p, int mipLevel, int arrayLayer, PBaseCommandBuffer pCB) override; + virtual bool ReadbackSubresource(void* p, bool recordCopyCommand, PBaseCommandBuffer pCB) override; + + virtual void GenerateMips(PBaseCommandBuffer pCB) override; + void GenerateCubeMapMips(PBaseCommandBuffer pCB); + + virtual Continue Scheduled_Update() override; + + // + // Vulkan + // + + void CreateSampler(); + + VkImage GetVkImage() const { return _image; } + VkImageView GetVkImageView() const { return _imageView; } + VkImageView GetVkImageViewForFramebuffer(CubeMapFace face) const; + VkImageView GetStorageVkImageView(int mipLevel, int arrayLayer) const { return _vStorageImageViews[mipLevel + arrayLayer * (_desc._mipLevels - 1)]; } + VkSampler GetVkSampler() const { return _sampler; } + ImageLayout GetSubresourceMainLayout(int mipLevel, int arrayLayer) const; + void MarkSubresourceDefined(int mipLevel, int arrayLayer); + + static VkFormat RemoveSRGB(VkFormat format); + }; + VERUS_TYPEDEFS(TextureVulkan); } diff --git a/TextureTool/TextureTool.vcxproj b/TextureTool/TextureTool.vcxproj index aac8068..715d908 100644 --- a/TextureTool/TextureTool.vcxproj +++ b/TextureTool/TextureTool.vcxproj @@ -11,23 +11,23 @@ - 16.0 + 17.0 Win32Proj {5A1A3E76-7F69-48B6-B1E3-F6BB281B7E73} TextureTool - 10.0.20348.0 + 10.0.22000.0 Application true - v142 + v143 Unicode Application false - v142 + v143 true Unicode @@ -45,18 +45,13 @@ - - true - - - false - Level3 true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true + stdcpp20 Console @@ -71,6 +66,7 @@ true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true + stdcpp20 Console diff --git a/Verus.sln b/Verus.sln index 98b2976..0fff8f7 100644 --- a/Verus.sln +++ b/Verus.sln @@ -1,25 +1,25 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29613.14 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34003.232 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Verus", "Verus\Verus.vcxproj", "{B154D670-E4B1-4D8A-885C-69546A5BD833}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloTexturedCube", "HelloTexturedCube\HelloTexturedCube.vcxproj", "{26BD6E61-E36D-464A-A312-4110ADF10083}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloTriangle", "HelloTriangle\HelloTriangle.vcxproj", "{BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PAKBuilder", "PAKBuilder\PAKBuilder.vcxproj", "{EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RendererDirect3D11", "RendererDirect3D11\RendererDirect3D11.vcxproj", "{8269DCCE-E226-46E4-B9F6-290AB5DF2678}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RendererDirect3D12", "RendererDirect3D12\RendererDirect3D12.vcxproj", "{53923514-84B2-4B78-889A-8709C6BFA3A5}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RendererVulkan", "RendererVulkan\RendererVulkan.vcxproj", "{C9195A1C-9224-4B40-BBBC-AA90EF3BE3E0}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "VulkanShaderCompiler", "VulkanShaderCompiler\VulkanShaderCompiler.vcxproj", "{1EA5F5D1-9138-406D-871B-3CD75343E14C}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PAKBuilder", "PAKBuilder\PAKBuilder.vcxproj", "{EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TextureTool", "TextureTool\TextureTool.vcxproj", "{5A1A3E76-7F69-48B6-B1E3-F6BB281B7E73}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloTriangle", "HelloTriangle\HelloTriangle.vcxproj", "{BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Verus", "Verus\Verus.vcxproj", "{B154D670-E4B1-4D8A-885C-69546A5BD833}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloTexturedCube", "HelloTexturedCube\HelloTexturedCube.vcxproj", "{26BD6E61-E36D-464A-A312-4110ADF10083}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RendererDirect3D11", "RendererDirect3D11\RendererDirect3D11.vcxproj", "{8269DCCE-E226-46E4-B9F6-290AB5DF2678}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "VulkanShaderCompiler", "VulkanShaderCompiler\VulkanShaderCompiler.vcxproj", "{1EA5F5D1-9138-406D-871B-3CD75343E14C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -27,10 +27,22 @@ Global Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B154D670-E4B1-4D8A-885C-69546A5BD833}.Debug|x64.ActiveCfg = Debug|x64 - {B154D670-E4B1-4D8A-885C-69546A5BD833}.Debug|x64.Build.0 = Debug|x64 - {B154D670-E4B1-4D8A-885C-69546A5BD833}.Release|x64.ActiveCfg = Release|x64 - {B154D670-E4B1-4D8A-885C-69546A5BD833}.Release|x64.Build.0 = Release|x64 + {26BD6E61-E36D-464A-A312-4110ADF10083}.Debug|x64.ActiveCfg = Debug|x64 + {26BD6E61-E36D-464A-A312-4110ADF10083}.Debug|x64.Build.0 = Debug|x64 + {26BD6E61-E36D-464A-A312-4110ADF10083}.Release|x64.ActiveCfg = Release|x64 + {26BD6E61-E36D-464A-A312-4110ADF10083}.Release|x64.Build.0 = Release|x64 + {BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}.Debug|x64.ActiveCfg = Debug|x64 + {BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}.Debug|x64.Build.0 = Debug|x64 + {BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}.Release|x64.ActiveCfg = Release|x64 + {BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}.Release|x64.Build.0 = Release|x64 + {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}.Debug|x64.ActiveCfg = Debug|x64 + {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}.Debug|x64.Build.0 = Debug|x64 + {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}.Release|x64.ActiveCfg = Release|x64 + {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}.Release|x64.Build.0 = Release|x64 + {8269DCCE-E226-46E4-B9F6-290AB5DF2678}.Debug|x64.ActiveCfg = Debug|x64 + {8269DCCE-E226-46E4-B9F6-290AB5DF2678}.Debug|x64.Build.0 = Debug|x64 + {8269DCCE-E226-46E4-B9F6-290AB5DF2678}.Release|x64.ActiveCfg = Release|x64 + {8269DCCE-E226-46E4-B9F6-290AB5DF2678}.Release|x64.Build.0 = Release|x64 {53923514-84B2-4B78-889A-8709C6BFA3A5}.Debug|x64.ActiveCfg = Debug|x64 {53923514-84B2-4B78-889A-8709C6BFA3A5}.Debug|x64.Build.0 = Debug|x64 {53923514-84B2-4B78-889A-8709C6BFA3A5}.Release|x64.ActiveCfg = Release|x64 @@ -39,30 +51,18 @@ Global {C9195A1C-9224-4B40-BBBC-AA90EF3BE3E0}.Debug|x64.Build.0 = Debug|x64 {C9195A1C-9224-4B40-BBBC-AA90EF3BE3E0}.Release|x64.ActiveCfg = Release|x64 {C9195A1C-9224-4B40-BBBC-AA90EF3BE3E0}.Release|x64.Build.0 = Release|x64 - {1EA5F5D1-9138-406D-871B-3CD75343E14C}.Debug|x64.ActiveCfg = Debug|x64 - {1EA5F5D1-9138-406D-871B-3CD75343E14C}.Debug|x64.Build.0 = Debug|x64 - {1EA5F5D1-9138-406D-871B-3CD75343E14C}.Release|x64.ActiveCfg = Release|x64 - {1EA5F5D1-9138-406D-871B-3CD75343E14C}.Release|x64.Build.0 = Release|x64 - {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}.Debug|x64.ActiveCfg = Debug|x64 - {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}.Debug|x64.Build.0 = Debug|x64 - {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}.Release|x64.ActiveCfg = Release|x64 - {EBF1E2F9-65AA-419D-A3D3-AD66EB086E57}.Release|x64.Build.0 = Release|x64 {5A1A3E76-7F69-48B6-B1E3-F6BB281B7E73}.Debug|x64.ActiveCfg = Debug|x64 {5A1A3E76-7F69-48B6-B1E3-F6BB281B7E73}.Debug|x64.Build.0 = Debug|x64 {5A1A3E76-7F69-48B6-B1E3-F6BB281B7E73}.Release|x64.ActiveCfg = Release|x64 {5A1A3E76-7F69-48B6-B1E3-F6BB281B7E73}.Release|x64.Build.0 = Release|x64 - {BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}.Debug|x64.ActiveCfg = Debug|x64 - {BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}.Debug|x64.Build.0 = Debug|x64 - {BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}.Release|x64.ActiveCfg = Release|x64 - {BC17ACD3-97EB-4D5C-A2C9-574CDAA7576B}.Release|x64.Build.0 = Release|x64 - {26BD6E61-E36D-464A-A312-4110ADF10083}.Debug|x64.ActiveCfg = Debug|x64 - {26BD6E61-E36D-464A-A312-4110ADF10083}.Debug|x64.Build.0 = Debug|x64 - {26BD6E61-E36D-464A-A312-4110ADF10083}.Release|x64.ActiveCfg = Release|x64 - {26BD6E61-E36D-464A-A312-4110ADF10083}.Release|x64.Build.0 = Release|x64 - {8269DCCE-E226-46E4-B9F6-290AB5DF2678}.Debug|x64.ActiveCfg = Debug|x64 - {8269DCCE-E226-46E4-B9F6-290AB5DF2678}.Debug|x64.Build.0 = Debug|x64 - {8269DCCE-E226-46E4-B9F6-290AB5DF2678}.Release|x64.ActiveCfg = Release|x64 - {8269DCCE-E226-46E4-B9F6-290AB5DF2678}.Release|x64.Build.0 = Release|x64 + {B154D670-E4B1-4D8A-885C-69546A5BD833}.Debug|x64.ActiveCfg = Debug|x64 + {B154D670-E4B1-4D8A-885C-69546A5BD833}.Debug|x64.Build.0 = Debug|x64 + {B154D670-E4B1-4D8A-885C-69546A5BD833}.Release|x64.ActiveCfg = Release|x64 + {B154D670-E4B1-4D8A-885C-69546A5BD833}.Release|x64.Build.0 = Release|x64 + {1EA5F5D1-9138-406D-871B-3CD75343E14C}.Debug|x64.ActiveCfg = Debug|x64 + {1EA5F5D1-9138-406D-871B-3CD75343E14C}.Debug|x64.Build.0 = Debug|x64 + {1EA5F5D1-9138-406D-871B-3CD75343E14C}.Release|x64.ActiveCfg = Release|x64 + {1EA5F5D1-9138-406D-871B-3CD75343E14C}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Verus/Verus.props b/Verus/Verus.props index 2400d40..69d5a23 100644 --- a/Verus/Verus.props +++ b/Verus/Verus.props @@ -3,8 +3,8 @@ - C:\Compressonator_4.3.206\include;C:\Home\Projects\Verus\verus\Verus\src;C:\Home\Middleware\AMD Tootle 2.3\include;C:\Home\Middleware\bullet3-2.89\src;C:\Home\Middleware\bullet3-2.89\Extras;C:\Home\Middleware\libogg-1.3.5\include;C:\Home\Middleware\libvorbis-1.3.7\include;C:\Home\Middleware\openal-soft-1.22.0-bin\include;C:\Home\Middleware\OpenXR-SDK-release-1.0.27\include;C:\Home\Middleware\SDL2-2.0.22\include;C:\Home\Middleware\WinPixEventRuntime\include;C:\VulkanSDK\1.3.239.0\Include;$(IncludePath) - C:\Compressonator_4.3.206\lib\VS2019\x64;C:\Home\Middleware\bullet3-2.89\bin;C:\Home\Middleware\AMD Tootle 2.3\lib;C:\Home\Middleware\libogg-1.3.5\lib;C:\Home\Middleware\libvorbis-1.3.7\lib2;C:\Home\Middleware\openal-soft-1.22.0-bin\libs\Win64;C:\Home\Middleware\OpenXR-SDK-release-1.0.27\lib;C:\Home\Middleware\SDL2-2.0.22\lib\x64;C:\Home\Middleware\WinPixEventRuntime\lib;C:\VulkanSDK\1.3.239.0\Lib;$(LibraryPath) + C:\Compressonator_4.3.206\include;C:\Home\Projects\Verus\verus\Verus\src;C:\Home\Middleware\AMD Tootle 2.3\include;C:\Home\Middleware\bullet3-3.25\src;C:\Home\Middleware\bullet3-3.25\Extras;C:\Home\Middleware\libogg-1.3.5\include;C:\Home\Middleware\libvorbis-1.3.7\include;C:\Home\Middleware\openal-soft-1.22.0-bin\include;C:\Home\Middleware\OpenXR-SDK-release-1.0.27\include;C:\Home\Middleware\SDL2-2.0.22\include;C:\Home\Middleware\WinPixEventRuntime\include;C:\VulkanSDK\1.3.239.0\Include;$(IncludePath) + C:\Compressonator_4.3.206\lib\VS2019\x64;C:\Home\Middleware\bullet3-3.25\bin;C:\Home\Middleware\AMD Tootle 2.3\lib;C:\Home\Middleware\libogg-1.3.5\lib;C:\Home\Middleware\libvorbis-1.3.7\lib2;C:\Home\Middleware\openal-soft-1.22.0-bin\libs\Win64;C:\Home\Middleware\OpenXR-SDK-release-1.0.27\lib;C:\Home\Middleware\SDL2-2.0.22\lib\x64;C:\Home\Middleware\WinPixEventRuntime\lib;C:\VulkanSDK\1.3.239.0\Lib;$(LibraryPath) diff --git a/Verus/Verus.vcxproj b/Verus/Verus.vcxproj index 102f3e8..326f09b 100644 --- a/Verus/Verus.vcxproj +++ b/Verus/Verus.vcxproj @@ -11,23 +11,23 @@ - 16.0 + 17.0 Win32Proj {B154D670-E4B1-4D8A-885C-69546A5BD833} Verus - 10.0.20348.0 + 10.0.22000.0 StaticLibrary true - v142 + v143 Unicode StaticLibrary false - v142 + v143 true Unicode @@ -45,12 +45,6 @@ - - true - - - false - Level3 @@ -60,6 +54,7 @@ Use verus.h Fast + stdcpp20 @@ -78,6 +73,7 @@ Use verus.h Fast + stdcpp20 @@ -216,7 +212,6 @@ - diff --git a/Verus/Verus.vcxproj.filters b/Verus/Verus.vcxproj.filters index 5ccb7b7..924edd7 100644 --- a/Verus/Verus.vcxproj.filters +++ b/Verus/Verus.vcxproj.filters @@ -165,9 +165,6 @@ src\Global - - src\Global - src\Global diff --git a/Verus/src/AI/TaskDriver.h b/Verus/src/AI/TaskDriver.h index 418975b..7a7f74e 100644 --- a/Verus/src/AI/TaskDriver.h +++ b/Verus/src/AI/TaskDriver.h @@ -1,59 +1,56 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::AI { - namespace AI + struct TaskDriverDelegate { - struct TaskDriverDelegate + virtual void TaskDriver_OnTask(CSZ task, CSZ mode) = 0; + }; + VERUS_TYPEDEFS(TaskDriverDelegate); + + class TaskDriver + { + struct Task { - virtual void TaskDriver_OnTask(CSZ task, CSZ mode) = 0; + String _name; + float _chance = 100; + float _time = 0; + float _deadline = 0; + float _intervalMin = 0; + float _intervalSize = 0; }; - VERUS_TYPEDEFS(TaskDriverDelegate); + VERUS_TYPEDEFS(Task); - class TaskDriver + typedef Map TMapTasks; + + struct Mode { - struct Task - { - String _name; - float _chance = 100; - float _time = 0; - float _deadline = 0; - float _intervalMin = 0; - float _intervalSize = 0; - }; - VERUS_TYPEDEFS(Task); - - typedef Map TMapTasks; - - struct Mode - { - String _name; - TMapTasks _mapTasks; - }; - VERUS_TYPEDEFS(Mode); - - typedef Map TMapModes; - - TMapModes _mapModes; - String _currentMode; - PTaskDriverDelegate _pDelegate = nullptr; - float _cooldown = 1; - float _cooldownTimer = 0; - - public: - TaskDriver(); - ~TaskDriver(); - - void Update(); - - Str GetCurrentMode() const { return _C(_currentMode); } - void SetCurrentMode(CSZ name) { _currentMode = name; } - void SetDelegate(PTaskDriverDelegate p) { _pDelegate = p; } - - void AddMode(CSZ name); - void AddTask(CSZ name, float chance, float intervalMin, float intervalMax, CSZ mode = nullptr); + String _name; + TMapTasks _mapTasks; }; - VERUS_TYPEDEFS(TaskDriver); - } + VERUS_TYPEDEFS(Mode); + + typedef Map TMapModes; + + TMapModes _mapModes; + String _currentMode; + PTaskDriverDelegate _pDelegate = nullptr; + float _cooldown = 1; + float _cooldownTimer = 0; + + public: + TaskDriver(); + ~TaskDriver(); + + void Update(); + + Str GetCurrentMode() const { return _C(_currentMode); } + void SetCurrentMode(CSZ name) { _currentMode = name; } + void SetDelegate(PTaskDriverDelegate p) { _pDelegate = p; } + + void AddMode(CSZ name); + void AddTask(CSZ name, float chance, float intervalMin, float intervalMax, CSZ mode = nullptr); + }; + VERUS_TYPEDEFS(TaskDriver); } diff --git a/Verus/src/AI/Turret.h b/Verus/src/AI/Turret.h index b10e0ef..0f3ad27 100644 --- a/Verus/src/AI/Turret.h +++ b/Verus/src/AI/Turret.h @@ -1,38 +1,35 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::AI { - namespace AI + class Turret { - class Turret - { - float _targetPitch = 0; - float _targetYaw = 0; - float _actualPitch = 0; - float _actualYaw = 0; - float _pitchSpeed = 1; - float _yawSpeed = 1; + float _targetPitch = 0; + float _targetYaw = 0; + float _actualPitch = 0; + float _actualYaw = 0; + float _pitchSpeed = 1; + float _yawSpeed = 1; - public: - void Update(); + public: + void Update(); - float GetTargetPitch() const { return _targetPitch; } - float GetTargetYaw() const { return _targetYaw; } - float GetActualPitch() const { return _actualPitch; } - float GetActualYaw() const { return _actualYaw; } + float GetTargetPitch() const { return _targetPitch; } + float GetTargetYaw() const { return _targetYaw; } + float GetActualPitch() const { return _actualPitch; } + float GetActualYaw() const { return _actualYaw; } - bool IsTargetPitchReached(float threshold) const; - bool IsTargetYawReached(float threshold) const; + bool IsTargetPitchReached(float threshold) const; + bool IsTargetYawReached(float threshold) const; - // Speed: - float GetPitchSpeed() const { return _pitchSpeed; } - float GetYawSpeed() const { return _yawSpeed; } - void SetPitchSpeed(float x) { _pitchSpeed = x; } - void SetYawSpeed(float x) { _yawSpeed = x; } + // Speed: + float GetPitchSpeed() const { return _pitchSpeed; } + float GetYawSpeed() const { return _yawSpeed; } + void SetPitchSpeed(float x) { _pitchSpeed = x; } + void SetYawSpeed(float x) { _yawSpeed = x; } - void LookAt(RcVector3 rayFromTurret, bool instantly = false); - }; - VERUS_TYPEDEFS(Turret); - } + void LookAt(RcVector3 rayFromTurret, bool instantly = false); + }; + VERUS_TYPEDEFS(Turret); } diff --git a/Verus/src/Anim/Animation.h b/Verus/src/Anim/Animation.h index 6f78204..b9eb70e 100644 --- a/Verus/src/Anim/Animation.h +++ b/Verus/src/Anim/Animation.h @@ -1,114 +1,111 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Anim { - namespace Anim + struct AnimationDelegate { - struct AnimationDelegate + virtual void Animation_OnEnd(CSZ name) {} + virtual void Animation_OnTrigger(CSZ name, int state) {} + }; + VERUS_TYPEDEFS(AnimationDelegate); + + // Objects of this type are stored in Collection. + struct MotionData + { + Motion _motion; + float _duration = 0; + bool _looping = true; + bool _fast = false; // For auto easing. + }; + VERUS_TYPEDEFS(MotionData); + + typedef StoreUniqueWithNoRefCount TStoreMotions; + // The collection of motion objects that can be reused by multiple animation objects. + class Collection : private TStoreMotions, public IO::AsyncDelegate + { + bool _useShortNames = true; + + public: + Collection(bool useShortNames = true); + ~Collection(); + + virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; + + void AddMotion(CSZ name, bool looping = true, float duration = 0, bool fast = false); + void DeleteAll(); + PMotionData Find(CSZ name); + int GetMaxBones(); + }; + VERUS_TYPEDEFS(Collection); + + // Holds the collection of motion objects and provides the ability to interpolate between them. + // Note: triggers will work properly with 'multiple animations' + 'single collection' only if you add motions before binding collection. + class Animation : public MotionDelegate + { + public: + static const int s_maxLayers = 8; + + enum class Edge : int { - virtual void Animation_OnEnd(CSZ name) {} - virtual void Animation_OnTrigger(CSZ name, int state) {} + begin = (1 << 0), + end = (1 << 1) }; - VERUS_TYPEDEFS(AnimationDelegate); - // Objects of this type are stored in Collection. - struct MotionData + struct Layer { - Motion _motion; - float _duration = 0; - bool _looping = true; - bool _fast = false; // For auto easing. + Animation* _pAnimation = nullptr; + CSZ _rootBone = nullptr; }; - VERUS_TYPEDEFS(MotionData); + VERUS_TYPEDEFS(Layer); - typedef StoreUniqueWithNoRefCount TStoreMotions; - // The collection of motion objects that can be reused by multiple animation objects. - class Collection : private TStoreMotions, public IO::AsyncDelegate - { - bool _useShortNames = true; + private: + PCollection _pCollection = nullptr; + PAnimationDelegate _pDelegate = nullptr; + PSkeleton _pSkeleton = nullptr; + Motion _transitionMotion; + String _currentMotion; + String _prevMotion; + Vector _vTriggerStates; + Easing _easing = Easing::none; + float _time = 0; + float _transitionDuration = 0; + float _transitionTime = 0; + bool _transition = false; + bool _playing = false; - public: - Collection(bool useShortNames = true); - ~Collection(); + public: + Animation(); + ~Animation(); - virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; + void Update(int layerCount = 0, PLayer pLayers = nullptr); + void UpdateSkeleton(int layerCount = 0, PLayer pLayers = nullptr); - void AddMotion(CSZ name, bool looping = true, float duration = 0, bool fast = false); - void DeleteAll(); - PMotionData Find(CSZ name); - int GetMaxBones(); - }; - VERUS_TYPEDEFS(Collection); + void BindCollection(PCollection p); + void BindSkeleton(PSkeleton p); + PAnimationDelegate SetDelegate(PAnimationDelegate p) { return Utils::Swap(_pDelegate, p); } - // Holds the collection of motion objects and provides the ability to interpolate between them. - // Note: triggers will work properly with 'multiple animations' + 'single collection' only if you add motions before binding collection. - class Animation : public MotionDelegate - { - public: - static const int s_maxLayers = 8; + bool IsPlaying() const { return _playing; } + void Play(); + void Stop(); + void Pause(); - enum class Edge : int - { - begin = (1 << 0), - end = (1 << 1) - }; + Str GetCurrentMotionName() const { return _C(_currentMotion); } - struct Layer - { - Animation* _pAnimation = nullptr; - CSZ _rootBone = nullptr; - }; - VERUS_TYPEDEFS(Layer); + void TransitionTo(CSZ name, + Interval duration = 0.5f, int randTime = -1, PMotion pFromMotion = nullptr); + bool TransitionToNew(std::initializer_list names, + Interval duration = 0.5f, int randTime = -1, PMotion pFromMotion = nullptr); + bool IsInTransition() const { return _transition; } - private: - PCollection _pCollection = nullptr; - PAnimationDelegate _pDelegate = nullptr; - PSkeleton _pSkeleton = nullptr; - Motion _transitionMotion; - String _currentMotion; - String _prevMotion; - Vector _vTriggerStates; - Easing _easing = Easing::none; - float _time = 0; - float _transitionDuration = 0; - float _transitionTime = 0; - bool _transition = false; - bool _playing = false; + virtual void Motion_OnTrigger(CSZ name, int state) override; - public: - Animation(); - ~Animation(); + PMotion GetMotion(); + float GetAlpha(CSZ name = nullptr) const; + float GetTime(); + bool IsNearEdge(float t = 0.1f, Edge edge = Edge::begin | Edge::end); - void Update(int layerCount = 0, PLayer pLayers = nullptr); - void UpdateSkeleton(int layerCount = 0, PLayer pLayers = nullptr); - - void BindCollection(PCollection p); - void BindSkeleton(PSkeleton p); - PAnimationDelegate SetDelegate(PAnimationDelegate p) { return Utils::Swap(_pDelegate, p); } - - bool IsPlaying() const { return _playing; } - void Play(); - void Stop(); - void Pause(); - - Str GetCurrentMotionName() const { return _C(_currentMotion); } - - void TransitionTo(CSZ name, - Interval duration = 0.5f, int randTime = -1, PMotion pFromMotion = nullptr); - bool TransitionToNew(std::initializer_list names, - Interval duration = 0.5f, int randTime = -1, PMotion pFromMotion = nullptr); - bool IsInTransition() const { return _transition; } - - virtual void Motion_OnTrigger(CSZ name, int state) override; - - PMotion GetMotion(); - float GetAlpha(CSZ name = nullptr) const; - float GetTime(); - bool IsNearEdge(float t = 0.1f, Edge edge = Edge::begin | Edge::end); - - int* GetTriggerStatesArray() { return _vTriggerStates.empty() ? nullptr : _vTriggerStates.data(); } - }; - VERUS_TYPEDEFS(Animation); - } + int* GetTriggerStatesArray() { return _vTriggerStates.empty() ? nullptr : _vTriggerStates.data(); } + }; + VERUS_TYPEDEFS(Animation); } diff --git a/Verus/src/Anim/Elastic.h b/Verus/src/Anim/Elastic.h index 2a666ec..06a3c2a 100644 --- a/Verus/src/Anim/Elastic.h +++ b/Verus/src/Anim/Elastic.h @@ -1,135 +1,132 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Anim { - namespace Anim + template + class Elastic { - template - class Elastic + T _target = 0; + T _actual = 0; + float _speed = 1; + float _rate = 1; + + public: + Elastic() { _rate = log(10.f); } + Elastic(const T& x) : _target(x), _actual(x) { _rate = log(10.f); } + Elastic(const T& x, float speed) : _target(x), _actual(x), _speed(speed) { _rate = log(10.f); } + + void operator=(const T& x) { _target = x; } + operator const T& () const { return _actual; } + + const T& GetTarget() const { return _target; } + void SetActual(const T& x) { _actual = x; } + void SetSpeed(float s) { _speed = s; } + void ForceTarget() { _actual = _target; } + void ForceTarget(const T& x) { _actual = _target = x; } + float GetDelta() const { return angle ? Math::WrapAngle(_target - _actual) : _target - _actual; } + void Update() { - T _target = 0; - T _actual = 0; - float _speed = 1; - float _rate = 1; - - public: - Elastic() { _rate = log(10.f); } - Elastic(const T& x) : _target(x), _actual(x) { _rate = log(10.f); } - Elastic(const T& x, float speed) : _target(x), _actual(x), _speed(speed) { _rate = log(10.f); } - - void operator=(const T& x) { _target = x; } - operator const T& () const { return _actual; } - - const T& GetTarget() const { return _target; } - void SetActual(const T& x) { _actual = x; } - void SetSpeed(float s) { _speed = s; } - void ForceTarget() { _actual = _target; } - void ForceTarget(const T& x) { _actual = _target = x; } - float GetDelta() const { return angle ? Math::WrapAngle(_target - _actual) : _target - _actual; } - void Update() + const T d = _target - _actual; + if (angle) { - const T d = _target - _actual; + VERUS_RT_ASSERT(_target >= T(-4) && _target < T(4)); + VERUS_RT_ASSERT(_actual >= T(-4) && _actual < T(4)); + if (d > T(VERUS_PI)) + _actual += VERUS_2PI; + else if (d < T(-VERUS_PI)) + _actual -= VERUS_2PI; + } + if (abs(d) < VERUS_FLOAT_THRESHOLD) + { + _actual = _target; + } + else + { + VERUS_QREF_TIMER; + const float ratio = 1 / exp(_speed * dt * _rate); // Exponential decay. + _actual = Math::Lerp(_target, _actual, ratio); if (angle) - { - VERUS_RT_ASSERT(_target >= T(-4) && _target < T(4)); - VERUS_RT_ASSERT(_actual >= T(-4) && _actual < T(4)); - if (d > T(VERUS_PI)) - _actual += VERUS_2PI; - else if (d < T(-VERUS_PI)) - _actual -= VERUS_2PI; - } - if (abs(d) < VERUS_FLOAT_THRESHOLD) - { - _actual = _target; - } - else - { - VERUS_QREF_TIMER; - const float ratio = 1 / exp(_speed * dt * _rate); // Exponential decay. - _actual = Math::Lerp(_target, _actual, ratio); - if (angle) - _actual = Math::WrapAngle(_actual); - } + _actual = Math::WrapAngle(_actual); } - }; + } + }; - template<> - class Elastic + template<> + class Elastic + { + typedef Vector3 T; + + T _target = 0; + T _actual = 0; + float _speed = 1; + float _rate = 1; + + public: + Elastic() { _rate = log(10.f); } + Elastic(const T& x) : _target(x), _actual(x) { _rate = log(10.f); } + Elastic(const T& x, float speed) : _target(x), _actual(x), _speed(speed) { _rate = log(10.f); } + + void operator=(const T& x) { _target = x; } + operator const T& () const { return _actual; } + + const T& GetTarget() const { return _target; } + void SetActual(const T& x) { _actual = x; } + void SetSpeed(float s) { _speed = s; } + void ForceTarget() { _actual = _target; } + void ForceTarget(const T& x) { _actual = _target = x; } + void Update() { - typedef Vector3 T; - - T _target = 0; - T _actual = 0; - float _speed = 1; - float _rate = 1; - - public: - Elastic() { _rate = log(10.f); } - Elastic(const T& x) : _target(x), _actual(x) { _rate = log(10.f); } - Elastic(const T& x, float speed) : _target(x), _actual(x), _speed(speed) { _rate = log(10.f); } - - void operator=(const T& x) { _target = x; } - operator const T& () const { return _actual; } - - const T& GetTarget() const { return _target; } - void SetActual(const T& x) { _actual = x; } - void SetSpeed(float s) { _speed = s; } - void ForceTarget() { _actual = _target; } - void ForceTarget(const T& x) { _actual = _target = x; } - void Update() + const Vector3 d = _target - _actual; + if (VMath::dot(d, d) < VERUS_FLOAT_THRESHOLD * VERUS_FLOAT_THRESHOLD) { - const Vector3 d = _target - _actual; - if (VMath::dot(d, d) < VERUS_FLOAT_THRESHOLD * VERUS_FLOAT_THRESHOLD) - { - _actual = _target; - } - else - { - VERUS_QREF_TIMER; - const float ratio = 1 / exp(_speed * dt * _rate); // Exponential decay. - _actual = VMath::lerp(ratio, _target, _actual); - } + _actual = _target; } - }; + else + { + VERUS_QREF_TIMER; + const float ratio = 1 / exp(_speed * dt * _rate); // Exponential decay. + _actual = VMath::lerp(ratio, _target, _actual); + } + } + }; - template<> - class Elastic + template<> + class Elastic + { + typedef Point3 T; + + T _target = 0; + T _actual = 0; + float _speed = 1; + float _rate = 1; + + public: + Elastic() { _rate = log(10.f); } + Elastic(const T& x) : _target(x), _actual(x) { _rate = log(10.f); } + Elastic(const T& x, float speed) : _target(x), _actual(x), _speed(speed) { _rate = log(10.f); } + + void operator=(const T& x) { _target = x; } + operator const T& () const { return _actual; } + + const T& GetTarget() const { return _target; } + void SetActual(const T& x) { _actual = x; } + void SetSpeed(float s) { _speed = s; } + void ForceTarget() { _actual = _target; } + void ForceTarget(const T& x) { _actual = _target = x; } + void Update() { - typedef Point3 T; - - T _target = 0; - T _actual = 0; - float _speed = 1; - float _rate = 1; - - public: - Elastic() { _rate = log(10.f); } - Elastic(const T& x) : _target(x), _actual(x) { _rate = log(10.f); } - Elastic(const T& x, float speed) : _target(x), _actual(x), _speed(speed) { _rate = log(10.f); } - - void operator=(const T& x) { _target = x; } - operator const T& () const { return _actual; } - - const T& GetTarget() const { return _target; } - void SetActual(const T& x) { _actual = x; } - void SetSpeed(float s) { _speed = s; } - void ForceTarget() { _actual = _target; } - void ForceTarget(const T& x) { _actual = _target = x; } - void Update() + const Vector3 d = _target - _actual; + if (VMath::dot(d, d) < VERUS_FLOAT_THRESHOLD * VERUS_FLOAT_THRESHOLD) { - const Vector3 d = _target - _actual; - if (VMath::dot(d, d) < VERUS_FLOAT_THRESHOLD * VERUS_FLOAT_THRESHOLD) - { - _actual = _target; - } - else - { - VERUS_QREF_TIMER; - const float ratio = 1 / exp(_speed * dt * _rate); // Exponential decay. - _actual = VMath::lerp(ratio, _target, _actual); - } + _actual = _target; } - }; - } + else + { + VERUS_QREF_TIMER; + const float ratio = 1 / exp(_speed * dt * _rate); // Exponential decay. + _actual = VMath::lerp(ratio, _target, _actual); + } + } + }; } diff --git a/Verus/src/Anim/Motion.cpp b/Verus/src/Anim/Motion.cpp index cc0f96d..10fd9df 100644 --- a/Verus/src/Anim/Motion.cpp +++ b/Verus/src/Anim/Motion.cpp @@ -462,16 +462,16 @@ void Motion::Bone::DeleteRedundantKeyframes(float boneAccLength) // Which keyframe can be removed with the least error? float leastError = threshold; int frameWithLeastError = -1; - for (const auto& kv : mapSaved) + for (const auto& [key, value] : mapSaved) { - const int excludeFrame = kv.first; + const int excludeFrame = key; if (!excludeFrame || _pMotion->GetFrameCount() == excludeFrame) continue; _mapRot.clear(); - for (const auto& kv2 : mapSaved) + for (const auto& [key2, value2] : mapSaved) { - if (kv2.first != excludeFrame) - _mapRot[kv2.first] = kv2.second; + if (key2 != excludeFrame) + _mapRot[key2] = value2; } float accError = 0; @@ -523,16 +523,16 @@ void Motion::Bone::DeleteRedundantKeyframes(float boneAccLength) // Which keyframe can be removed with the least error? float leastError = threshold; int frameWithLeastError = -1; - for (const auto& kv : mapSaved) + for (const auto& [key, value] : mapSaved) { - const int excludeFrame = kv.first; + const int excludeFrame = key; if (!excludeFrame || _pMotion->GetFrameCount() == excludeFrame) continue; _mapPos.clear(); - for (const auto& kv2 : mapSaved) + for (const auto& [key2, value2] : mapSaved) { - if (kv2.first != excludeFrame) - _mapPos[kv2.first] = kv2.second; + if (key2 != excludeFrame) + _mapPos[key2] = value2; } float accError = 0; @@ -584,16 +584,16 @@ void Motion::Bone::DeleteRedundantKeyframes(float boneAccLength) // Which keyframe can be removed with the least error? float leastError = threshold; int frameWithLeastError = -1; - for (const auto& kv : mapSaved) + for (const auto& [key, value] : mapSaved) { - const int excludeFrame = kv.first; + const int excludeFrame = key; if (!excludeFrame || _pMotion->GetFrameCount() == excludeFrame) continue; _mapScale.clear(); - for (const auto& kv2 : mapSaved) + for (const auto& [key2, value2] : mapSaved) { - if (kv2.first != excludeFrame) - _mapScale[kv2.first] = kv2.second; + if (key2 != excludeFrame) + _mapScale[key2] = value2; } float accError = 0; @@ -927,10 +927,10 @@ void Motion::Done() Motion::PBone Motion::GetBoneByIndex(int index) { int i = 0; - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { if (i == index) - return &kv.second; + return &value; i++; } return nullptr; @@ -989,9 +989,9 @@ void Motion::Serialize(IO::RStream stream) stream << _fps; stream << GetBoneCount(); - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; stream.WriteString(_C(bone.GetName())); bone.Serialize(stream, version); } @@ -1078,27 +1078,27 @@ void Motion::DeleteRedundantKeyframes(Map& mapBoneAccLengths) void Motion::DeleteOddKeyframes() { - for (auto& kv : _mapBones) - kv.second.DeleteOddKeyframes(); + for (auto& [key, value] : _mapBones) + value.DeleteOddKeyframes(); } void Motion::InsertLoopKeyframes() { - for (auto& kv : _mapBones) - kv.second.InsertLoopKeyframes(); + for (auto& [key, value] : _mapBones) + value.InsertLoopKeyframes(); } void Motion::Cut(int frame, bool before) { - for (auto& kv : _mapBones) - kv.second.Cut(frame, before); + for (auto& [key, value] : _mapBones) + value.Cut(frame, before); _frameCount = before ? _frameCount - frame : frame + 1; } void Motion::Fix(bool speedLimit) { - for (auto& kv : _mapBones) - kv.second.Fix(speedLimit); + for (auto& [key, value] : _mapBones) + value.Fix(speedLimit); } void Motion::ProcessTriggers(float time, PMotionDelegate p, int* pUserTriggerStates) @@ -1110,9 +1110,9 @@ void Motion::ProcessTriggers(float time, PMotionDelegate p, int* pUserTriggerSta nativeTime = GetNativeDuration() - nativeTime; int i = 0; - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - PBone pBone = &kv.second; + PBone pBone = &value; int state = 0; if (!(_reversed && nativeTime < _fpsInv * 0.5f)) // Avoid edge case for the first frame in reverse. pBone->ComputeTriggerAt(nativeTime, state); @@ -1132,9 +1132,9 @@ void Motion::ProcessTriggers(float time, PMotionDelegate p, int* pUserTriggerSta void Motion::ResetTriggers(int* pUserTriggerStates) { int i = 0; - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - PBone pBone = &kv.second; + PBone pBone = &value; int state = 0; if (_reversed) pBone->ComputeTriggerAt(GetNativeDuration(), state); @@ -1153,9 +1153,9 @@ void Motion::SkipTriggers(float time, int* pUserTriggerStates) nativeTime = GetNativeDuration() - nativeTime; int i = 0; - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - PBone pBone = &kv.second; + PBone pBone = &value; int state; pBone->ComputeTriggerAt(nativeTime, state); if (pUserTriggerStates) @@ -1242,14 +1242,14 @@ void Motion::Exec(CSZ code, PBone pBone, Bone::Channel channel) } else { - for (auto& bone : _mapBones) + for (auto& [key, value] : _mapBones) { if (!strcmp(what, "rot")) - bone.second._mapRot.clear(); + value._mapRot.clear(); if (!strcmp(what, "pos")) - bone.second._mapPos.clear(); + value._mapPos.clear(); if (!strcmp(what, "scale")) - bone.second._mapScale.clear(); + value._mapScale.clear(); } } } diff --git a/Verus/src/Anim/Motion.h b/Verus/src/Anim/Motion.h index 6915302..6260e2a 100644 --- a/Verus/src/Anim/Motion.h +++ b/Verus/src/Anim/Motion.h @@ -1,342 +1,339 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Anim { - namespace Anim + struct MotionDelegate { - struct MotionDelegate - { - virtual void Motion_OnTrigger(CSZ name, int state) = 0; - }; - VERUS_TYPEDEFS(MotionDelegate); + virtual void Motion_OnTrigger(CSZ name, int state) = 0; + }; + VERUS_TYPEDEFS(MotionDelegate); - // Motion holds a series of keyframes and provides the ability to interpolate between them. - // Motion can be stored in XAN format. - // Motion's rate can be scaled and even reversed. - // Animation object can be used to handle multiple motion objects. - class Motion : public Object + // Motion holds a series of keyframes and provides the ability to interpolate between them. + // Motion can be stored in XAN format. + // Motion's rate can be scaled and even reversed. + // Animation object can be used to handle multiple motion objects. + class Motion : public Object + { + public: + class Bone : public AllocatorAware { public: - class Bone : public AllocatorAware + enum class Channel : int { - public: - enum class Channel : int - { - rotation, - position, - scale, - trigger - }; - - enum class Flags : UINT32 - { - none = 0, - slerpRot = (1 << 0), - splinePos = (1 << 1), - splineScale = (1 << 2) - }; - - private: - friend class Motion; - - static const float s_magicValueForCircle; - - class Rotation - { - public: - Quat _q; - - Rotation(); - Rotation(RcQuat q); - Rotation(RcVector3 euler); - }; - VERUS_TYPEDEFS(Rotation); - - typedef Map TMapRot; - typedef Map TMapPos; - typedef Map TMapScale; - typedef Map TMapTrigger; - - String _name; - Motion* _pMotion = nullptr; - TMapRot _mapRot; // Rotation keyframes. - TMapPos _mapPos; // Position keyframes. - TMapScale _mapScale; // Scaling keyframes. - TMapTrigger _mapTrigger; // Trigger keyframes. - int _lastTriggerState = 0; - Flags _flags = Flags::none; - - template - float FindControlPoints(const TMap& m, int frames[4], T keys[4], float time) const - { - frames[0] = frames[1] = frames[2] = frames[3] = -1; - if (m.empty()) // No frames at all, so return null. - return 0; - time = Math::Max(0.f, time); // Negative time is not allowed. - float alpha; - const int frame = static_cast(_pMotion->GetFps() * time); // Frame is before or at 'time'. - typename TMap::const_iterator it = m.upper_bound(frame); // Find frame after 'time'. - if (it != m.cend()) // There are frames greater (after 'time'): - { - if (it != m.cbegin()) // And there are less than (before 'time'), full interpolation: - { - typename TMap::const_iterator itPrev = it; - itPrev--; - frames[1] = itPrev->first; - keys[1] = itPrev->second; - if (itPrev != m.cbegin()) - { - itPrev--; - frames[0] = itPrev->first; - keys[0] = itPrev->second; - } - frames[2] = it->first; - keys[2] = it->second; - it++; - if (it != m.cend()) - { - frames[3] = it->first; - keys[3] = it->second; - } - alpha = (time - (frames[1] * _pMotion->GetFpsInv())) / ((frames[2] - frames[1]) * _pMotion->GetFpsInv()); - } - else // But there are no less than: - { - frames[2] = it->first; - keys[2] = it->second; - it++; - if (it != m.cend()) - { - frames[3] = it->first; - keys[3] = it->second; - } - alpha = time / (frames[2] * _pMotion->GetFpsInv()); - } - } - else // There are no frames greater, but there are less than: - { - it--; - frames[1] = it->first; - keys[1] = it->second; - if (it != m.cbegin()) - { - it--; - frames[0] = it->first; - keys[0] = it->second; - } - alpha = 0; - } - return alpha; - } - - template - static bool SpaceTimeSyncTemplate(TMap& m, int fromFrame, int toFrame) - { - const auto itFrom = m.find(fromFrame); - const auto itTo = m.find(toFrame); - if (m.end() == itFrom || m.end() == itTo) // Endpoints must exist. - return false; - - const int totalFrames = toFrame - fromFrame; - - auto it = itFrom; - Vector vSegments; - vSegments.reserve(8); - float totalDist = 0; - while (it != itTo) - { - const auto& posA = it->second; - it++; - const auto& posB = it->second; - const float d = VMath::dist(Point3(posA), Point3(posB)); - vSegments.push_back(d); - totalDist += d; - } - if (totalDist < 1e-4f) // Distance is too small. - return false; - const float invTotalDist = 1.f / totalDist; - - TMap tempMap; - it = itFrom; - it++; - while (it != itTo) // Copy all keys in-between, delete original keys. - { - tempMap[it->first] = std::move(it->second); - it = m.erase(it); - } - - it = tempMap.begin(); - float distAcc = 0; - int i = 0; - while (it != tempMap.end()) - { - distAcc += vSegments[i++]; - int syncedFrame = fromFrame + static_cast(totalFrames * (distAcc * invTotalDist) + 0.5f); - while (m.end() != m.find(syncedFrame)) // Frame already occupied? - syncedFrame++; - m[syncedFrame] = it->second; - it++; - } - - return true; - } - - public: - Bone(Motion* pMotion = nullptr); - ~Bone(); - - Str GetName() const { return _C(_name); } - void Rename(CSZ name) { _name = name; } - - int GetLastTriggerState() const { return _lastTriggerState; } - void SetLastTriggerState(int state) { _lastTriggerState = state; } - - Flags GetFlags() const { return _flags; } - void SetFlags(Flags flags) { _flags = flags; } - - void DeleteAll(); - - // Insert: - void InsertKeyframeRotation(int frame, RcQuat q); - void InsertKeyframeRotation(int frame, RcVector3 euler); - void InsertKeyframePosition(int frame, RcVector3 pos); - void InsertKeyframeScale(int frame, RcVector3 scale); - void InsertKeyframeTrigger(int frame, int state); - - // Delete: - void DeleteKeyframeRotation(int frame); - void DeleteKeyframePosition(int frame); - void DeleteKeyframeScale(int frame); - void DeleteKeyframeTrigger(int frame); - - // Find: - bool FindKeyframeRotation(int frame, RVector3 euler, RQuat q) const; - bool FindKeyframePosition(int frame, RVector3 pos) const; - bool FindKeyframeScale(int frame, RVector3 scale) const; - bool FindKeyframeTrigger(int frame, int& state) const; - - // Compute: - void ComputeRotationAt(float time, RVector3 euler, RQuat q) const; - void ComputePositionAt(float time, RVector3 pos) const; - void ComputeScaleAt(float time, RVector3 scale) const; - void ComputeTriggerAt(float time, int& state) const; - void ComputeMatrixAt(float time, RTransform3 mat); - - void MoveKeyframe(int direction, Channel channel, int frame); - - int GetRotationKeyCount() const { return Utils::Cast32(_mapRot.size()); } - int GetPositionKeyCount() const { return Utils::Cast32(_mapPos.size()); } - int GetScaleKeyCount() const { return Utils::Cast32(_mapScale.size()); } - int GetTriggerKeyCount() const { return Utils::Cast32(_mapTrigger.size()); } - - VERUS_P(void Serialize(IO::RStream stream, UINT16 version)); - VERUS_P(void Deserialize(IO::RStream stream, UINT16 version)); - - void DeleteRedundantKeyframes(float boneAccLength); - void DeleteOddKeyframes(); - void InsertLoopKeyframes(); - void Cut(int frame, bool before); - void Fix(bool speedLimit); - - void ApplyScaleBias(RcVector3 scale, RcVector3 bias); - - void Scatter(int srcFrom, int srcTo, int dMin, int dMax); - - bool SpaceTimeSync(Channel channel, int fromFrame, int toFrame); - - int GetLastKeyframe() const; + rotation, + position, + scale, + trigger + }; + + enum class Flags : UINT32 + { + none = 0, + slerpRot = (1 << 0), + splinePos = (1 << 1), + splineScale = (1 << 2) }; - VERUS_TYPEDEFS(Bone); private: - static const int s_xanVersion = 0x0102; - static const int s_maxFps = 10000; - static const int s_maxBones = 10000; - static const int s_maxFrames = 32 * 1024 * 1024; + friend class Motion; - typedef Map TMapBones; + static const float s_magicValueForCircle; - TMapBones _mapBones; - Motion* _pBlendMotion = nullptr; - int _frameCount = 60; - int _fps = 12; - float _fpsInv = 1 / 12.f; - float _blendAlpha = 0; - float _playbackSpeed = 1; - float _playbackSpeedInv = 1; - bool _reversed = false; - - public: - Motion(); - ~Motion(); - - void Init(); - void Done(); - - int GetFps() const { return _fps; } - float GetFpsInv() const { return _fpsInv; } - void SetFps(int fps) { _fps = fps; _fpsInv = 1.f / _fps; } - - int GetFrameCount() const { return _frameCount; } - void SetFrameCount(int count) { _frameCount = count; } - - int GetBoneCount() const { return Utils::Cast32(_mapBones.size()); } - - float GetDuration() const { return GetNativeDuration() * _playbackSpeedInv; } - float GetNativeDuration() const { return _frameCount * _fpsInv; } - - PBone GetBoneByIndex(int index); - int GetBoneIndex(CSZ name) const; - - PBone InsertBone(CSZ name); - void DeleteBone(CSZ name); - void DeleteAllBones(); - PBone FindBone(CSZ name); - - template - void ForEachBone(const T& fn) + class Rotation { - for (auto& kv : _mapBones) + public: + Quat _q; + + Rotation(); + Rotation(RcQuat q); + Rotation(RcVector3 euler); + }; + VERUS_TYPEDEFS(Rotation); + + typedef Map TMapRot; + typedef Map TMapPos; + typedef Map TMapScale; + typedef Map TMapTrigger; + + String _name; + Motion* _pMotion = nullptr; + TMapRot _mapRot; // Rotation keyframes. + TMapPos _mapPos; // Position keyframes. + TMapScale _mapScale; // Scaling keyframes. + TMapTrigger _mapTrigger; // Trigger keyframes. + int _lastTriggerState = 0; + Flags _flags = Flags::none; + + template + float FindControlPoints(const TMap& m, int frames[4], T keys[4], float time) const + { + frames[0] = frames[1] = frames[2] = frames[3] = -1; + if (m.empty()) // No frames at all, so return null. + return 0; + time = Math::Max(0.f, time); // Negative time is not allowed. + float alpha; + const int frame = static_cast(_pMotion->GetFps() * time); // Frame is before or at 'time'. + typename TMap::const_iterator it = m.upper_bound(frame); // Find frame after 'time'. + if (it != m.cend()) // There are frames greater (after 'time'): { - if (Continue::no == fn(kv.second)) - break; + if (it != m.cbegin()) // And there are less than (before 'time'), full interpolation: + { + typename TMap::const_iterator itPrev = it; + itPrev--; + frames[1] = itPrev->first; + keys[1] = itPrev->second; + if (itPrev != m.cbegin()) + { + itPrev--; + frames[0] = itPrev->first; + keys[0] = itPrev->second; + } + frames[2] = it->first; + keys[2] = it->second; + it++; + if (it != m.cend()) + { + frames[3] = it->first; + keys[3] = it->second; + } + alpha = (time - (frames[1] * _pMotion->GetFpsInv())) / ((frames[2] - frames[1]) * _pMotion->GetFpsInv()); + } + else // But there are no less than: + { + frames[2] = it->first; + keys[2] = it->second; + it++; + if (it != m.cend()) + { + frames[3] = it->first; + keys[3] = it->second; + } + alpha = time / (frames[2] * _pMotion->GetFpsInv()); + } } + else // There are no frames greater, but there are less than: + { + it--; + frames[1] = it->first; + keys[1] = it->second; + if (it != m.cbegin()) + { + it--; + frames[0] = it->first; + keys[0] = it->second; + } + alpha = 0; + } + return alpha; } - void Serialize(IO::RStream stream); - void Deserialize(IO::RStream stream); + template + static bool SpaceTimeSyncTemplate(TMap& m, int fromFrame, int toFrame) + { + const auto itFrom = m.find(fromFrame); + const auto itTo = m.find(toFrame); + if (m.end() == itFrom || m.end() == itTo) // Endpoints must exist. + return false; - void BakeMotionAt(float time, Motion& dest) const; - void BindBlendMotion(Motion* p, float alpha); - Motion* GetBlendMotion() const { return _pBlendMotion; } - float GetBlendAlpha() const { return _blendAlpha; } + const int totalFrames = toFrame - fromFrame; - void DeleteRedundantKeyframes(Map& mapBoneAccLengths); + auto it = itFrom; + Vector vSegments; + vSegments.reserve(8); + float totalDist = 0; + while (it != itTo) + { + const auto& posA = it->second; + it++; + const auto& posB = it->second; + const float d = VMath::dist(Point3(posA), Point3(posB)); + vSegments.push_back(d); + totalDist += d; + } + if (totalDist < 1e-4f) // Distance is too small. + return false; + const float invTotalDist = 1.f / totalDist; + + TMap tempMap; + it = itFrom; + it++; + while (it != itTo) // Copy all keys in-between, delete original keys. + { + tempMap[it->first] = std::move(it->second); + it = m.erase(it); + } + + it = tempMap.begin(); + float distAcc = 0; + int i = 0; + while (it != tempMap.end()) + { + distAcc += vSegments[i++]; + int syncedFrame = fromFrame + static_cast(totalFrames * (distAcc * invTotalDist) + 0.5f); + while (m.end() != m.find(syncedFrame)) // Frame already occupied? + syncedFrame++; + m[syncedFrame] = it->second; + it++; + } + + return true; + } + + public: + Bone(Motion* pMotion = nullptr); + ~Bone(); + + Str GetName() const { return _C(_name); } + void Rename(CSZ name) { _name = name; } + + int GetLastTriggerState() const { return _lastTriggerState; } + void SetLastTriggerState(int state) { _lastTriggerState = state; } + + Flags GetFlags() const { return _flags; } + void SetFlags(Flags flags) { _flags = flags; } + + void DeleteAll(); + + // Insert: + void InsertKeyframeRotation(int frame, RcQuat q); + void InsertKeyframeRotation(int frame, RcVector3 euler); + void InsertKeyframePosition(int frame, RcVector3 pos); + void InsertKeyframeScale(int frame, RcVector3 scale); + void InsertKeyframeTrigger(int frame, int state); + + // Delete: + void DeleteKeyframeRotation(int frame); + void DeleteKeyframePosition(int frame); + void DeleteKeyframeScale(int frame); + void DeleteKeyframeTrigger(int frame); + + // Find: + bool FindKeyframeRotation(int frame, RVector3 euler, RQuat q) const; + bool FindKeyframePosition(int frame, RVector3 pos) const; + bool FindKeyframeScale(int frame, RVector3 scale) const; + bool FindKeyframeTrigger(int frame, int& state) const; + + // Compute: + void ComputeRotationAt(float time, RVector3 euler, RQuat q) const; + void ComputePositionAt(float time, RVector3 pos) const; + void ComputeScaleAt(float time, RVector3 scale) const; + void ComputeTriggerAt(float time, int& state) const; + void ComputeMatrixAt(float time, RTransform3 mat); + + void MoveKeyframe(int direction, Channel channel, int frame); + + int GetRotationKeyCount() const { return Utils::Cast32(_mapRot.size()); } + int GetPositionKeyCount() const { return Utils::Cast32(_mapPos.size()); } + int GetScaleKeyCount() const { return Utils::Cast32(_mapScale.size()); } + int GetTriggerKeyCount() const { return Utils::Cast32(_mapTrigger.size()); } + + VERUS_P(void Serialize(IO::RStream stream, UINT16 version)); + VERUS_P(void Deserialize(IO::RStream stream, UINT16 version)); + + void DeleteRedundantKeyframes(float boneAccLength); void DeleteOddKeyframes(); void InsertLoopKeyframes(); - void Cut(int frame, bool before = true); + void Cut(int frame, bool before); void Fix(bool speedLimit); - // Triggers: - void ProcessTriggers(float time, PMotionDelegate p, int* pUserTriggerStates = nullptr); - void ResetTriggers(int* pUserTriggerStates = nullptr); - void SkipTriggers(float time, int* pUserTriggerStates = nullptr); + void ApplyScaleBias(RcVector3 scale, RcVector3 bias); - void ApplyScaleBias(CSZ name, RcVector3 scale, RcVector3 bias); + void Scatter(int srcFrom, int srcTo, int dMin, int dMax); - float GetPlaybackSpeed() const { return _playbackSpeed; } - float GetPlaybackSpeedInv() const { return _playbackSpeedInv; } - void SetPlaybackSpeed(float x); - void ComputePlaybackSpeed(float duration); - bool IsReversed() const { return _reversed; } - - void Exec(CSZ code, PBone pBone = nullptr, Bone::Channel channel = Bone::Channel::rotation); + bool SpaceTimeSync(Channel channel, int fromFrame, int toFrame); int GetLastKeyframe() const; - - static bool ExtractNestBone(CSZ name, SZ nestBone); }; - VERUS_TYPEDEFS(Motion); - } + VERUS_TYPEDEFS(Bone); + + private: + static const int s_xanVersion = 0x0102; + static const int s_maxFps = 10000; + static const int s_maxBones = 10000; + static const int s_maxFrames = 32 * 1024 * 1024; + + typedef Map TMapBones; + + TMapBones _mapBones; + Motion* _pBlendMotion = nullptr; + int _frameCount = 60; + int _fps = 12; + float _fpsInv = 1 / 12.f; + float _blendAlpha = 0; + float _playbackSpeed = 1; + float _playbackSpeedInv = 1; + bool _reversed = false; + + public: + Motion(); + ~Motion(); + + void Init(); + void Done(); + + int GetFps() const { return _fps; } + float GetFpsInv() const { return _fpsInv; } + void SetFps(int fps) { _fps = fps; _fpsInv = 1.f / _fps; } + + int GetFrameCount() const { return _frameCount; } + void SetFrameCount(int count) { _frameCount = count; } + + int GetBoneCount() const { return Utils::Cast32(_mapBones.size()); } + + float GetDuration() const { return GetNativeDuration() * _playbackSpeedInv; } + float GetNativeDuration() const { return _frameCount * _fpsInv; } + + PBone GetBoneByIndex(int index); + int GetBoneIndex(CSZ name) const; + + PBone InsertBone(CSZ name); + void DeleteBone(CSZ name); + void DeleteAllBones(); + PBone FindBone(CSZ name); + + template + void ForEachBone(const T& fn) + { + for (auto& [key, value] : _mapBones) + { + if (Continue::no == fn(value)) + break; + } + } + + void Serialize(IO::RStream stream); + void Deserialize(IO::RStream stream); + + void BakeMotionAt(float time, Motion& dest) const; + void BindBlendMotion(Motion* p, float alpha); + Motion* GetBlendMotion() const { return _pBlendMotion; } + float GetBlendAlpha() const { return _blendAlpha; } + + void DeleteRedundantKeyframes(Map& mapBoneAccLengths); + void DeleteOddKeyframes(); + void InsertLoopKeyframes(); + void Cut(int frame, bool before = true); + void Fix(bool speedLimit); + + // Triggers: + void ProcessTriggers(float time, PMotionDelegate p, int* pUserTriggerStates = nullptr); + void ResetTriggers(int* pUserTriggerStates = nullptr); + void SkipTriggers(float time, int* pUserTriggerStates = nullptr); + + void ApplyScaleBias(CSZ name, RcVector3 scale, RcVector3 bias); + + float GetPlaybackSpeed() const { return _playbackSpeed; } + float GetPlaybackSpeedInv() const { return _playbackSpeedInv; } + void SetPlaybackSpeed(float x); + void ComputePlaybackSpeed(float duration); + bool IsReversed() const { return _reversed; } + + void Exec(CSZ code, PBone pBone = nullptr, Bone::Channel channel = Bone::Channel::rotation); + + int GetLastKeyframe() const; + + static bool ExtractNestBone(CSZ name, SZ nestBone); + }; + VERUS_TYPEDEFS(Motion); } diff --git a/Verus/src/Anim/Orbit.h b/Verus/src/Anim/Orbit.h index 5b5a0de..59d030c 100644 --- a/Verus/src/Anim/Orbit.h +++ b/Verus/src/Anim/Orbit.h @@ -1,47 +1,44 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Anim { - namespace Anim + class Orbit { - class Orbit - { - Matrix3 _matrix; - Elastic _pitch; - Elastic _yaw; - float _basePitch = 0; - float _baseYaw = 0; - float _speed = 1; - float _offsetStrength = 0; - float _maxPitch = 0.45f; - bool _locked = false; + Matrix3 _matrix; + Elastic _pitch; + Elastic _yaw; + float _basePitch = 0; + float _baseYaw = 0; + float _speed = 1; + float _offsetStrength = 0; + float _maxPitch = 0.45f; + bool _locked = false; - public: - Orbit(); - ~Orbit(); + public: + Orbit(); + ~Orbit(); - void Update(bool smoothRestore = true); + void Update(bool smoothRestore = true); - void Lock(); - void Unlock(); - bool IsLocked() const { return _locked; } + void Lock(); + void Unlock(); + bool IsLocked() const { return _locked; } - void AddPitch(float a); - void AddYaw(float a); - void AddPitchFree(float a); - void AddYawFree(float a); + void AddPitch(float a); + void AddYaw(float a); + void AddPitchFree(float a); + void AddYawFree(float a); - float GetPitch() const { return _pitch; } - float GetYaw() const { return _yaw; } + float GetPitch() const { return _pitch; } + float GetYaw() const { return _yaw; } - RcMatrix3 GetMatrix() const { return _matrix; } + RcMatrix3 GetMatrix() const { return _matrix; } - float GetOffsetStrength() const { return _offsetStrength; } + float GetOffsetStrength() const { return _offsetStrength; } - void SetSpeed(float x) { _speed = x; } - void SetMaxPitch(float a) { _maxPitch = a; } - }; - VERUS_TYPEDEFS(Orbit); - } + void SetSpeed(float x) { _speed = x; } + void SetMaxPitch(float a) { _maxPitch = a; } + }; + VERUS_TYPEDEFS(Orbit); } diff --git a/Verus/src/Anim/Shaker.h b/Verus/src/Anim/Shaker.h index 2b97d06..24dc4fd 100644 --- a/Verus/src/Anim/Shaker.h +++ b/Verus/src/Anim/Shaker.h @@ -1,49 +1,46 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Anim { - namespace Anim + // Shaker can load standard wav file, 8-bit mono, and use it as a function of time. + // Works well for camera's shaking effects. + class Shaker { - // Shaker can load standard wav file, 8-bit mono, and use it as a function of time. - // Works well for camera's shaking effects. - class Shaker - { - String _url; - Vector _vData; - float _speed = 0; - float _offset = 0; - float _value = 0; - float _scale = 1; - float _bias = 0; - bool _looping = false; + String _url; + Vector _vData; + float _speed = 0; + float _offset = 0; + float _value = 0; + float _scale = 1; + float _bias = 0; + bool _looping = false; - public: - Shaker(float speed = 400, bool looping = true) : _speed(speed), _looping(looping) {} + public: + Shaker(float speed = 400, bool looping = true) : _speed(speed), _looping(looping) {} - bool IsLoaded() const { return !_vData.empty(); } - void Load(CSZ url); - Str GetURL() const { return _C(_url); } + bool IsLoaded() const { return !_vData.empty(); } + void Load(CSZ url); + Str GetURL() const { return _C(_url); } - void Update(); + void Update(); - void Reset() { _offset = 0; } - void Randomize(); - // Returns the current value in the range [-1 to 1]. - float Get(); + void Reset() { _offset = 0; } + void Randomize(); + // Returns the current value in the range [-1 to 1]. + float Get(); - float GetSpeed() const { return _speed; } - void SetSpeed(float speed) { _speed = speed; } + float GetSpeed() const { return _speed; } + void SetSpeed(float speed) { _speed = speed; } - float GetScale() const { return _scale; } - void SetScale(float scale) { _scale = scale; } + float GetScale() const { return _scale; } + void SetScale(float scale) { _scale = scale; } - float GetBias() const { return _bias; } - void SetBias(float bias) { _bias = bias; } + float GetBias() const { return _bias; } + void SetBias(float bias) { _bias = bias; } - bool IsLooping() const { return _looping; } - void SetLooping(float looping) { _looping = looping; } - }; - VERUS_TYPEDEFS(Shaker); - } + bool IsLooping() const { return _looping; } + void SetLooping(float looping) { _looping = looping; } + }; + VERUS_TYPEDEFS(Shaker); } diff --git a/Verus/src/Anim/Skeleton.cpp b/Verus/src/Anim/Skeleton.cpp index d6fee68..7118184 100644 --- a/Verus/src/Anim/Skeleton.cpp +++ b/Verus/src/Anim/Skeleton.cpp @@ -16,8 +16,8 @@ Skeleton::~Skeleton() void Skeleton::operator=(RcSkeleton that) { Init(); - for (const auto& kv : that._mapBones) - _mapBones[kv.first] = kv.second; + for (const auto& [key, value] : that._mapBones) + _mapBones[key] = value; _primaryBoneCount = that._primaryBoneCount; } @@ -36,9 +36,9 @@ void Skeleton::Draw(bool bindPose, PcTransform3 pMat, int selected) { VERUS_QREF_DD; dd.Begin(CGI::DebugDraw::Type::lines, pMat, false); - for (const auto& kv : _mapBones) + for (const auto& [key, value] : _mapBones) { - PcBone pBone = &kv.second; + PcBone pBone = &value; PcBone pParent = FindBone(_C(pBone->_parentName)); if (pParent) { @@ -58,9 +58,9 @@ void Skeleton::Draw(bool bindPose, PcTransform3 pMat, int selected) } } } - for (const auto& kv : _mapBones) + for (const auto& [key, value] : _mapBones) { - PcBone pBone = &kv.second; + PcBone pBone = &value; const Transform3 mat = bindPose ? pBone->_matFromBoneSpace : pBone->_matFinal * pBone->_matFromBoneSpace; const float scale = 0.04f; @@ -122,10 +122,10 @@ Skeleton::PcBone Skeleton::FindBone(CSZ name) const Skeleton::PBone Skeleton::FindBoneByIndex(int index) { - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - if (kv.second._shaderIndex == index) - return &kv.second; + if (value._shaderIndex == index) + return &value; } return nullptr; } @@ -134,9 +134,9 @@ void Skeleton::ApplyMotion(RMotion motion, float time, int layeredMotionCount, P { if (_ragdollMode) { - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; if (bone._pRigidBody) { btTransform btr; @@ -176,9 +176,9 @@ void Skeleton::ApplyMotion(RMotion motion, float time, int layeredMotionCount, P _pLayeredMotions = pLayeredMotions; ResetBones(); - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; if (!bone._ready) { _pCurrentBone = &bone; @@ -198,9 +198,9 @@ void Skeleton::ApplyMotion(RMotion motion, float time, int layeredMotionCount, P void Skeleton::UpdateUniformBufferArray(mataff* p) const { - for (const auto& kv : _mapBones) + for (const auto& [key, value] : _mapBones) { - RcBone bone = kv.second; + RcBone bone = value; if (bone._shaderIndex >= 0 && bone._shaderIndex < VERUS_MAX_BONES) p[bone._shaderIndex] = bone._matFinal.UniformBufferFormat(); } @@ -208,17 +208,17 @@ void Skeleton::UpdateUniformBufferArray(mataff* p) const void Skeleton::ResetFinalPose() { - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - kv.second._matFinal = Transform3::identity(); - kv.second._matFinalInv = Transform3::identity(); + value._matFinal = Transform3::identity(); + value._matFinalInv = Transform3::identity(); } } void Skeleton::ResetBones() { - for (auto& kv : _mapBones) - kv.second._ready = false; + for (auto& [key, value] : _mapBones) + value._ready = false; } void Skeleton::RecursiveBoneUpdate() @@ -300,8 +300,8 @@ void Skeleton::RecursiveBoneUpdate() void Skeleton::InsertBonesIntoMotion(RMotion motion) const { - for (const auto& kv : _mapBones) - motion.InsertBone(_C(kv.first)); + for (const auto& [key, value] : _mapBones) + motion.InsertBone(_C(key)); } void Skeleton::DeleteOutsiders(RMotion motion) const @@ -332,9 +332,9 @@ void Skeleton::AdjustPrimaryBones(const Vector& vPrimaryBones) if (inverse) std::swap(addPri, addSec); - for (const auto& kv : _mapBones) + for (const auto& [key, value] : _mapBones) { - RcBone bone = kv.second; + RcBone bone = value; if (vPrimaryBones.end() != std::find(vPrimaryBones.begin(), vPrimaryBones.end(), bone._name)) mapSort[bone._shaderIndex + addPri] = bone._name; else @@ -343,11 +343,11 @@ void Skeleton::AdjustPrimaryBones(const Vector& vPrimaryBones) _primaryBoneCount = 0; - for (const auto& kv : mapSort) + for (const auto& [key, value] : mapSort) { - if (kv.first < secondaryOffset) // Primary bone: + if (key < secondaryOffset) // Primary bone: { - PBone pBone = FindBone(_C(kv.second)); + PBone pBone = FindBone(_C(value)); const int newIndex = Utils::Cast32(_mapPrimary.size()); _mapPrimary[pBone->_shaderIndex] = newIndex; pBone->_shaderIndex = newIndex; @@ -355,7 +355,7 @@ void Skeleton::AdjustPrimaryBones(const Vector& vPrimaryBones) } else // Secondary bone: { - PBone pBone = FindBone(_C(kv.second)); + PBone pBone = FindBone(_C(value)); PcBone pParent = FindBone(_C(pBone->_parentName)); bool isPrimary = false; while (!isPrimary) @@ -400,9 +400,9 @@ void Skeleton::LoadRigInfo(CSZ url) void Skeleton::LoadRigInfoFromPtr(SZ p) { - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; bone._rigRot = Vector3(0); bone._cRot = Vector3(0); bone._cLimits = Vector3(0); @@ -419,9 +419,9 @@ void Skeleton::LoadRigInfoFromPtr(SZ p) float massCheck = 0; if (p) { - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; bone._rigBone = false; } @@ -498,12 +498,12 @@ void Skeleton::BeginRagdoll(RcTransform3 matW, RcVector3 impulse, CSZ bone) const float sleepL = 1.6f; const float sleepA = 2.5f; - for (auto& kv : _mapBones) - kv.second._ready = true; + for (auto& [key, value] : _mapBones) + value._ready = true; - for (const auto& kv : _mapBones) + for (const auto& [key, value] : _mapBones) { - PcBone pBone = &kv.second; + PcBone pBone = &value; PBone pParent = FindBone(_C(pBone->_parentName)); if (pParent && pParent->_rigBone && !pParent->_pShape) // Create a shape for parent bone: @@ -574,9 +574,9 @@ void Skeleton::BeginRagdoll(RcTransform3 matW, RcVector3 impulse, CSZ bone) const Transform3 matInitC = Transform3::rotationZYX(Vector3(-VERUS_PI / 2, 0, -VERUS_PI / 2)); // Create leaf actors and joints: - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - PBone pBone = &kv.second; + PBone pBone = &value; PBone pParent = pBone; do { @@ -667,9 +667,9 @@ void Skeleton::EndRagdoll() { VERUS_QREF_BULLET; - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; if (bone._pConstraint) { bullet.GetWorld()->removeConstraint(bone._pConstraint); @@ -678,9 +678,9 @@ void Skeleton::EndRagdoll() } } - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; if (bone._pRigidBody) { bullet.GetWorld()->removeRigidBody(bone._pRigidBody); @@ -700,9 +700,9 @@ void Skeleton::EndRagdoll() void Skeleton::BakeMotion(RMotion motion, int frame, bool kinect) { - for (const auto& kv : _mapBones) + for (const auto& [key, value] : _mapBones) { - RcBone bone = kv.second; + RcBone bone = value; if (kinect && !IsKinectBone(_C(bone._name))) continue; PcBone pParent = FindBone(_C(bone._parentName)); @@ -792,9 +792,9 @@ void Skeleton::AdaptBindPoseOf(RcSkeleton that) // TODO: improve. const Point3 origin(0); - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone boneDst = kv.second; + RBone boneDst = value; PBone pParentDst = FindBone(_C(boneDst._parentName)); PcBone pBoneSrc = that.FindBone(_C(boneDst._name)); PcBone pParentSrc = pBoneSrc ? that.FindBone(_C(pBoneSrc->_parentName)) : nullptr; @@ -850,10 +850,10 @@ void Skeleton::SimpleIK(CSZ boneDriven, CSZ boneDriver, RcVector3 dirDriverSpace void Skeleton::ProcessKinectData(const BYTE* p, RMotion motion, int frame) { - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - kv.second._matFinal = Transform3::identity(); - kv.second._matExternal = Transform3::identity(); + value._matFinal = Transform3::identity(); + value._matExternal = Transform3::identity(); } UINT64 timestamp; @@ -925,9 +925,9 @@ void Skeleton::ProcessKinectData(const BYTE* p, RMotion motion, int frame) shTwist *= 1 - abs(shAxis.getY()); } - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; if (!IsKinectBone(_C(bone._name))) continue; #if 0 @@ -970,9 +970,9 @@ void Skeleton::ProcessKinectData(const BYTE* p, RMotion motion, int frame) VERUS_FOR(i, 4) { - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; if (IsKinectBone(_C(bone._name)) && !IsKinectLeafBone(_C(bone._name))) continue; PBone pParent = FindBone(_C(bone._parentName)); @@ -985,10 +985,10 @@ void Skeleton::ProcessKinectData(const BYTE* p, RMotion motion, int frame) BakeMotion(motion, frame, true); - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - kv.second._matFinal = Transform3::identity(); - kv.second._matExternal = Transform3::identity(); + value._matFinal = Transform3::identity(); + value._matExternal = Transform3::identity(); } } @@ -1033,9 +1033,9 @@ void Skeleton::LoadKinectBindPose(CSZ xml) mapData[pElem->Attribute("n")] = pos; } - for (const auto& kv : _mapBones) + for (const auto& [key, value] : _mapBones) { - RBone bone = kv.second; + RBone bone = value; if (!IsKinectBone(_C(bone._name))) continue; PBone pParent = FindBone(_C(bone._parentName)); @@ -1229,9 +1229,9 @@ Vector3 Skeleton::GetHighestSpeed(RMotion motion, CSZ name, RcVector3 scale, boo void Skeleton::ComputeBoneLengths(Map& m, bool accumulated) { - for (auto& kv : _mapBones) + for (auto& [key, value] : _mapBones) { - RcBone bone = kv.second; + RcBone bone = value; PcBone pParentBone = FindBone(_C(bone._parentName)); float len = 0; if (pParentBone) @@ -1261,7 +1261,7 @@ void Skeleton::ComputeBoneLengths(Map& m, bool accumulated) } if (accumulated) // Add leaf bone lengths? { - for (auto& kv : m) - kv.second += 0.02f; + for (auto& [key, value] : m) + value += 0.02f; } } diff --git a/Verus/src/Anim/Skeleton.h b/Verus/src/Anim/Skeleton.h index e1d6b11..d73f687 100644 --- a/Verus/src/Anim/Skeleton.h +++ b/Verus/src/Anim/Skeleton.h @@ -1,163 +1,160 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Anim { - namespace Anim + // Standard skeleton, which can be animated using motion object. + // X3D format can support up to 256 bones, but the hardware has certain limitations. + // With Shader Model 2.0 the shader can hold about 32 bone matrices. + // Other bones must be remapped using Primary Bones concept. + // Layered motions add the ability to mix multiple motions, just like images are mixed with alpha channel. + // Layered motion affects it's root bone and all descendants of that bone. + // A ragdoll can be created automatically or configured using XML .rig file. + // Ragdoll's simulation can start from any motion frame and any simulated pose can be baked back into motion object, + // allowing smooth transition to ragdoll simulation and back to motion. + class Skeleton : public Object { - // Standard skeleton, which can be animated using motion object. - // X3D format can support up to 256 bones, but the hardware has certain limitations. - // With Shader Model 2.0 the shader can hold about 32 bone matrices. - // Other bones must be remapped using Primary Bones concept. - // Layered motions add the ability to mix multiple motions, just like images are mixed with alpha channel. - // Layered motion affects it's root bone and all descendants of that bone. - // A ragdoll can be created automatically or configured using XML .rig file. - // Ragdoll's simulation can start from any motion frame and any simulated pose can be baked back into motion object, - // allowing smooth transition to ragdoll simulation and back to motion. - class Skeleton : public Object + public: + struct LayeredMotion { - public: - struct LayeredMotion - { - PMotion _pMotion = nullptr; - CSZ _rootBone = nullptr; - float _alpha = 0; - float _time = 0; - }; - VERUS_TYPEDEFS(LayeredMotion); - - struct Bone : AllocatorAware - { - Transform3 _matToBoneSpace = Transform3::identity(); - Transform3 _matFromBoneSpace = Transform3::identity(); - Transform3 _matFinal = Transform3::identity(); - Transform3 _matFinalInv = Transform3::identity(); - Transform3 _matExternal = Transform3::identity(); - Transform3 _matAdapt = Transform3::identity(); - Transform3 _matToActorSpace = Transform3::identity(); - Vector3 _rigRot = Vector3(0); // Rotation angles of ragdoll's rigid component. - Vector3 _cRot = Vector3(0); // Constraint's rotation angles. - Vector3 _cLimits = Vector3(0); // Constraint's limits. - Vector3 _boxSize = Vector3(0); // For a box shape. - String _name; - String _parentName; - btCollisionShape* _pShape = nullptr; - btRigidBody* _pRigidBody = nullptr; - btTypedConstraint* _pConstraint = nullptr; - float _width = 0; - float _length = 0; - float _mass = 0; - float _friction = 0; - int _shaderIndex = 0; // Index of a matrix in the vertex shader. - bool _ready = false; - bool _rigBone = true; - bool _hinge = false; // btHingeConstraint vs btConeTwistConstraint. - bool _noCollision = false; - }; - VERUS_TYPEDEFS(Bone); - - private: - typedef Map TMapBones; - typedef Map TMapPrimary; - - Transform3 _matParents = Transform3::identity(); - Transform3 _matRagdollToWorld = Transform3::identity(); - Transform3 _matRagdollToWorldInv = Transform3::identity(); - TMapBones _mapBones; - TMapPrimary _mapPrimary; - PBone _pCurrentBone = nullptr; - PMotion _pCurrentMotion = nullptr; - PLayeredMotion _pLayeredMotions = nullptr; - float _currentTime = 0; - float _mass = 0; - int _primaryBoneCount = 0; - int _layeredMotionCount = 0; - bool _ragdollMode = false; - - public: - Skeleton(); - ~Skeleton(); - - void operator=(const Skeleton& that); - - void Init(); - void Done(); - - void Draw(bool bindPose = true, PcTransform3 pMat = nullptr, int selected = -1); - - static CSZ RootName() { return "$ROOT"; } - - PBone InsertBone(RBone bone); - PBone FindBone(CSZ name); - PcBone FindBone(CSZ name) const; - // Uses shader's array index to find a bone. - PBone FindBoneByIndex(int index); - - // Sets the current pose using motion object (Motion). - void ApplyMotion(RMotion motion, float time, - int layeredMotionCount = 0, PLayeredMotion pLayeredMotions = nullptr); - - // Fills the array of matrices that will be used by a shader. - void UpdateUniformBufferArray(mataff* p) const; - - void ResetFinalPose(); - - VERUS_P(void ResetBones()); - VERUS_P(void RecursiveBoneUpdate()); - - int GetBoneCount() const { return _primaryBoneCount ? _primaryBoneCount : Utils::Cast32(_mapBones.size()); } - - template - void ForEachBone(const F& fn) - { - for (auto& kv : _mapBones) - if (Continue::no == fn(kv.second)) - return; - } - template - void ForEachBone(const F& fn) const - { - for (const auto& kv : _mapBones) - if (Continue::no == fn(kv.second)) - return; - } - - // Adds skeleton's bones to motion object (Motion). - void InsertBonesIntoMotion(RMotion motion) const; - // Removes motion's bones, which are not skeleton's bones. - void DeleteOutsiders(RMotion motion) const; - - void AdjustPrimaryBones(const Vector& vPrimaryBones); - int RemapBoneIndex(int index) const; - - bool IsParentOf(CSZ bone, CSZ parent) const; - - void LoadRigInfo(CSZ url); - void LoadRigInfoFromPtr(SZ p); - void BeginRagdoll(RcTransform3 matW, RcVector3 impulse = Vector3(0), CSZ bone = "Spine2"); - void EndRagdoll(); - bool IsRagdollMode() const { return _ragdollMode; } - RcTransform3 GetRagdollToWorldMatrix() { return _matRagdollToWorld; } - - // Saves the current pose into motion object (Motion) at some frame. - void BakeMotion(RMotion motion, int frame = 0, bool kinect = false); - void AdaptBindPoseOf(const Skeleton& that); - void SimpleIK(CSZ boneDriven, CSZ boneDriver, RcVector3 dirDriverSpace, RcVector3 dirDesiredMeshSpace, float limitDot, float alpha); - - void ProcessKinectData(const BYTE* p, RMotion motion, int frame = 0); - void ProcessKinectJoint(const BYTE* p, CSZ name, RcVector3 skeletonPos); - void LoadKinectBindPose(CSZ xml); - static bool IsKinectBone(CSZ name); - static bool IsKinectLeafBone(CSZ name); - - void FixateFeet(RMotion motion); - - // Tries to compute the highest speed at which a bone would move with this motion applied. - // Can be used to sync animation and movement to fix the sliding feet problem. - Vector3 GetHighestSpeed(RMotion motion, CSZ name, RcVector3 scale = Vector3(1, 0, 1), bool positive = false); - - void ComputeBoneLengths(Map& m, bool accumulated = false); + PMotion _pMotion = nullptr; + CSZ _rootBone = nullptr; + float _alpha = 0; + float _time = 0; }; - VERUS_TYPEDEFS(Skeleton); - } + VERUS_TYPEDEFS(LayeredMotion); + + struct Bone : AllocatorAware + { + Transform3 _matToBoneSpace = Transform3::identity(); + Transform3 _matFromBoneSpace = Transform3::identity(); + Transform3 _matFinal = Transform3::identity(); + Transform3 _matFinalInv = Transform3::identity(); + Transform3 _matExternal = Transform3::identity(); + Transform3 _matAdapt = Transform3::identity(); + Transform3 _matToActorSpace = Transform3::identity(); + Vector3 _rigRot = Vector3(0); // Rotation angles of ragdoll's rigid component. + Vector3 _cRot = Vector3(0); // Constraint's rotation angles. + Vector3 _cLimits = Vector3(0); // Constraint's limits. + Vector3 _boxSize = Vector3(0); // For a box shape. + String _name; + String _parentName; + btCollisionShape* _pShape = nullptr; + btRigidBody* _pRigidBody = nullptr; + btTypedConstraint* _pConstraint = nullptr; + float _width = 0; + float _length = 0; + float _mass = 0; + float _friction = 0; + int _shaderIndex = 0; // Index of a matrix in the vertex shader. + bool _ready = false; + bool _rigBone = true; + bool _hinge = false; // btHingeConstraint vs btConeTwistConstraint. + bool _noCollision = false; + }; + VERUS_TYPEDEFS(Bone); + + private: + typedef Map TMapBones; + typedef Map TMapPrimary; + + Transform3 _matParents = Transform3::identity(); + Transform3 _matRagdollToWorld = Transform3::identity(); + Transform3 _matRagdollToWorldInv = Transform3::identity(); + TMapBones _mapBones; + TMapPrimary _mapPrimary; + PBone _pCurrentBone = nullptr; + PMotion _pCurrentMotion = nullptr; + PLayeredMotion _pLayeredMotions = nullptr; + float _currentTime = 0; + float _mass = 0; + int _primaryBoneCount = 0; + int _layeredMotionCount = 0; + bool _ragdollMode = false; + + public: + Skeleton(); + ~Skeleton(); + + void operator=(const Skeleton& that); + + void Init(); + void Done(); + + void Draw(bool bindPose = true, PcTransform3 pMat = nullptr, int selected = -1); + + static CSZ RootName() { return "$ROOT"; } + + PBone InsertBone(RBone bone); + PBone FindBone(CSZ name); + PcBone FindBone(CSZ name) const; + // Uses shader's array index to find a bone. + PBone FindBoneByIndex(int index); + + // Sets the current pose using motion object (Motion). + void ApplyMotion(RMotion motion, float time, + int layeredMotionCount = 0, PLayeredMotion pLayeredMotions = nullptr); + + // Fills the array of matrices that will be used by a shader. + void UpdateUniformBufferArray(mataff* p) const; + + void ResetFinalPose(); + + VERUS_P(void ResetBones()); + VERUS_P(void RecursiveBoneUpdate()); + + int GetBoneCount() const { return _primaryBoneCount ? _primaryBoneCount : Utils::Cast32(_mapBones.size()); } + + template + void ForEachBone(const F& fn) + { + for (auto& [key, value] : _mapBones) + if (Continue::no == fn(value)) + return; + } + template + void ForEachBone(const F& fn) const + { + for (const auto& [key, value] : _mapBones) + if (Continue::no == fn(value)) + return; + } + + // Adds skeleton's bones to motion object (Motion). + void InsertBonesIntoMotion(RMotion motion) const; + // Removes motion's bones, which are not skeleton's bones. + void DeleteOutsiders(RMotion motion) const; + + void AdjustPrimaryBones(const Vector& vPrimaryBones); + int RemapBoneIndex(int index) const; + + bool IsParentOf(CSZ bone, CSZ parent) const; + + void LoadRigInfo(CSZ url); + void LoadRigInfoFromPtr(SZ p); + void BeginRagdoll(RcTransform3 matW, RcVector3 impulse = Vector3(0), CSZ bone = "Spine2"); + void EndRagdoll(); + bool IsRagdollMode() const { return _ragdollMode; } + RcTransform3 GetRagdollToWorldMatrix() { return _matRagdollToWorld; } + + // Saves the current pose into motion object (Motion) at some frame. + void BakeMotion(RMotion motion, int frame = 0, bool kinect = false); + void AdaptBindPoseOf(const Skeleton& that); + void SimpleIK(CSZ boneDriven, CSZ boneDriver, RcVector3 dirDriverSpace, RcVector3 dirDesiredMeshSpace, float limitDot, float alpha); + + void ProcessKinectData(const BYTE* p, RMotion motion, int frame = 0); + void ProcessKinectJoint(const BYTE* p, CSZ name, RcVector3 skeletonPos); + void LoadKinectBindPose(CSZ xml); + static bool IsKinectBone(CSZ name); + static bool IsKinectLeafBone(CSZ name); + + void FixateFeet(RMotion motion); + + // Tries to compute the highest speed at which a bone would move with this motion applied. + // Can be used to sync animation and movement to fix the sliding feet problem. + Vector3 GetHighestSpeed(RMotion motion, CSZ name, RcVector3 scale = Vector3(1, 0, 1), bool positive = false); + + void ComputeBoneLengths(Map& m, bool accumulated = false); + }; + VERUS_TYPEDEFS(Skeleton); } diff --git a/Verus/src/Anim/Warp.h b/Verus/src/Anim/Warp.h index 404a0b2..5daef15 100644 --- a/Verus/src/Anim/Warp.h +++ b/Verus/src/Anim/Warp.h @@ -1,83 +1,80 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Anim { - namespace Anim + // Warp manages sphere-based deformations to create such effects like dangling and speech. + // Any other part of the mesh can also be deformed. + // Warp's zone objects can use motion object or can simulate spring physics, + // for example to simulate female's breast. + // Warp class includes a function to convert special audio files to motion. + // If there is a filename.wav, containing character's speech, some additional files must be created: + // 1. filename_Jaw.wav; effects: Stretch 400, Dynamic 10 Gate, 8000 8-bit. + // 2. filename_O.wav; effects: Low pass 5000Hz, Keep O noise, Dynamic 10 Gate, 8000 8-bit. + // 3. filename_S.wav; effects: Keep S noise, Dynamic 10 Gate, Stretch 400, 8000 8-bit. + // Motion should be applied to the skeleton before it will be used in Update() method. + // Then _skeletonReady can be set to true for the mesh. + class Warp : public Object { - // Warp manages sphere-based deformations to create such effects like dangling and speech. - // Any other part of the mesh can also be deformed. - // Warp's zone objects can use motion object or can simulate spring physics, - // for example to simulate female's breast. - // Warp class includes a function to convert special audio files to motion. - // If there is a filename.wav, containing character's speech, some additional files must be created: - // 1. filename_Jaw.wav; effects: Stretch 400, Dynamic 10 Gate, 8000 8-bit. - // 2. filename_O.wav; effects: Low pass 5000Hz, Keep O noise, Dynamic 10 Gate, 8000 8-bit. - // 3. filename_S.wav; effects: Keep S noise, Dynamic 10 Gate, Stretch 400, 8000 8-bit. - // Motion should be applied to the skeleton before it will be used in Update() method. - // Then _skeletonReady can be set to true for the mesh. - class Warp : public Object + public: + typedef Map TMapOffsets; + class Zone { public: - typedef Map TMapOffsets; - class Zone - { - public: - Point3 _pos = Point3(0); - Point3 _posW = Point3(0); - Vector3 _vel = Vector3(0); - Vector3 _off = Vector3(0); - String _name; - String _bone; - TMapOffsets _mapOffsets; - float _radius = 0; - float _spring = 0; - float _damping = 5; - float _maxOffset = 0; - char _type = 0; - }; - VERUS_TYPEDEFS(Zone); - - private: - Vector _vZones; - String _preview; - float _yMin = FLT_MAX; - float _jawScale = 1; - - public: - Warp(); - ~Warp(); - - void Init(); - void Done(); - - void Update(RSkeleton skeleton); - void DrawLines() const; - void DrawZones() const; - - void Load(CSZ url); - void LoadFromPtr(SZ p); - - void Fill(PVector4 p); - - void ApplyMotion(RMotion motion, float time); - - static void ComputeLipSyncFromAudio(RcBlob blob, RMotion motion, float jawScale = 1); - - float GetJawScale() const { return _jawScale; } - - template - void ForEachZone(const T& fn) - { - for (auto& zone : _vZones) - { - if (Continue::no == fn(zone)) - break; - } - } - - void SetPreview(CSZ preview) { _preview = preview; } + Point3 _pos = Point3(0); + Point3 _posW = Point3(0); + Vector3 _vel = Vector3(0); + Vector3 _off = Vector3(0); + String _name; + String _bone; + TMapOffsets _mapOffsets; + float _radius = 0; + float _spring = 0; + float _damping = 5; + float _maxOffset = 0; + char _type = 0; }; - VERUS_TYPEDEFS(Warp); - } + VERUS_TYPEDEFS(Zone); + + private: + Vector _vZones; + String _preview; + float _yMin = FLT_MAX; + float _jawScale = 1; + + public: + Warp(); + ~Warp(); + + void Init(); + void Done(); + + void Update(RSkeleton skeleton); + void DrawLines() const; + void DrawZones() const; + + void Load(CSZ url); + void LoadFromPtr(SZ p); + + void Fill(PVector4 p); + + void ApplyMotion(RMotion motion, float time); + + static void ComputeLipSyncFromAudio(RcBlob blob, RMotion motion, float jawScale = 1); + + float GetJawScale() const { return _jawScale; } + + template + void ForEachZone(const T& fn) + { + for (auto& zone : _vZones) + { + if (Continue::no == fn(zone)) + break; + } + } + + void SetPreview(CSZ preview) { _preview = preview; } + }; + VERUS_TYPEDEFS(Warp); } diff --git a/Verus/src/App/App.h b/Verus/src/App/App.h index e64ae18..f223101 100644 --- a/Verus/src/App/App.h +++ b/Verus/src/App/App.h @@ -11,10 +11,7 @@ namespace verus void Free_App(); } -namespace verus +namespace verus::App { - namespace App - { - void RunEventLoop(); - } + void RunEventLoop(); } diff --git a/Verus/src/App/Settings.h b/Verus/src/App/Settings.h index 63ba8b6..5b75815 100644 --- a/Verus/src/App/Settings.h +++ b/Verus/src/App/Settings.h @@ -1,192 +1,189 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::App { - namespace App + enum class DisplayMode : int { - enum class DisplayMode : int + exclusiveFullscreen, + windowed, + borderlessWindowed + }; + + class Info + { + public: + CSZ _appName = nullptr; + UINT32 _appVersion = 0; + CSZ _engineName = nullptr; + UINT32 _engineVersion = 0; + }; + VERUS_TYPEDEFS(Info); + + class QualitySettings + { + public: + enum class OverallQuality : int { - exclusiveFullscreen, - windowed, - borderlessWindowed + custom, + low, + medium, + high, + ultra }; - class Info + enum class Quality : int { - public: - CSZ _appName = nullptr; - UINT32 _appVersion = 0; - CSZ _engineName = nullptr; - UINT32 _engineVersion = 0; + low, + medium, + high, + ultra }; - VERUS_TYPEDEFS(Info); - class QualitySettings + enum class WaterQuality : int { - public: - enum class OverallQuality : int - { - custom, - low, - medium, - high, - ultra - }; - - enum class Quality : int - { - low, - medium, - high, - ultra - }; - - enum class WaterQuality : int - { - solidColor, - simpleReflection, - distortedReflection, - trueWavesReflection, - trueWavesRefraction - }; - - public: - bool _displayOffscreenDraw = true; - float _displayOffscreenScale = 1; - int _gpuAnisotropyLevel = 4; - int _gpuAntiAliasingLevel = 0; - Quality _gpuShaderQuality = Quality::medium; - bool _gpuTessellation = false; - int _gpuTextureLodLevel = 0; - bool _gpuTrilinearFilter = true; - bool _postProcessAntiAliasing = false; - bool _postProcessBloom = true; - bool _postProcessCinema = false; - bool _postProcessLightShafts = true; - bool _postProcessMotionBlur = false; - bool _postProcessSSAO = true; - bool _postProcessSSR = false; - bool _sceneAmbientOcclusion = true; - int _sceneGrassDensity = 600; - Quality _sceneShadowQuality = Quality::medium; - WaterQuality _sceneWaterQuality = WaterQuality::solidColor; - - bool operator==(const QualitySettings& that) const; - bool operator!=(const QualitySettings& that) const; - - void SetQuality(OverallQuality q); - void SetXrQuality(); - OverallQuality DetectQuality() const; + solidColor, + simpleReflection, + distortedReflection, + trueWavesReflection, + trueWavesRefraction }; - VERUS_TYPEDEFS(QualitySettings); - // Capacity is per frame. 3 frames are buffered. - class Limits + public: + bool _displayOffscreenDraw = true; + float _displayOffscreenScale = 1; + int _gpuAnisotropyLevel = 4; + int _gpuAntiAliasingLevel = 0; + Quality _gpuShaderQuality = Quality::medium; + bool _gpuTessellation = false; + int _gpuTextureLodLevel = 0; + bool _gpuTrilinearFilter = true; + bool _postProcessAntiAliasing = false; + bool _postProcessBloom = true; + bool _postProcessCinema = false; + bool _postProcessLightShafts = true; + bool _postProcessMotionBlur = false; + bool _postProcessSSAO = true; + bool _postProcessSSR = false; + bool _sceneAmbientOcclusion = true; + int _sceneGrassDensity = 600; + Quality _sceneShadowQuality = Quality::medium; + WaterQuality _sceneWaterQuality = WaterQuality::solidColor; + + bool operator==(const QualitySettings& that) const; + bool operator!=(const QualitySettings& that) const; + + void SetQuality(OverallQuality q); + void SetXrQuality(); + OverallQuality DetectQuality() const; + }; + VERUS_TYPEDEFS(QualitySettings); + + // Capacity is per frame. 3 frames are buffered. + class Limits + { + public: + int _d3d12_dhViewsCapacity = 50000; // D3D limit is one million. + int _d3d12_dhSamplersCapacity = 500; // D3D limit is 2048. + int _ds_ubViewCapacity = 20; + int _ds_ubSubpassFSCapacity = 20; + int _ds_ubShadowFSCapacity = 50; + int _ds_ubMeshVSCapacity = 20; + int _forest_ubVSCapacity = 200; + int _forest_ubFSCapacity = 200; + int _generateMips_ubCapacity = 50; + int _generateCubeMapMips_ubCapacity = 50; + int _grass_ubVSCapacity = 20; + int _grass_ubFSCapacity = 20; + int _gui_ubGuiCapacity = 100; + int _gui_ubGuiFSCapacity = 100; + int _mesh_ubViewCapacity = 800; + int _mesh_ubMaterialFSCapacity = 1000; + int _mesh_ubMeshVSCapacity = 2000; + int _mesh_ubSkeletonVSCapacity = 200; + int _particles_ubVSCapacity = 100; + int _particles_ubFSCapacity = 100; + int _quad_ubVSCapacity = 20; + int _quad_ubFSCapacity = 20; + int _sky_ubViewCapacity = 80; + int _sky_ubMaterialFSCapacity = 80; + int _sky_ubMeshVSCapacity = 80; + int _sky_ubObjectCapacity = 80; + int _terrain_ubVSCapacity = 40; + int _terrain_ubFSCapacity = 40; + int _water_ubVSCapacity = 20; + int _water_ubFSCapacity = 20; + }; + VERUS_TYPEDEFS(Limits); + + class Settings : public QualitySettings, public Singleton, IO::Json + { + typedef Map TMapLocalizedStrings; + + TMapLocalizedStrings _mapLocalizedStrings; + + public: + struct CommandLine { - public: - int _d3d12_dhViewsCapacity = 50000; // D3D limit is one million. - int _d3d12_dhSamplersCapacity = 500; // D3D limit is 2048. - int _ds_ubViewCapacity = 20; - int _ds_ubSubpassFSCapacity = 20; - int _ds_ubShadowFSCapacity = 50; - int _ds_ubMeshVSCapacity = 20; - int _forest_ubVSCapacity = 200; - int _forest_ubFSCapacity = 200; - int _generateMips_ubCapacity = 50; - int _generateCubeMapMips_ubCapacity = 50; - int _grass_ubVSCapacity = 20; - int _grass_ubFSCapacity = 20; - int _gui_ubGuiCapacity = 100; - int _gui_ubGuiFSCapacity = 100; - int _mesh_ubViewCapacity = 800; - int _mesh_ubMaterialFSCapacity = 1000; - int _mesh_ubMeshVSCapacity = 2000; - int _mesh_ubSkeletonVSCapacity = 200; - int _particles_ubVSCapacity = 100; - int _particles_ubFSCapacity = 100; - int _quad_ubVSCapacity = 20; - int _quad_ubFSCapacity = 20; - int _sky_ubViewCapacity = 80; - int _sky_ubMaterialFSCapacity = 80; - int _sky_ubMeshVSCapacity = 80; - int _sky_ubObjectCapacity = 80; - int _terrain_ubVSCapacity = 40; - int _terrain_ubFSCapacity = 40; - int _water_ubVSCapacity = 20; - int _water_ubFSCapacity = 20; + int _gapi = -1; + int _openXR = -1; + float _xrHeight = -FLT_MAX; + bool _exclusiveFullscreen = false; + bool _windowed = false; + bool _borderlessWindowed = false; + bool _restarted = false; }; - VERUS_TYPEDEFS(Limits); - class Settings : public QualitySettings, public Singleton, IO::Json + enum Platform : int { - typedef Map TMapLocalizedStrings; - - TMapLocalizedStrings _mapLocalizedStrings; - - public: - struct CommandLine - { - int _gapi = -1; - int _openXR = -1; - float _xrHeight = -FLT_MAX; - bool _exclusiveFullscreen = false; - bool _windowed = false; - bool _borderlessWindowed = false; - bool _restarted = false; - }; - - enum Platform : int - { - classic, - uwp - }; - - bool _displayAllowHighDPI = true; - float _displayFOV = 70; - DisplayMode _displayMode = DisplayMode::windowed; - int _displaySizeHeight = 720; - int _displaySizeWidth = 1280; - bool _displayVSync = true; - int _gapi = 0; - float _inputMouseSensitivity = 1; - bool _openXR = false; - bool _physicsSupportDebugDraw = false; - String _uiLang = "EN"; - float _xrFOV = 110; - float _xrHeight = 0; - CommandLine _commandLine; - Limits _limits; - String _imguiFont; - Info _info; - float _highDpiScale = 1; - Platform _platform = Platform::classic; - - Settings(); - ~Settings(); - - void ParseCommandLineArgs(int argc, wchar_t* argv[]); - void ParseCommandLineArgs(int argc, char* argv[]); - - void Load(); - void HandleHighDpi(); - void HandleCommandLineArgs(); - void Validate(); - void Save(); - - void MatchScreen(); - - RcLimits GetLimits() const { return _limits; } - - void LoadLocalizedStrings(CSZ url); - CSZ GetLocalizedString(CSZ id) const; - - void UpdateHighDpiScale(); - int GetFontSize() const; - - int Scale(int size, float extraScale = 1) const; - float GetScale() const; + classic, + uwp }; - VERUS_TYPEDEFS(Settings); - } + + bool _displayAllowHighDPI = true; + float _displayFOV = 70; + DisplayMode _displayMode = DisplayMode::windowed; + int _displaySizeHeight = 720; + int _displaySizeWidth = 1280; + bool _displayVSync = true; + int _gapi = 0; + float _inputMouseSensitivity = 1; + bool _openXR = false; + bool _physicsSupportDebugDraw = false; + String _uiLang = "EN"; + float _xrFOV = 110; + float _xrHeight = 0; + CommandLine _commandLine; + Limits _limits; + String _imguiFont; + Info _info; + float _highDpiScale = 1; + Platform _platform = Platform::classic; + + Settings(); + ~Settings(); + + void ParseCommandLineArgs(int argc, wchar_t* argv[]); + void ParseCommandLineArgs(int argc, char* argv[]); + + void Load(); + void HandleHighDpi(); + void HandleCommandLineArgs(); + void Validate(); + void Save(); + + void MatchScreen(); + + RcLimits GetLimits() const { return _limits; } + + void LoadLocalizedStrings(CSZ url); + CSZ GetLocalizedString(CSZ id) const; + + void UpdateHighDpiScale(); + int GetFontSize() const; + + int Scale(int size, float extraScale = 1) const; + float GetScale() const; + }; + VERUS_TYPEDEFS(Settings); } diff --git a/Verus/src/App/UndoManager.h b/Verus/src/App/UndoManager.h index a2a0700..c977e1c 100644 --- a/Verus/src/App/UndoManager.h +++ b/Verus/src/App/UndoManager.h @@ -1,71 +1,68 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::App { - namespace App + class UndoManager : public Object { - class UndoManager : public Object + public: + class Command { - public: - class Command - { - bool _hasRedo = false; - - public: - virtual ~Command() {} - virtual void SaveState(bool forUndo = false) = 0; - virtual void Undo() = 0; - virtual void Redo() = 0; - virtual Str GetName() const { return ""; } - virtual bool IsValid() const { return true; } - bool HasRedo() const { return _hasRedo; } - void SetHasRedo(bool hasRedo) { _hasRedo = hasRedo; }; - }; - VERUS_TYPEDEFS(Command); - - private: - Vector _vCommands; - int _maxCommands = 30; - int _nextUndo = 0; + bool _hasRedo = false; public: - UndoManager(); - ~UndoManager(); - - void Init(int maxCommands = 30); - void Done(); - - int GetMaxCommands() const { return _maxCommands; } - void SetMaxCommands(int maxCommands); - - int GetCommandCount() const { return Utils::Cast32(_vCommands.size()); } - - void Undo(); - void Redo(); - - bool CanUndo() const; - bool CanRedo() const; - - PCommand BeginChange(PCommand pCommand); - PCommand EndChange(PCommand pCommand = nullptr); - - void DeleteInvalidCommands(); - - template - void ForEachCommand(const T& fn) - { - int i = 0; - for (auto& x : _vCommands) - { - if (Continue::no == fn(x, i < _nextUndo)) - return; - i++; - } - } - - int GetNextUndo() const { return _nextUndo; } + virtual ~Command() {} + virtual void SaveState(bool forUndo = false) = 0; + virtual void Undo() = 0; + virtual void Redo() = 0; + virtual Str GetName() const { return ""; } + virtual bool IsValid() const { return true; } + bool HasRedo() const { return _hasRedo; } + void SetHasRedo(bool hasRedo) { _hasRedo = hasRedo; }; }; - VERUS_TYPEDEFS(UndoManager); - } + VERUS_TYPEDEFS(Command); + + private: + Vector _vCommands; + int _maxCommands = 30; + int _nextUndo = 0; + + public: + UndoManager(); + ~UndoManager(); + + void Init(int maxCommands = 30); + void Done(); + + int GetMaxCommands() const { return _maxCommands; } + void SetMaxCommands(int maxCommands); + + int GetCommandCount() const { return Utils::Cast32(_vCommands.size()); } + + void Undo(); + void Redo(); + + bool CanUndo() const; + bool CanRedo() const; + + PCommand BeginChange(PCommand pCommand); + PCommand EndChange(PCommand pCommand = nullptr); + + void DeleteInvalidCommands(); + + template + void ForEachCommand(const T& fn) + { + int i = 0; + for (auto& x : _vCommands) + { + if (Continue::no == fn(x, i < _nextUndo)) + return; + i++; + } + } + + int GetNextUndo() const { return _nextUndo; } + }; + VERUS_TYPEDEFS(UndoManager); } diff --git a/Verus/src/App/Window.h b/Verus/src/App/Window.h index 90ca1c9..ef51fbe 100644 --- a/Verus/src/App/Window.h +++ b/Verus/src/App/Window.h @@ -1,41 +1,38 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::App { - namespace App + class Window : public Object { - class Window : public Object + SDL_Window* _pWnd = nullptr; + + public: + struct Desc { - SDL_Window* _pWnd = nullptr; + CSZ _title = nullptr; + int _x = SDL_WINDOWPOS_CENTERED; + int _y = SDL_WINDOWPOS_CENTERED; + int _width = 0; + int _height = 0; + Uint32 _flags = 0; + DisplayMode _displayMode = DisplayMode::windowed; + UINT32 _color = VERUS_COLOR_BLACK; + bool _resizable = true; + bool _maximized = false; + bool _useSettings = true; - public: - struct Desc - { - CSZ _title = nullptr; - int _x = SDL_WINDOWPOS_CENTERED; - int _y = SDL_WINDOWPOS_CENTERED; - int _width = 0; - int _height = 0; - Uint32 _flags = 0; - DisplayMode _displayMode = DisplayMode::windowed; - UINT32 _color = VERUS_COLOR_BLACK; - bool _resizable = true; - bool _maximized = false; - bool _useSettings = true; - - void ApplySettings(); - }; - VERUS_TYPEDEFS(Desc); - - Window(); - ~Window(); - - void Init(RcDesc desc = Desc()); - void Done(); - - SDL_Window* GetSDL() const { return _pWnd; } + void ApplySettings(); }; - VERUS_TYPEDEFS(Window); - } + VERUS_TYPEDEFS(Desc); + + Window(); + ~Window(); + + void Init(RcDesc desc = Desc()); + void Done(); + + SDL_Window* GetSDL() const { return _pWnd; } + }; + VERUS_TYPEDEFS(Window); } diff --git a/Verus/src/Audio/AudioSystem.cpp b/Verus/src/Audio/AudioSystem.cpp index 1986f19..7adb44e 100644 --- a/Verus/src/Audio/AudioSystem.cpp +++ b/Verus/src/Audio/AudioSystem.cpp @@ -68,14 +68,14 @@ void AudioSystem::Update() _streamPlayers[i].Update(); // Update every frame: - for (auto& x : TStoreSounds::_map) - x.second.Update(); + for (auto& [key, value] : TStoreSounds::_map) + value.Update(); // Update ~15 times per second: if (timer.IsEventEvery(67)) { - for (auto& x : TStoreSounds::_map) - x.second.UpdateHRTF(); + for (auto& [key, value] : TStoreSounds::_map) + value.UpdateHRTF(); if (VMath::lengthSqr(_listenerDirection) > 0.1f && VMath::lengthSqr(_listenerUp) > 0.1f) diff --git a/Verus/src/Audio/AudioSystem.h b/Verus/src/Audio/AudioSystem.h index 7ffe909..5d33bec 100644 --- a/Verus/src/Audio/AudioSystem.h +++ b/Verus/src/Audio/AudioSystem.h @@ -1,45 +1,42 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Audio { - namespace Audio + typedef StoreUnique TStoreSounds; + class AudioSystem : public Singleton, public Object, private TStoreSounds { - typedef StoreUnique TStoreSounds; - class AudioSystem : public Singleton, public Object, private TStoreSounds - { - Point3 _listenerPosition = Point3(0); - Vector3 _listenerDirection = Vector3(0, 0, 1); - Vector3 _listenerVelocity = Vector3(0); - Vector3 _listenerUp = Vector3(0, 1, 0); - ALCdevice* _pDevice = nullptr; - ALCcontext* _pContext = nullptr; - String _version; - String _deviceSpecifier; - StreamPlayer _streamPlayers[4]; + Point3 _listenerPosition = Point3(0); + Vector3 _listenerDirection = Vector3(0, 0, 1); + Vector3 _listenerVelocity = Vector3(0); + Vector3 _listenerUp = Vector3(0, 1, 0); + ALCdevice* _pDevice = nullptr; + ALCcontext* _pContext = nullptr; + String _version; + String _deviceSpecifier; + StreamPlayer _streamPlayers[4]; - public: - AudioSystem(); - ~AudioSystem(); + public: + AudioSystem(); + ~AudioSystem(); - void Init(); - void Done(); + void Init(); + void Done(); - void Update(); + void Update(); - RStreamPlayer GetStreamPlayer(int index) { return _streamPlayers[index]; } - void DeleteAllStreams(); + RStreamPlayer GetStreamPlayer(int index) { return _streamPlayers[index]; } + void DeleteAllStreams(); - PSound InsertSound(CSZ url); - PSound FindSound(CSZ url); - void DeleteSound(CSZ url); - void DeleteAllSounds(); + PSound InsertSound(CSZ url); + PSound FindSound(CSZ url); + void DeleteSound(CSZ url); + void DeleteAllSounds(); - void UpdateListener(RcPoint3 pos, RcVector3 dir, RcVector3 vel, RcVector3 up); - float ComputeTravelDelay(RcPoint3 pos) const; + void UpdateListener(RcPoint3 pos, RcVector3 dir, RcVector3 vel, RcVector3 up); + float ComputeTravelDelay(RcPoint3 pos) const; - static CSZ GetSingletonFailMessage() { return "Make_Audio(); // FAIL.\r\n"; } - }; - VERUS_TYPEDEFS(AudioSystem); - } + static CSZ GetSingletonFailMessage() { return "Make_Audio(); // FAIL.\r\n"; } + }; + VERUS_TYPEDEFS(AudioSystem); } diff --git a/Verus/src/Audio/OggCallbacks.cpp b/Verus/src/Audio/OggCallbacks.cpp index 7b7ba9e..f6ddd73 100644 --- a/Verus/src/Audio/OggCallbacks.cpp +++ b/Verus/src/Audio/OggCallbacks.cpp @@ -1,47 +1,44 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #include "verus.h" -namespace verus +namespace verus::Audio { - namespace Audio + size_t read_func(void* ptr, size_t size, size_t nmemb, void* datasource) { - size_t read_func(void* ptr, size_t size, size_t nmemb, void* datasource) - { - POggDataSource pDS = static_cast(datasource); - INT64 readLen = size * nmemb; - const INT64 maxLen = pDS->_size - pDS->_cursor; - if (readLen > maxLen) - readLen = maxLen; - memcpy(ptr, pDS->_p + pDS->_cursor, size_t(readLen)); - pDS->_cursor += readLen; - return size_t(readLen); - } - - int seek_func(void* datasource, ogg_int64_t offset, int whence) - { - POggDataSource pDS = static_cast(datasource); - switch (whence) - { - case SEEK_SET: pDS->_cursor = offset; return 0; - case SEEK_CUR: pDS->_cursor += offset; return 0; - case SEEK_END: pDS->_cursor = pDS->_size - offset; return 0; - } - return -1; - } - - int close_func(void* datasource) - { - POggDataSource pDS = static_cast(datasource); - pDS->_cursor = 0; - return 0; - } - - long tell_func(void* datasource) - { - POggDataSource pDS = static_cast(datasource); - return long(pDS->_cursor); - } - - const ov_callbacks g_oggCallbacks = { read_func, seek_func, close_func, tell_func }; + POggDataSource pDS = static_cast(datasource); + INT64 readLen = size * nmemb; + const INT64 maxLen = pDS->_size - pDS->_cursor; + if (readLen > maxLen) + readLen = maxLen; + memcpy(ptr, pDS->_p + pDS->_cursor, size_t(readLen)); + pDS->_cursor += readLen; + return size_t(readLen); } + + int seek_func(void* datasource, ogg_int64_t offset, int whence) + { + POggDataSource pDS = static_cast(datasource); + switch (whence) + { + case SEEK_SET: pDS->_cursor = offset; return 0; + case SEEK_CUR: pDS->_cursor += offset; return 0; + case SEEK_END: pDS->_cursor = pDS->_size - offset; return 0; + } + return -1; + } + + int close_func(void* datasource) + { + POggDataSource pDS = static_cast(datasource); + pDS->_cursor = 0; + return 0; + } + + long tell_func(void* datasource) + { + POggDataSource pDS = static_cast(datasource); + return long(pDS->_cursor); + } + + const ov_callbacks g_oggCallbacks = { read_func, seek_func, close_func, tell_func }; } diff --git a/Verus/src/Audio/OggCallbacks.h b/Verus/src/Audio/OggCallbacks.h index 0665a40..5db3b57 100644 --- a/Verus/src/Audio/OggCallbacks.h +++ b/Verus/src/Audio/OggCallbacks.h @@ -1,23 +1,20 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Audio { - namespace Audio + struct OggDataSource { - struct OggDataSource - { - const BYTE* _p = nullptr; - INT64 _size = 0; - INT64 _cursor = 0; - }; - VERUS_TYPEDEFS(OggDataSource); + const BYTE* _p = nullptr; + INT64 _size = 0; + INT64 _cursor = 0; + }; + VERUS_TYPEDEFS(OggDataSource); - size_t read_func(void*, size_t, size_t, void*); - int seek_func(void*, ogg_int64_t, int); - int close_func(void*); - long tell_func(void*); + size_t read_func(void*, size_t, size_t, void*); + int seek_func(void*, ogg_int64_t, int); + int close_func(void*); + long tell_func(void*); - extern const ov_callbacks g_oggCallbacks; - } + extern const ov_callbacks g_oggCallbacks; } diff --git a/Verus/src/Audio/Sound.h b/Verus/src/Audio/Sound.h index 36035b2..396c430 100644 --- a/Verus/src/Audio/Sound.h +++ b/Verus/src/Audio/Sound.h @@ -1,152 +1,149 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Audio { - namespace Audio + struct SoundFlags { - struct SoundFlags + enum { - enum - { - loaded = (ObjectFlags::user << 0), - is3D = (ObjectFlags::user << 1), - looping = (ObjectFlags::user << 2), - randOff = (ObjectFlags::user << 3), - keepPcmBuffer = (ObjectFlags::user << 4), - user = (ObjectFlags::user << 5) - }; + loaded = (ObjectFlags::user << 0), + is3D = (ObjectFlags::user << 1), + looping = (ObjectFlags::user << 2), + randOff = (ObjectFlags::user << 3), + keepPcmBuffer = (ObjectFlags::user << 4), + user = (ObjectFlags::user << 5) }; + }; - class Sound : public Object, public IO::AsyncDelegate + class Sound : public Object, public IO::AsyncDelegate + { + Source _sources[8]; + String _url; + Vector _vPcmBuffer; + ALuint _buffer = 0; + int _refCount = 0; + int _next = 0; + Interval _gain = 1; + Interval _pitch = 1; + float _referenceDistance = 4; + float _length = 0; + + public: + // Note that this structure contains some default values for new sources, which can be changed per source. + struct Desc { - Source _sources[8]; - String _url; - Vector _vPcmBuffer; - ALuint _buffer = 0; - int _refCount = 0; - int _next = 0; - Interval _gain = 1; - Interval _pitch = 1; - float _referenceDistance = 4; - float _length = 0; + CSZ _url = nullptr; + Interval _gain = 0.8f; + Interval _pitch = 1; + float _referenceDistance = 4; + bool _is3D = false; + bool _looping = false; + bool _randomOffset = false; + bool _keepPcmBuffer = false; - public: - // Note that this structure contains some default values for new sources, which can be changed per source. - struct Desc - { - CSZ _url = nullptr; - Interval _gain = 0.8f; - Interval _pitch = 1; - float _referenceDistance = 4; - bool _is3D = false; - bool _looping = false; - bool _randomOffset = false; - bool _keepPcmBuffer = false; - - Desc(CSZ url) : _url(url) {} - Desc& Set3D(bool b = true) { _is3D = b; return *this; } - Desc& SetLooping(bool b = true) { _looping = b; return *this; } - Desc& SetRandomOffset(bool b = true) { _randomOffset = b; return *this; } - Desc& SetGain(Interval gain) { _gain = gain; return *this; } - Desc& SetPitch(Interval pitch) { _pitch = pitch; return *this; } - Desc& SetReferenceDistance(float rd) { _referenceDistance = rd; return *this; } - }; - VERUS_TYPEDEFS(Desc); - - Sound(); - ~Sound(); - - void AddRef() { _refCount++; } - int GetRefCount() const { return _refCount; } - - void Init(RcDesc desc); - bool Done(); - - void Update(); - void UpdateHRTF(); - - // - virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; - bool IsLoaded() const { return IsFlagSet(SoundFlags::loaded); } - Str GetURL() const { return _C(_url); } - // - - SourcePtr NewSource(PSourcePtr pID = nullptr, Source::RcDesc desc = Source::Desc()); - - Interval GetGain() const { return _gain; } - Interval GetPitch() const { return _pitch; } - - float GetLength() const { return _length; } - - float GetRandomOffset() const; - void SetRandomOffset(bool b) { b ? SetFlag(SoundFlags::randOff) : ResetFlag(SoundFlags::randOff); } - bool HasRandomOffset() const { return IsFlagSet(SoundFlags::randOff); } - - Blob GetPcmBuffer() const; + Desc(CSZ url) : _url(url) {} + Desc& Set3D(bool b = true) { _is3D = b; return *this; } + Desc& SetLooping(bool b = true) { _looping = b; return *this; } + Desc& SetRandomOffset(bool b = true) { _randomOffset = b; return *this; } + Desc& SetGain(Interval gain) { _gain = gain; return *this; } + Desc& SetPitch(Interval pitch) { _pitch = pitch; return *this; } + Desc& SetReferenceDistance(float rd) { _referenceDistance = rd; return *this; } }; - VERUS_TYPEDEFS(Sound); + VERUS_TYPEDEFS(Desc); - class SoundPtr : public Ptr + Sound(); + ~Sound(); + + void AddRef() { _refCount++; } + int GetRefCount() const { return _refCount; } + + void Init(RcDesc desc); + bool Done(); + + void Update(); + void UpdateHRTF(); + + // + virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; + bool IsLoaded() const { return IsFlagSet(SoundFlags::loaded); } + Str GetURL() const { return _C(_url); } + // + + SourcePtr NewSource(PSourcePtr pID = nullptr, Source::RcDesc desc = Source::Desc()); + + Interval GetGain() const { return _gain; } + Interval GetPitch() const { return _pitch; } + + float GetLength() const { return _length; } + + float GetRandomOffset() const; + void SetRandomOffset(bool b) { b ? SetFlag(SoundFlags::randOff) : ResetFlag(SoundFlags::randOff); } + bool HasRandomOffset() const { return IsFlagSet(SoundFlags::randOff); } + + Blob GetPcmBuffer() const; + }; + VERUS_TYPEDEFS(Sound); + + class SoundPtr : public Ptr + { + public: + void Init(Sound::RcDesc desc); + }; + VERUS_TYPEDEFS(SoundPtr); + + class SoundPwn : public SoundPtr + { + public: + ~SoundPwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(SoundPwn); + + template + class SoundPwns + { + SoundPwn _sounds[COUNT]; + int _prev = 0; + + public: + SoundPwns() { - public: - void Init(Sound::RcDesc desc); - }; - VERUS_TYPEDEFS(SoundPtr); + } - class SoundPwn : public SoundPtr + ~SoundPwns() { - public: - ~SoundPwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(SoundPwn); + Done(); + } - template - class SoundPwns + void Init(Sound::RcDesc desc) { - SoundPwn _sounds[COUNT]; - int _prev = 0; - - public: - SoundPwns() + char buffer[200]; + VERUS_FOR(i, COUNT) { + sprintf_s(buffer, desc._url, i); + Sound::Desc descs = desc; + descs._url = buffer; + _sounds[i].Init(descs); } + } - ~SoundPwns() - { - Done(); - } + void Done() + { + VERUS_FOR(i, COUNT) + _sounds[i].Done(); + } - void Init(Sound::RcDesc desc) - { - char buffer[200]; - VERUS_FOR(i, COUNT) - { - sprintf_s(buffer, desc._url, i); - Sound::Desc descs = desc; - descs._url = buffer; - _sounds[i].Init(descs); - } - } - - void Done() - { - VERUS_FOR(i, COUNT) - _sounds[i].Done(); - } - - RSoundPtr operator[](int i) - { - const bool useRand = i < 0; - if (useRand) - i = Utils::I().GetRandom().Next() & 0xFF; // Only positive. - i %= COUNT; - if (useRand && (i == _prev)) - i = (i + 1) % COUNT; - _prev = i; - return _sounds[i]; - } - }; - } + RSoundPtr operator[](int i) + { + const bool useRand = i < 0; + if (useRand) + i = Utils::I().GetRandom().Next() & 0xFF; // Only positive. + i %= COUNT; + if (useRand && (i == _prev)) + i = (i + 1) % COUNT; + _prev = i; + return _sounds[i]; + } + }; } diff --git a/Verus/src/Audio/Source.h b/Verus/src/Audio/Source.h index 4ef21ad..b8c68a1 100644 --- a/Verus/src/Audio/Source.h +++ b/Verus/src/Audio/Source.h @@ -1,57 +1,54 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Audio { - namespace Audio + class Source { - class Source + friend class SourcePtr; // _pSound @ Attach(). + friend class Sound; // _sid @ NewSource(). + + Point3 _position = Point3(0); + Vector3 _direction = Vector3(0); + Vector3 _velocity = Vector3(0); + Sound* _pSound = nullptr; + ALuint _sid = 0; + float _travelDelay = 0; + + public: + struct Desc { - friend class SourcePtr; // _pSound @ Attach(). - friend class Sound; // _sid @ NewSource(). - - Point3 _position = Point3(0); - Vector3 _direction = Vector3(0); - Vector3 _velocity = Vector3(0); - Sound* _pSound = nullptr; - ALuint _sid = 0; - float _travelDelay = 0; - - public: - struct Desc - { - float _secOffset = 0; - float _gain = 1; - float _pitch = 1; - bool _stopSource = true; - }; - VERUS_TYPEDEFS(Desc); - - Source(); - ~Source(); - - void Done(); - - void Update(); - void UpdateHRTF(bool is3D); - - void Play(); - void PlayAt(RcPoint3 pos, RcVector3 dir = Vector3(0), RcVector3 vel = Vector3(0), float delay = 0); - void Stop(); - void MoveTo(RcPoint3 pos, RcVector3 dir = Vector3(0), RcVector3 vel = Vector3(0)); - - void SetGain(float gain); - void SetPitch(float pitch); - void SetLooping(bool loop); + float _secOffset = 0; + float _gain = 1; + float _pitch = 1; + bool _stopSource = true; }; - VERUS_TYPEDEFS(Source); + VERUS_TYPEDEFS(Desc); - class SourcePtr : public Ptr - { - public: - void Attach(Source* pSource, Sound* pSound); - void Done(); - }; - VERUS_TYPEDEFS(SourcePtr); - } + Source(); + ~Source(); + + void Done(); + + void Update(); + void UpdateHRTF(bool is3D); + + void Play(); + void PlayAt(RcPoint3 pos, RcVector3 dir = Vector3(0), RcVector3 vel = Vector3(0), float delay = 0); + void Stop(); + void MoveTo(RcPoint3 pos, RcVector3 dir = Vector3(0), RcVector3 vel = Vector3(0)); + + void SetGain(float gain); + void SetPitch(float pitch); + void SetLooping(bool loop); + }; + VERUS_TYPEDEFS(Source); + + class SourcePtr : public Ptr + { + public: + void Attach(Source* pSource, Sound* pSound); + void Done(); + }; + VERUS_TYPEDEFS(SourcePtr); } diff --git a/Verus/src/Audio/StreamPlayer.h b/Verus/src/Audio/StreamPlayer.h index 62f9056..54cc62a 100644 --- a/Verus/src/Audio/StreamPlayer.h +++ b/Verus/src/Audio/StreamPlayer.h @@ -1,83 +1,80 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Audio { - namespace Audio + class Track : public IO::AsyncDelegate { - class Track : public IO::AsyncDelegate + Vector _vOggEncodedTrack; + OggDataSource _ds; + std::atomic_bool _loaded; + + public: + Track(); + ~Track(); + + POggDataSource GetOggDataSource() { return &_ds; } + void Init(CSZ url); + void Done(); + + virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; + bool IsLoaded() const { return _loaded; } + }; + VERUS_TYPEDEFS(Track); + + struct StreamPlayerFlags + { + enum { - Vector _vOggEncodedTrack; - OggDataSource _ds; - std::atomic_bool _loaded; - - public: - Track(); - ~Track(); - - POggDataSource GetOggDataSource() { return &_ds; } - void Init(CSZ url); - void Done(); - - virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; - bool IsLoaded() const { return _loaded; } + stopThread = (ObjectFlags::user << 0), + play = (ObjectFlags::user << 1), + noLock = (ObjectFlags::user << 2) }; - VERUS_TYPEDEFS(Track); + }; - struct StreamPlayerFlags - { - enum - { - stopThread = (ObjectFlags::user << 0), - play = (ObjectFlags::user << 1), - noLock = (ObjectFlags::user << 2) - }; - }; + class StreamPlayer : public Object, public Lockable + { + Track _nativeTrack; + Vector _vTracks; + Vector _vSmallBuffer; + Vector _vMediumBuffer; + std::thread _thread; + std::condition_variable _cv; + vorbis_info* _pVorbisInfo = nullptr; + PTrack _pTrack = nullptr; + OggVorbis_File _oggVorbisFile; + ALuint _buffers[2]; + ALuint _source = 0; + ALenum _format = 0; + Linear _fade; + float _gain = 0.25f; + int _currentTrack = 0; - class StreamPlayer : public Object, public Lockable - { - Track _nativeTrack; - Vector _vTracks; - Vector _vSmallBuffer; - Vector _vMediumBuffer; - std::thread _thread; - std::condition_variable _cv; - vorbis_info* _pVorbisInfo = nullptr; - PTrack _pTrack = nullptr; - OggVorbis_File _oggVorbisFile; - ALuint _buffers[2]; - ALuint _source = 0; - ALenum _format = 0; - Linear _fade; - float _gain = 0.25f; - int _currentTrack = 0; + public: + StreamPlayer(); + ~StreamPlayer(); - public: - StreamPlayer(); - ~StreamPlayer(); + void Init(); + void Done(); - void Init(); - void Done(); + void Update(); - void Update(); + void AddTrack(PTrack pTrack); + void DeleteTrack(PTrack pTrack); + void SwitchToTrack(PTrack pTrack); - void AddTrack(PTrack pTrack); - void DeleteTrack(PTrack pTrack); - void SwitchToTrack(PTrack pTrack); + void Play(); + void Stop(); + void Seek(int pos); - void Play(); - void Stop(); - void Seek(int pos); + VERUS_P(void ThreadProc()); + VERUS_P(void StopThread()); + VERUS_P(void FillBuffer(ALuint buffer)); - VERUS_P(void ThreadProc()); - VERUS_P(void StopThread()); - VERUS_P(void FillBuffer(ALuint buffer)); - - void FadeIn(float time); - void FadeOut(float time); - void Mute(); - void SetGain(float gain); - }; - VERUS_TYPEDEFS(StreamPlayer); - } + void FadeIn(float time); + void FadeOut(float time); + void Mute(); + void SetGain(float gain); + }; + VERUS_TYPEDEFS(StreamPlayer); } diff --git a/Verus/src/CGI/BaseCommandBuffer.h b/Verus/src/CGI/BaseCommandBuffer.h index e54fdbd..2517124 100644 --- a/Verus/src/CGI/BaseCommandBuffer.h +++ b/Verus/src/CGI/BaseCommandBuffer.h @@ -1,113 +1,110 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + // View can be a smaller portion of framebuffer with an offset. + enum class ViewportScissorFlags : UINT32 { - // View can be a smaller portion of framebuffer with an offset. - enum class ViewportScissorFlags : UINT32 - { - none = 0, - setViewportForFramebuffer = (1 << 0), - setViewportForCurrentView = (1 << 1), - setScissorForFramebuffer = (1 << 2), - setScissorForCurrentView = (1 << 3), - applyOffscreenScale = (1 << 4), - applyHalfScale = (1 << 5), - setAllForFramebuffer = setViewportForFramebuffer | setScissorForFramebuffer, - setAllForCurrentView = setViewportForCurrentView | setScissorForCurrentView, - setAllForCurrentViewScaled = setAllForCurrentView | applyOffscreenScale - }; + none = 0, + setViewportForFramebuffer = (1 << 0), + setViewportForCurrentView = (1 << 1), + setScissorForFramebuffer = (1 << 2), + setScissorForCurrentView = (1 << 3), + applyOffscreenScale = (1 << 4), + applyHalfScale = (1 << 5), + setAllForFramebuffer = setViewportForFramebuffer | setScissorForFramebuffer, + setAllForCurrentView = setViewportForCurrentView | setScissorForCurrentView, + setAllForCurrentViewScaled = setAllForCurrentView | applyOffscreenScale + }; - class BaseCommandBuffer : public Object, public Scheduled - { - protected: - Vector4 _viewportSize = Vector4(0); - Vector4 _viewScaleBias = Vector4(0); + class BaseCommandBuffer : public Object, public Scheduled + { + protected: + Vector4 _viewportSize = Vector4(0); + Vector4 _viewScaleBias = Vector4(0); - void SetViewportAndScissor(ViewportScissorFlags vsf, int width, int height); + void SetViewportAndScissor(ViewportScissorFlags vsf, int width, int height); - BaseCommandBuffer() = default; - virtual ~BaseCommandBuffer() = default; + BaseCommandBuffer() = default; + virtual ~BaseCommandBuffer() = default; - public: - virtual void Init() = 0; - virtual void Done() = 0; + public: + virtual void Init() = 0; + virtual void Done() = 0; - virtual void InitOneTimeSubmit() = 0; - virtual void DoneOneTimeSubmit() = 0; + virtual void InitOneTimeSubmit() = 0; + virtual void DoneOneTimeSubmit() = 0; - virtual void Begin() = 0; - virtual void End() = 0; + virtual void Begin() = 0; + virtual void End() = 0; - virtual void PipelineImageMemoryBarrier(TexturePtr tex, ImageLayout oldLayout, ImageLayout newLayout, - Range mipLevels, Range arrayLayers = 0) = 0; + virtual void PipelineImageMemoryBarrier(TexturePtr tex, ImageLayout oldLayout, ImageLayout newLayout, + Range mipLevels, Range arrayLayers = 0) = 0; - // - virtual void BeginRenderPass(RPHandle renderPassHandle, FBHandle framebufferHandle, - std::initializer_list ilClearValues, ViewportScissorFlags vsf = ViewportScissorFlags::setAllForCurrentViewScaled) = 0; - virtual void NextSubpass() = 0; - virtual void EndRenderPass() = 0; - // + // + virtual void BeginRenderPass(RPHandle renderPassHandle, FBHandle framebufferHandle, + std::initializer_list ilClearValues, ViewportScissorFlags vsf = ViewportScissorFlags::setAllForCurrentViewScaled) = 0; + virtual void NextSubpass() = 0; + virtual void EndRenderPass() = 0; + // - // - virtual void BindPipeline(PipelinePtr pipe) = 0; - virtual void SetViewport(std::initializer_list il, float minDepth = 0, float maxDepth = 1) = 0; - virtual void SetScissor(std::initializer_list il) = 0; - virtual void SetBlendConstants(const float* p) = 0; - // + // + virtual void BindPipeline(PipelinePtr pipe) = 0; + virtual void SetViewport(std::initializer_list il, float minDepth = 0, float maxDepth = 1) = 0; + virtual void SetScissor(std::initializer_list il) = 0; + virtual void SetBlendConstants(const float* p) = 0; + // - // - virtual void BindVertexBuffers(GeometryPtr geo, UINT32 bindingsFilter = UINT32_MAX) = 0; - virtual void BindIndexBuffer(GeometryPtr geo) = 0; - // + // + virtual void BindVertexBuffers(GeometryPtr geo, UINT32 bindingsFilter = UINT32_MAX) = 0; + virtual void BindIndexBuffer(GeometryPtr geo) = 0; + // - // - virtual bool BindDescriptors(ShaderPtr shader, int setNumber, CSHandle complexSetHandle = CSHandle()) = 0; - virtual bool BindDescriptors(ShaderPtr shader, int setNumber, GeometryPtr geo, int sbIndex) = 0; - virtual void PushConstants(ShaderPtr shader, int offset, int size, const void* p, ShaderStageFlags stageFlags = ShaderStageFlags::vs_fs) = 0; - // + // + virtual bool BindDescriptors(ShaderPtr shader, int setNumber, CSHandle complexSetHandle = CSHandle()) = 0; + virtual bool BindDescriptors(ShaderPtr shader, int setNumber, GeometryPtr geo, int sbIndex) = 0; + virtual void PushConstants(ShaderPtr shader, int offset, int size, const void* p, ShaderStageFlags stageFlags = ShaderStageFlags::vs_fs) = 0; + // - // - virtual void Draw(int vertexCount, int instanceCount = 1, int firstVertex = 0, int firstInstance = 0) = 0; - virtual void DrawIndexed(int indexCount, int instanceCount = 1, int firstIndex = 0, int vertexOffset = 0, int firstInstance = 0) = 0; - virtual void Dispatch(int groupCountX, int groupCountY, int groupCountZ = 1) = 0; - virtual void DispatchIndirect() {} // WIP. - virtual void DispatchMesh(int groupCountX, int groupCountY, int groupCountZ) {} // WIP. - virtual void TraceRays(int width, int height, int depth) {} // WIP. - // + // + virtual void Draw(int vertexCount, int instanceCount = 1, int firstVertex = 0, int firstInstance = 0) = 0; + virtual void DrawIndexed(int indexCount, int instanceCount = 1, int firstIndex = 0, int vertexOffset = 0, int firstInstance = 0) = 0; + virtual void Dispatch(int groupCountX, int groupCountY, int groupCountZ = 1) = 0; + virtual void DispatchIndirect() {} // WIP. + virtual void DispatchMesh(int groupCountX, int groupCountY, int groupCountZ) {} // WIP. + virtual void TraceRays(int width, int height, int depth) {} // WIP. + // - // - virtual void ProfilerBeginEvent(UINT32 color, CSZ text) {} - virtual void ProfilerEndEvent() {} - virtual void ProfilerSetMarker(UINT32 color, CSZ text) {} - // + // + virtual void ProfilerBeginEvent(UINT32 color, CSZ text) {} + virtual void ProfilerEndEvent() {} + virtual void ProfilerSetMarker(UINT32 color, CSZ text) {} + // - RcVector4 GetViewportSize() const { return _viewportSize; } - RcVector4 GetViewScaleBias() const { return _viewScaleBias; } - }; - VERUS_TYPEDEFS(BaseCommandBuffer); + RcVector4 GetViewportSize() const { return _viewportSize; } + RcVector4 GetViewScaleBias() const { return _viewScaleBias; } + }; + VERUS_TYPEDEFS(BaseCommandBuffer); - class CommandBufferPtr : public Ptr - { - public: - void Init(); - void InitOneTimeSubmit(); - }; - VERUS_TYPEDEFS(CommandBufferPtr); + class CommandBufferPtr : public Ptr + { + public: + void Init(); + void InitOneTimeSubmit(); + }; + VERUS_TYPEDEFS(CommandBufferPtr); - class CommandBufferPwn : public CommandBufferPtr - { - public: - ~CommandBufferPwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(CommandBufferPwn); + class CommandBufferPwn : public CommandBufferPtr + { + public: + ~CommandBufferPwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(CommandBufferPwn); - template - class CommandBufferPwns : public Pwns - { - }; - } + template + class CommandBufferPwns : public Pwns + { + }; } diff --git a/Verus/src/CGI/BaseExtReality.h b/Verus/src/CGI/BaseExtReality.h index 182f2a5..7ec0b79 100644 --- a/Verus/src/CGI/BaseExtReality.h +++ b/Verus/src/CGI/BaseExtReality.h @@ -3,121 +3,118 @@ #define VERUS_XR_DESTROY(xr, fn) {if (XR_NULL_HANDLE != xr) {fn; xr = XR_NULL_HANDLE;}} -namespace verus +namespace verus::CGI { - namespace CGI + class BaseExtReality : public Object { - class BaseExtReality : public Object + struct ActionEx { - struct ActionEx - { - XrAction _handle = XR_NULL_HANDLE; - Vector _vSubactionPaths; - Vector _vActionSpaces; - }; - VERUS_TYPEDEFS(ActionEx); - - protected: - Math::Pose _areaSpaceHeadPose; - Math::Pose _worldSpaceHeadPose; - Math::Pose _areaPose; // In world space. - Transform3 _trAreaToWorld = Transform3::identity(); - Point3 _areaOrigin = Point3(0); - Vector4 _areaSpaceUserOffset = Vector4(0); // W is yaw. - XrInstance _instance = XR_NULL_HANDLE; - XrDebugUtilsMessengerEXT _debugUtilsMessenger = XR_NULL_HANDLE; - XrSystemId _systemId = XR_NULL_SYSTEM_ID; - XrSession _session = XR_NULL_HANDLE; - XrSpace _referenceSpace = XR_NULL_HANDLE; - XrSpace _headSpace = XR_NULL_HANDLE; - XrTime _predictedDisplayTime = 0; - Vector _vRequiredExtensions; - Vector _vViews; - Vector _vCompositionLayerProjectionViews; - Vector _vActionSets; - Vector _vActiveActionSets; - Vector _vActions; - XrFormFactor _formFactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY; - XrViewConfigurationType _viewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; - XrEnvironmentBlendMode _envBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; - XrSessionState _sessionState = XR_SESSION_STATE_UNKNOWN; - XrPosef _identityPose; - float _userHeight = 1.5f; - float _areaYaw = 0; - int _combinedSwapChainWidth = 0; - int _combinedSwapChainHeight = 0; - int _currentViewIndex = 0; - int _swapChainBufferCount = 0; - int _swapChainBufferIndex = 0; - RPHandle _rph; - Vector _fbh; - bool _runningSession = false; - bool _shouldRender = false; - bool _areaUpdated = false; - - BaseExtReality(); - virtual ~BaseExtReality(); - - public: - virtual void Init(); - virtual void Done(); - - protected: - static XRAPI_ATTR XrBool32 XRAPI_CALL DebugUtilsMessengerCallback( - XrDebugUtilsMessageSeverityFlagsEXT messageSeverityFlags, - XrDebugUtilsMessageTypeFlagsEXT messageTypeFlags, - const XrDebugUtilsMessengerCallbackDataEXT* pCallbackData, - void* pUserData); - bool CheckRequiredExtensions() const; - void CreateInstance(); - void CreateDebugUtilsMessenger(); - void CreateReferenceSpace(); - void CreateHeadSpace(); - virtual XrSwapchain GetSwapChain(int viewIndex) = 0; - virtual void GetSwapChainSize(int viewIndex, int32_t& w, int32_t& h) = 0; - - public: - virtual void CreateActions(); - virtual void PollEvents(); - virtual void SyncActions(UINT32 activeActionSetsMask = -1); - - virtual bool GetActionStateBoolean(int actionIndex, bool& currentState, bool* pChangedState, int subaction); - virtual bool GetActionStateFloat(int actionIndex, float& currentState, bool* pChangedState, int subaction); - virtual bool GetActionStatePose(int actionIndex, bool& currentState, Math::RPose pose, int subaction); - - virtual void BeginFrame(); - virtual int LocateViews(); - virtual void BeginView(int viewIndex, RViewDesc viewDesc); - virtual void AcquireSwapChainImage(); - virtual void EndView(int viewIndex); - virtual void EndFrame(); - - int GetCombinedSwapChainWidth() const { return _combinedSwapChainWidth; } - int GetCombinedSwapChainHeight() const { return _combinedSwapChainHeight; } - - RPHandle GetRenderPassHandle() const; - FBHandle GetFramebufferHandle() const; - - Math::RcPose GetAreaSpaceHeadPose() const { return _areaSpaceHeadPose; } - Math::RcPose GetWorldSpaceHeadPose() const { return _worldSpaceHeadPose; } - - // - virtual void BeginAreaUpdate(); - virtual void EndAreaUpdate(PcVector4 pUserOffset = nullptr); - float GetUserHeight() const { return _userHeight; } - void SetUserHeight(float height); - float GetAreaYaw() const { return _areaYaw; } - void SetAreaYaw(float yaw); - RcPoint3 GetAreaOrigin() const { return _areaOrigin; } - void SetAreaOrigin(RcPoint3 origin); - void MoveAreaBy(RcVector3 offset); - void TurnAreaBy(float angle); - RcVector4 GetAreaSpaceUserOffset() const { return _areaSpaceUserOffset; } - void TeleportUserTo(RcPoint3 pos, float yaw); - void UpdateAreaTransform(); - void AreaSpacePoseToWorldSpacePose(Math::RPose pose); - // + XrAction _handle = XR_NULL_HANDLE; + Vector _vSubactionPaths; + Vector _vActionSpaces; }; - VERUS_TYPEDEFS(BaseExtReality); - } + VERUS_TYPEDEFS(ActionEx); + + protected: + Math::Pose _areaSpaceHeadPose; + Math::Pose _worldSpaceHeadPose; + Math::Pose _areaPose; // In world space. + Transform3 _trAreaToWorld = Transform3::identity(); + Point3 _areaOrigin = Point3(0); + Vector4 _areaSpaceUserOffset = Vector4(0); // W is yaw. + XrInstance _instance = XR_NULL_HANDLE; + XrDebugUtilsMessengerEXT _debugUtilsMessenger = XR_NULL_HANDLE; + XrSystemId _systemId = XR_NULL_SYSTEM_ID; + XrSession _session = XR_NULL_HANDLE; + XrSpace _referenceSpace = XR_NULL_HANDLE; + XrSpace _headSpace = XR_NULL_HANDLE; + XrTime _predictedDisplayTime = 0; + Vector _vRequiredExtensions; + Vector _vViews; + Vector _vCompositionLayerProjectionViews; + Vector _vActionSets; + Vector _vActiveActionSets; + Vector _vActions; + XrFormFactor _formFactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY; + XrViewConfigurationType _viewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; + XrEnvironmentBlendMode _envBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; + XrSessionState _sessionState = XR_SESSION_STATE_UNKNOWN; + XrPosef _identityPose; + float _userHeight = 1.5f; + float _areaYaw = 0; + int _combinedSwapChainWidth = 0; + int _combinedSwapChainHeight = 0; + int _currentViewIndex = 0; + int _swapChainBufferCount = 0; + int _swapChainBufferIndex = 0; + RPHandle _rph; + Vector _fbh; + bool _runningSession = false; + bool _shouldRender = false; + bool _areaUpdated = false; + + BaseExtReality(); + virtual ~BaseExtReality(); + + public: + virtual void Init(); + virtual void Done(); + + protected: + static XRAPI_ATTR XrBool32 XRAPI_CALL DebugUtilsMessengerCallback( + XrDebugUtilsMessageSeverityFlagsEXT messageSeverityFlags, + XrDebugUtilsMessageTypeFlagsEXT messageTypeFlags, + const XrDebugUtilsMessengerCallbackDataEXT* pCallbackData, + void* pUserData); + bool CheckRequiredExtensions() const; + void CreateInstance(); + void CreateDebugUtilsMessenger(); + void CreateReferenceSpace(); + void CreateHeadSpace(); + virtual XrSwapchain GetSwapChain(int viewIndex) = 0; + virtual void GetSwapChainSize(int viewIndex, int32_t& w, int32_t& h) = 0; + + public: + virtual void CreateActions(); + virtual void PollEvents(); + virtual void SyncActions(UINT32 activeActionSetsMask = -1); + + virtual bool GetActionStateBoolean(int actionIndex, bool& currentState, bool* pChangedState, int subaction); + virtual bool GetActionStateFloat(int actionIndex, float& currentState, bool* pChangedState, int subaction); + virtual bool GetActionStatePose(int actionIndex, bool& currentState, Math::RPose pose, int subaction); + + virtual void BeginFrame(); + virtual int LocateViews(); + virtual void BeginView(int viewIndex, RViewDesc viewDesc); + virtual void AcquireSwapChainImage(); + virtual void EndView(int viewIndex); + virtual void EndFrame(); + + int GetCombinedSwapChainWidth() const { return _combinedSwapChainWidth; } + int GetCombinedSwapChainHeight() const { return _combinedSwapChainHeight; } + + RPHandle GetRenderPassHandle() const; + FBHandle GetFramebufferHandle() const; + + Math::RcPose GetAreaSpaceHeadPose() const { return _areaSpaceHeadPose; } + Math::RcPose GetWorldSpaceHeadPose() const { return _worldSpaceHeadPose; } + + // + virtual void BeginAreaUpdate(); + virtual void EndAreaUpdate(PcVector4 pUserOffset = nullptr); + float GetUserHeight() const { return _userHeight; } + void SetUserHeight(float height); + float GetAreaYaw() const { return _areaYaw; } + void SetAreaYaw(float yaw); + RcPoint3 GetAreaOrigin() const { return _areaOrigin; } + void SetAreaOrigin(RcPoint3 origin); + void MoveAreaBy(RcVector3 offset); + void TurnAreaBy(float angle); + RcVector4 GetAreaSpaceUserOffset() const { return _areaSpaceUserOffset; } + void TeleportUserTo(RcPoint3 pos, float yaw); + void UpdateAreaTransform(); + void AreaSpacePoseToWorldSpacePose(Math::RPose pose); + // + }; + VERUS_TYPEDEFS(BaseExtReality); } diff --git a/Verus/src/CGI/BaseGeometry.h b/Verus/src/CGI/BaseGeometry.h index 7087ebf..115749e 100644 --- a/Verus/src/CGI/BaseGeometry.h +++ b/Verus/src/CGI/BaseGeometry.h @@ -1,72 +1,69 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class BaseCommandBuffer; + + struct GeometryDesc { - class BaseCommandBuffer; + CSZ _name = nullptr; + PcVertexInputAttrDesc _pVertexInputAttrDesc = nullptr; + const int* _pStrides = nullptr; + UINT32 _dynBindingsMask = 0; + bool _32BitIndices = false; + }; + VERUS_TYPEDEFS(GeometryDesc); - struct GeometryDesc - { - CSZ _name = nullptr; - PcVertexInputAttrDesc _pVertexInputAttrDesc = nullptr; - const int* _pStrides = nullptr; - UINT32 _dynBindingsMask = 0; - bool _32BitIndices = false; - }; - VERUS_TYPEDEFS(GeometryDesc); + class BaseGeometry : public Object, public Scheduled + { + protected: + String _name; + UINT32 _instBindingsMask = 0; + UINT32 _dynBindingsMask = 0; + bool _32BitIndices = false; - class BaseGeometry : public Object, public Scheduled - { - protected: - String _name; - UINT32 _instBindingsMask = 0; - UINT32 _dynBindingsMask = 0; - bool _32BitIndices = false; + BaseGeometry() = default; + virtual ~BaseGeometry() = default; - BaseGeometry() = default; - virtual ~BaseGeometry() = default; + public: + virtual void Init(RcGeometryDesc desc) = 0; + virtual void Done() = 0; - public: - virtual void Init(RcGeometryDesc desc) = 0; - virtual void Done() = 0; + virtual void CreateVertexBuffer(int count, int binding) = 0; + virtual void UpdateVertexBuffer(const void* p, int binding, BaseCommandBuffer* pCB = nullptr, INT64 size = 0, INT64 offset = 0) = 0; - virtual void CreateVertexBuffer(int count, int binding) = 0; - virtual void UpdateVertexBuffer(const void* p, int binding, BaseCommandBuffer* pCB = nullptr, INT64 size = 0, INT64 offset = 0) = 0; + virtual void CreateIndexBuffer(int count) = 0; + virtual void UpdateIndexBuffer(const void* p, BaseCommandBuffer* pCB = nullptr, INT64 size = 0, INT64 offset = 0) = 0; - virtual void CreateIndexBuffer(int count) = 0; - virtual void UpdateIndexBuffer(const void* p, BaseCommandBuffer* pCB = nullptr, INT64 size = 0, INT64 offset = 0) = 0; + virtual void CreateStorageBuffer(int count, int structSize, int sbIndex, ShaderStageFlags stageFlags) = 0; + virtual void UpdateStorageBuffer(const void* p, int sbIndex, BaseCommandBuffer* pCB = nullptr, INT64 size = 0, INT64 offset = 0) = 0; + virtual int GetStorageBufferStructSize(int sbIndex) const = 0; - virtual void CreateStorageBuffer(int count, int structSize, int sbIndex, ShaderStageFlags stageFlags) = 0; - virtual void UpdateStorageBuffer(const void* p, int sbIndex, BaseCommandBuffer* pCB = nullptr, INT64 size = 0, INT64 offset = 0) = 0; - virtual int GetStorageBufferStructSize(int sbIndex) const = 0; + static int GetVertexInputAttrDescCount(PcVertexInputAttrDesc p); + static int GetBindingCount(PcVertexInputAttrDesc p); - static int GetVertexInputAttrDescCount(PcVertexInputAttrDesc p); - static int GetBindingCount(PcVertexInputAttrDesc p); + bool Has32BitIndices() const { return _32BitIndices; } + }; + VERUS_TYPEDEFS(BaseGeometry); - bool Has32BitIndices() const { return _32BitIndices; } - }; - VERUS_TYPEDEFS(BaseGeometry); + class GeometryPtr : public Ptr + { + public: + void Init(RcGeometryDesc desc); + }; + VERUS_TYPEDEFS(GeometryPtr); - class GeometryPtr : public Ptr - { - public: - void Init(RcGeometryDesc desc); - }; - VERUS_TYPEDEFS(GeometryPtr); + class GeometryPwn : public GeometryPtr + { + public: + ~GeometryPwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(GeometryPwn); - class GeometryPwn : public GeometryPtr - { - public: - ~GeometryPwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(GeometryPwn); - - template - class GeometryPwns : public Pwns - { - }; - } + template + class GeometryPwns : public Pwns + { + }; } diff --git a/Verus/src/CGI/BasePipeline.h b/Verus/src/CGI/BasePipeline.h index 3f13791..68cc074 100644 --- a/Verus/src/CGI/BasePipeline.h +++ b/Verus/src/CGI/BasePipeline.h @@ -1,92 +1,89 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + struct PipelineDesc { - struct PipelineDesc + GeometryPtr _geometry; + ShaderPtr _shader; + CSZ _shaderBranch = nullptr; + String _colorAttachBlendEqs[VERUS_MAX_CA]; + String _colorAttachWriteMasks[VERUS_MAX_CA]; + PipelineRasterizationState _rasterizationState; + PrimitiveTopology _topology = PrimitiveTopology::triangleList; + int _sampleCount = 1; + RPHandle _renderPassHandle; + int _subpass = 0; + UINT32 _vertexInputBindingsFilter = UINT32_MAX; + CompareOp _depthCompareOp = CompareOp::less; + bool _depthTestEnable = true; + bool _depthWriteEnable = true; + bool _stencilTestEnable = false; + bool _primitiveRestartEnable = false; // Special index value is 0xFFFFFFFF for 32-bit and 0xFFFF for 16-bit indices. + bool _compute = false; // Compute pipeline, use PipelineDesc(ShaderPtr, CSZ) to set this to true. + + // What to draw (geo)? How to draw (shader)? Where to draw (render pass)? + PipelineDesc(GeometryPtr geo, ShaderPtr shader, CSZ branch, RPHandle renderPassHandle, int subpass = 0) : + _geometry(geo), _shader(shader), _shaderBranch(branch), _renderPassHandle(renderPassHandle), _subpass(subpass) { - GeometryPtr _geometry; - ShaderPtr _shader; - CSZ _shaderBranch = nullptr; - String _colorAttachBlendEqs[VERUS_MAX_CA]; - String _colorAttachWriteMasks[VERUS_MAX_CA]; - PipelineRasterizationState _rasterizationState; - PrimitiveTopology _topology = PrimitiveTopology::triangleList; - int _sampleCount = 1; - RPHandle _renderPassHandle; - int _subpass = 0; - UINT32 _vertexInputBindingsFilter = UINT32_MAX; - CompareOp _depthCompareOp = CompareOp::less; - bool _depthTestEnable = true; - bool _depthWriteEnable = true; - bool _stencilTestEnable = false; - bool _primitiveRestartEnable = false; // Special index value is 0xFFFFFFFF for 32-bit and 0xFFFF for 16-bit indices. - bool _compute = false; // Compute pipeline, use PipelineDesc(ShaderPtr, CSZ) to set this to true. + _colorAttachBlendEqs[0] = VERUS_COLOR_BLEND_OFF; + VERUS_FOR(i, VERUS_COUNT_OF(_colorAttachWriteMasks)) + _colorAttachWriteMasks[i] = "rgba"; + } + PipelineDesc(ShaderPtr shader, CSZ branch) : + _shader(shader), _shaderBranch(branch), _compute(true) {} - // What to draw (geo)? How to draw (shader)? Where to draw (render pass)? - PipelineDesc(GeometryPtr geo, ShaderPtr shader, CSZ branch, RPHandle renderPassHandle, int subpass = 0) : - _geometry(geo), _shader(shader), _shaderBranch(branch), _renderPassHandle(renderPassHandle), _subpass(subpass) - { - _colorAttachBlendEqs[0] = VERUS_COLOR_BLEND_OFF; - VERUS_FOR(i, VERUS_COUNT_OF(_colorAttachWriteMasks)) - _colorAttachWriteMasks[i] = "rgba"; - } - PipelineDesc(ShaderPtr shader, CSZ branch) : - _shader(shader), _shaderBranch(branch), _compute(true) {} - - void DisableDepthTest() - { - _depthTestEnable = false; - _depthWriteEnable = false; - } - - void EnableDepthBias() - { - _rasterizationState._depthBiasEnable = true; - _rasterizationState._depthBiasConstantFactor = 14; - _rasterizationState._depthBiasSlopeFactor = 1.1f; - if (App::Settings::I()._sceneShadowQuality >= App::Settings::Quality::high) - _rasterizationState._depthBiasConstantFactor = 50; - } - }; - VERUS_TYPEDEFS(PipelineDesc); - - class BasePipeline : public Object, public Scheduled + void DisableDepthTest() { - protected: - UINT32 _vertexInputBindingsFilter = UINT32_MAX; + _depthTestEnable = false; + _depthWriteEnable = false; + } - BasePipeline() = default; - virtual ~BasePipeline() = default; - - public: - virtual void Init(RcPipelineDesc desc) = 0; - virtual void Done() = 0; - - UINT32 GetVertexInputBindingsFilter() const { return _vertexInputBindingsFilter; } - }; - VERUS_TYPEDEFS(BasePipeline); - - class PipelinePtr : public Ptr + void EnableDepthBias() { - public: - void Init(RcPipelineDesc desc); - }; - VERUS_TYPEDEFS(PipelinePtr); + _rasterizationState._depthBiasEnable = true; + _rasterizationState._depthBiasConstantFactor = 14; + _rasterizationState._depthBiasSlopeFactor = 1.1f; + if (App::Settings::I()._sceneShadowQuality >= App::Settings::Quality::high) + _rasterizationState._depthBiasConstantFactor = 50; + } + }; + VERUS_TYPEDEFS(PipelineDesc); - class PipelinePwn : public PipelinePtr - { - public: - ~PipelinePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(PipelinePwn); + class BasePipeline : public Object, public Scheduled + { + protected: + UINT32 _vertexInputBindingsFilter = UINT32_MAX; - template - class PipelinePwns : public Pwns - { - }; - } + BasePipeline() = default; + virtual ~BasePipeline() = default; + + public: + virtual void Init(RcPipelineDesc desc) = 0; + virtual void Done() = 0; + + UINT32 GetVertexInputBindingsFilter() const { return _vertexInputBindingsFilter; } + }; + VERUS_TYPEDEFS(BasePipeline); + + class PipelinePtr : public Ptr + { + public: + void Init(RcPipelineDesc desc); + }; + VERUS_TYPEDEFS(PipelinePtr); + + class PipelinePwn : public PipelinePtr + { + public: + ~PipelinePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(PipelinePwn); + + template + class PipelinePwns : public Pwns + { + }; } diff --git a/Verus/src/CGI/BaseRenderer.h b/Verus/src/CGI/BaseRenderer.h index 323a0f3..46ac5ea 100644 --- a/Verus/src/CGI/BaseRenderer.h +++ b/Verus/src/CGI/BaseRenderer.h @@ -1,113 +1,110 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + enum class Gapi : int { - enum class Gapi : int + unknown, + vulkan, + direct3D11, + direct3D12 + }; + + struct BaseRendererDesc + { + GlobalVarsClipboard _gvc; + + BaseRendererDesc() { - unknown, - vulkan, - direct3D11, - direct3D12 - }; + _gvc.Copy(); + } + }; + VERUS_TYPEDEFS(BaseRendererDesc); - struct BaseRendererDesc - { - GlobalVarsClipboard _gvc; + class BaseRenderer : public Object + { + protected: + Vector _vScheduled; + BaseRendererDesc _desc; + int _swapChainBufferCount = 0; + int _swapChainBufferIndex = 0; + int _ringBufferIndex = 0; - BaseRendererDesc() - { - _gvc.Copy(); - } - }; - VERUS_TYPEDEFS(BaseRendererDesc); + BaseRenderer(); + virtual ~BaseRenderer(); - class BaseRenderer : public Object - { - protected: - Vector _vScheduled; - BaseRendererDesc _desc; - int _swapChainBufferCount = 0; - int _swapChainBufferIndex = 0; - int _ringBufferIndex = 0; + public: + static const int s_ringBufferSize = 3; - BaseRenderer(); - virtual ~BaseRenderer(); + static BaseRenderer* Load(CSZ dll, RBaseRendererDesc desc); + virtual void ReleaseMe() = 0; - public: - static const int s_ringBufferSize = 3; + void SetDesc(RBaseRendererDesc desc) { _desc = desc; } - static BaseRenderer* Load(CSZ dll, RBaseRendererDesc desc); - virtual void ReleaseMe() = 0; + int GetSwapChainBufferCount() const { return _swapChainBufferCount; } + int GetSwapChainBufferIndex() const { return _swapChainBufferIndex; } + int GetRingBufferIndex() const { return _ringBufferIndex; } - void SetDesc(RBaseRendererDesc desc) { _desc = desc; } + void Schedule(PScheduled p); + void Unschedule(PScheduled p); + void UpdateScheduled(); - int GetSwapChainBufferCount() const { return _swapChainBufferCount; } - int GetSwapChainBufferIndex() const { return _swapChainBufferIndex; } - int GetRingBufferIndex() const { return _ringBufferIndex; } + virtual void ImGuiInit(RPHandle renderPassHandle) = 0; + virtual void ImGuiRenderDrawData() = 0; - void Schedule(PScheduled p); - void Unschedule(PScheduled p); - void UpdateScheduled(); + virtual void ResizeSwapChain() = 0; - virtual void ImGuiInit(RPHandle renderPassHandle) = 0; - virtual void ImGuiRenderDrawData() = 0; + virtual PBaseExtReality GetExtReality() { return nullptr; } - virtual void ResizeSwapChain() = 0; + // Which graphics API? + virtual Gapi GetGapi() = 0; - virtual PBaseExtReality GetExtReality() { return nullptr; } + // + virtual void BeginFrame() = 0; + virtual void AcquireSwapChainImage() = 0; + virtual void EndFrame() = 0; + virtual void WaitIdle() = 0; + virtual void OnMinimized() = 0; + // - // Which graphics API? - virtual Gapi GetGapi() = 0; + // + virtual PBaseCommandBuffer InsertCommandBuffer() = 0; + virtual PBaseGeometry InsertGeometry() = 0; + virtual PBasePipeline InsertPipeline() = 0; + virtual PBaseShader InsertShader() = 0; + virtual PBaseTexture InsertTexture() = 0; - // - virtual void BeginFrame() = 0; - virtual void AcquireSwapChainImage() = 0; - virtual void EndFrame() = 0; - virtual void WaitIdle() = 0; - virtual void OnMinimized() = 0; - // + virtual void DeleteCommandBuffer(PBaseCommandBuffer p) = 0; + virtual void DeleteGeometry(PBaseGeometry p) = 0; + virtual void DeletePipeline(PBasePipeline p) = 0; + virtual void DeleteShader(PBaseShader p) = 0; + virtual void DeleteTexture(PBaseTexture p) = 0; - // - virtual PBaseCommandBuffer InsertCommandBuffer() = 0; - virtual PBaseGeometry InsertGeometry() = 0; - virtual PBasePipeline InsertPipeline() = 0; - virtual PBaseShader InsertShader() = 0; - virtual PBaseTexture InsertTexture() = 0; + RPHandle CreateSimpleRenderPass(Format format, RP::Attachment::LoadOp loadOp = RP::Attachment::LoadOp::dontCare, ImageLayout layout = ImageLayout::fsReadOnly); + RPHandle CreateShadowRenderPass(Format format, RP::Attachment::LoadOp loadOp = RP::Attachment::LoadOp::clear); + virtual RPHandle CreateRenderPass(std::initializer_list ilA, std::initializer_list ilS, std::initializer_list ilD) = 0; + virtual FBHandle CreateFramebuffer(RPHandle renderPassHandle, std::initializer_list il, int w, int h, + int swapChainBufferIndex = -1, CubeMapFace cubeMapFace = CubeMapFace::none) = 0; + virtual void DeleteRenderPass(RPHandle handle) = 0; + virtual void DeleteFramebuffer(FBHandle handle) = 0; + // - virtual void DeleteCommandBuffer(PBaseCommandBuffer p) = 0; - virtual void DeleteGeometry(PBaseGeometry p) = 0; - virtual void DeletePipeline(PBasePipeline p) = 0; - virtual void DeleteShader(PBaseShader p) = 0; - virtual void DeleteTexture(PBaseTexture p) = 0; + static void SetAlphaBlendHelper( + CSZ sz, + int& colorBlendOp, + int& alphaBlendOp, + int& srcColorBlendFactor, + int& dstColorBlendFactor, + int& srcAlphaBlendFactor, + int& dstAlphaBlendFactor); - RPHandle CreateSimpleRenderPass(Format format, RP::Attachment::LoadOp loadOp = RP::Attachment::LoadOp::dontCare, ImageLayout layout = ImageLayout::fsReadOnly); - RPHandle CreateShadowRenderPass(Format format, RP::Attachment::LoadOp loadOp = RP::Attachment::LoadOp::clear); - virtual RPHandle CreateRenderPass(std::initializer_list ilA, std::initializer_list ilS, std::initializer_list ilD) = 0; - virtual FBHandle CreateFramebuffer(RPHandle renderPassHandle, std::initializer_list il, int w, int h, - int swapChainBufferIndex = -1, CubeMapFace cubeMapFace = CubeMapFace::none) = 0; - virtual void DeleteRenderPass(RPHandle handle) = 0; - virtual void DeleteFramebuffer(FBHandle handle) = 0; - // - - static void SetAlphaBlendHelper( - CSZ sz, - int& colorBlendOp, - int& alphaBlendOp, - int& srcColorBlendFactor, - int& dstColorBlendFactor, - int& srcAlphaBlendFactor, - int& dstAlphaBlendFactor); - - virtual void UpdateUtilization() {} - }; - VERUS_TYPEDEFS(BaseRenderer); - } + virtual void UpdateUtilization() {} + }; + VERUS_TYPEDEFS(BaseRenderer); extern "C" { - typedef CGI::PBaseRenderer(*PFNCREATERENDERER)(UINT32 version, CGI::BaseRendererDesc* pDesc); + typedef PBaseRenderer(*PFNCREATERENDERER)(UINT32 version, BaseRendererDesc* pDesc); } } diff --git a/Verus/src/CGI/BaseShader.h b/Verus/src/CGI/BaseShader.h index 19ae4f1..a6977dd 100644 --- a/Verus/src/CGI/BaseShader.h +++ b/Verus/src/CGI/BaseShader.h @@ -1,103 +1,100 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + struct ShaderDesc { - struct ShaderDesc + CSZ _url = nullptr; + CSZ _source = nullptr; + CSZ* _branches = nullptr; + CSZ* _ignoreList = nullptr; + CSZ _userDefines = nullptr; + bool _saveCompiled = false; + + ShaderDesc(CSZ url = nullptr) : _url(url) {} + }; + VERUS_TYPEDEFS(ShaderDesc); + + class BaseShader : public Object, public Scheduled + { + static CSZ s_branchCommentMarker; + + public: + enum class Stage : int { - CSZ _url = nullptr; - CSZ _source = nullptr; - CSZ* _branches = nullptr; - CSZ* _ignoreList = nullptr; - CSZ _userDefines = nullptr; - bool _saveCompiled = false; - - ShaderDesc(CSZ url = nullptr) : _url(url) {} + vs, // Vertex shader + hs, // Tessellation control shader (Hull shader) + ds, // Tessellation evaluation shader (Domain shader) + gs, // Geometry shader + fs, // Fragment shader (Pixel shader) + cs, // Compute Shader + count }; - VERUS_TYPEDEFS(ShaderDesc); - class BaseShader : public Object, public Scheduled - { - static CSZ s_branchCommentMarker; + protected: + String _sourceName; + CSZ* _ignoreList = nullptr; + CSZ _userDefines = nullptr; + bool _saveCompiled = false; - public: - enum class Stage : int - { - vs, // Vertex shader - hs, // Tessellation control shader (Hull shader) - ds, // Tessellation evaluation shader (Domain shader) - gs, // Geometry shader - fs, // Fragment shader (Pixel shader) - cs, // Compute Shader - count - }; + BaseShader() = default; + virtual ~BaseShader() = default; - protected: - String _sourceName; - CSZ* _ignoreList = nullptr; - CSZ _userDefines = nullptr; - bool _saveCompiled = false; + public: + virtual void Init(CSZ source, CSZ sourceName, CSZ* branches) = 0; + virtual void Done() = 0; - BaseShader() = default; - virtual ~BaseShader() = default; + void Load(CSZ url); + static String Parse( + CSZ branchDesc, + RString entry, + String stageEntries[], + RString stages, + Vector& vMacroName, + Vector& vMacroValue, + CSZ prefix); + static void TestParse(); - public: - virtual void Init(CSZ source, CSZ sourceName, CSZ* branches) = 0; - virtual void Done() = 0; + virtual void CreateDescriptorSet(int setNumber, const void* pSrc, int size, + int capacity = 1, std::initializer_list il = {}, ShaderStageFlags stageFlags = ShaderStageFlags::vs_fs) = 0; + virtual void CreatePipelineLayout() = 0; + virtual CSHandle BindDescriptorSetTextures(int setNumber, std::initializer_list il, + const int* pMipLevels = nullptr, const int* pArrayLayers = nullptr) = 0; + virtual void FreeDescriptorSet(CSHandle& complexSetHandle) = 0; - void Load(CSZ url); - static String Parse( - CSZ branchDesc, - RString entry, - String stageEntries[], - RString stages, - Vector& vMacroName, - Vector& vMacroValue, - CSZ prefix); - static void TestParse(); + virtual void BeginBindDescriptors() = 0; + virtual void EndBindDescriptors() = 0; - virtual void CreateDescriptorSet(int setNumber, const void* pSrc, int size, - int capacity = 1, std::initializer_list il = {}, ShaderStageFlags stageFlags = ShaderStageFlags::vs_fs) = 0; - virtual void CreatePipelineLayout() = 0; - virtual CSHandle BindDescriptorSetTextures(int setNumber, std::initializer_list il, - const int* pMipLevels = nullptr, const int* pArrayLayers = nullptr) = 0; - virtual void FreeDescriptorSet(CSHandle& complexSetHandle) = 0; + Str GetSourceName() const { return _C(_sourceName); } - virtual void BeginBindDescriptors() = 0; - virtual void EndBindDescriptors() = 0; + void SetIgnoreList(CSZ* list) { _ignoreList = list; } + bool IsInIgnoreList(CSZ name) const; - Str GetSourceName() const { return _C(_sourceName); } + void SetUserDefines(CSZ def) { _userDefines = def; } - void SetIgnoreList(CSZ* list) { _ignoreList = list; } - bool IsInIgnoreList(CSZ name) const; + void SetSaveCompiled(bool b) { _saveCompiled = b; } + static void SaveCompiled(CSZ code, CSZ filename); + }; + VERUS_TYPEDEFS(BaseShader); - void SetUserDefines(CSZ def) { _userDefines = def; } + class ShaderPtr : public Ptr + { + public: + void Init(RcShaderDesc desc); + }; + VERUS_TYPEDEFS(ShaderPtr); - void SetSaveCompiled(bool b) { _saveCompiled = b; } - static void SaveCompiled(CSZ code, CSZ filename); - }; - VERUS_TYPEDEFS(BaseShader); + class ShaderPwn : public ShaderPtr + { + public: + ~ShaderPwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(ShaderPwn); - class ShaderPtr : public Ptr - { - public: - void Init(RcShaderDesc desc); - }; - VERUS_TYPEDEFS(ShaderPtr); - - class ShaderPwn : public ShaderPtr - { - public: - ~ShaderPwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(ShaderPwn); - - template - class ShaderPwns : public Pwns - { - }; - } + template + class ShaderPwns : public Pwns + { + }; } diff --git a/Verus/src/CGI/BaseTexture.h b/Verus/src/CGI/BaseTexture.h index 0fc55ff..8d68112 100644 --- a/Verus/src/CGI/BaseTexture.h +++ b/Verus/src/CGI/BaseTexture.h @@ -1,156 +1,153 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + struct SamplerDesc { - struct SamplerDesc + Vector4 _borderColor = Vector4(0); + char _filterMagMinMip[4]; + char _addressModeUVW[4]; + float _mipLodBias = 0; + float _minLod = 0; + float _maxLod = 15; + + SamplerDesc() { - Vector4 _borderColor = Vector4(0); - char _filterMagMinMip[4]; - char _addressModeUVW[4]; - float _mipLodBias = 0; - float _minLod = 0; - float _maxLod = 15; + VERUS_ZERO_MEM(_filterMagMinMip); + VERUS_ZERO_MEM(_addressModeUVW); + } - SamplerDesc() - { - VERUS_ZERO_MEM(_filterMagMinMip); - VERUS_ZERO_MEM(_addressModeUVW); - } + void SetFilter(CSZ f) { strcpy(_filterMagMinMip, f); } + void SetAddressMode(CSZ a) { strcpy(_addressModeUVW, a); } + void Set(CSZ f, CSZ a) { SetFilter(f); SetAddressMode(a); } + }; + VERUS_TYPEDEFS(SamplerDesc); - void SetFilter(CSZ f) { strcpy(_filterMagMinMip, f); } - void SetAddressMode(CSZ a) { strcpy(_addressModeUVW, a); } - void Set(CSZ f, CSZ a) { SetFilter(f); SetAddressMode(a); } - }; - VERUS_TYPEDEFS(SamplerDesc); - - struct TextureDesc + struct TextureDesc + { + enum class Flags : UINT32 { - enum class Flags : UINT32 - { - none = 0, - colorAttachment = (1 << 0), // Texture can be used as a render target. - inputAttachment = (1 << 1), // Texture can be used as an input attachment in a framebuffer (optimization for tiled rendering). - depthSampledR = (1 << 2), // Depth can be sampled in a shader, initial layout will be depthStencilReadOnly. - depthSampledW = (1 << 3), // Depth can be sampled in a shader, initial layout will be depthStencilAttachment. - anyShaderResource = (1 << 4), // Will use xsReadOnly as main layout (any shader can sample this texture). - generateMips = (1 << 5), // Allows GenerateMips calls. Not compatible with BGRA format on some systems. - forceArrayTexture = (1 << 6), // Create array texture even if arrayLayers=1. - sync = (1 << 7), // Load image data synchronously. - exposureMips = (1 << 8), // Internal flag for automatic exposure. - cubeMap = (1 << 9) - }; - - Vector4 _clearValue = Vector4(0); - PcSamplerDesc _pSamplerDesc = nullptr; - CSZ _name = nullptr; - CSZ _url = nullptr; - CSZ* _urls = nullptr; - Format _format = Format::unormR8G8B8A8; - int _width = 0; - int _height = 0; - short _depth = 1; - short _mipLevels = 1; - short _arrayLayers = 1; - short _sampleCount = 1; - Flags _flags = Flags::none; - short _texturePart = 0; - short _readbackMip = SHRT_MAX; // -1 means the smallest one, SHRT_MAX means readback is disabled. - - TextureDesc(CSZ url = nullptr) : _url(url) {} - - void Reset(int w = 0, int h = 0, Format format = Format::unormR8G8B8A8) - { - *this = TextureDesc(); - _format = format; - _width = w; - _height = h; - } + none = 0, + colorAttachment = (1 << 0), // Texture can be used as a render target. + inputAttachment = (1 << 1), // Texture can be used as an input attachment in a framebuffer (optimization for tiled rendering). + depthSampledR = (1 << 2), // Depth can be sampled in a shader, initial layout will be depthStencilReadOnly. + depthSampledW = (1 << 3), // Depth can be sampled in a shader, initial layout will be depthStencilAttachment. + anyShaderResource = (1 << 4), // Will use xsReadOnly as main layout (any shader can sample this texture). + generateMips = (1 << 5), // Allows GenerateMips calls. Not compatible with BGRA format on some systems. + forceArrayTexture = (1 << 6), // Create array texture even if arrayLayers=1. + sync = (1 << 7), // Load image data synchronously. + exposureMips = (1 << 8), // Internal flag for automatic exposure. + cubeMap = (1 << 9) }; - VERUS_TYPEDEFS(TextureDesc); - class BaseTexture : public Object, public IO::AsyncDelegate, public Scheduled + Vector4 _clearValue = Vector4(0); + PcSamplerDesc _pSamplerDesc = nullptr; + CSZ _name = nullptr; + CSZ _url = nullptr; + CSZ* _urls = nullptr; + Format _format = Format::unormR8G8B8A8; + int _width = 0; + int _height = 0; + short _depth = 1; + short _mipLevels = 1; + short _arrayLayers = 1; + short _sampleCount = 1; + Flags _flags = Flags::none; + short _texturePart = 0; + short _readbackMip = SHRT_MAX; // -1 means the smallest one, SHRT_MAX means readback is disabled. + + TextureDesc(CSZ url = nullptr) : _url(url) {} + + void Reset(int w = 0, int h = 0, Format format = Format::unormR8G8B8A8) { - protected: - Vector4 _size = Vector4(0); - String _name; - TextureDesc _desc; - UINT64 _initAtFrame = 0; - ImageLayout _mainLayout = ImageLayout::fsReadOnly; - int _part = 0; - int _bytesPerPixel = 0; + *this = TextureDesc(); + _format = format; + _width = w; + _height = h; + } + }; + VERUS_TYPEDEFS(TextureDesc); - BaseTexture(); - virtual ~BaseTexture(); + class BaseTexture : public Object, public IO::AsyncDelegate, public Scheduled + { + protected: + Vector4 _size = Vector4(0); + String _name; + TextureDesc _desc; + UINT64 _initAtFrame = 0; + ImageLayout _mainLayout = ImageLayout::fsReadOnly; + int _part = 0; + int _bytesPerPixel = 0; - public: - virtual void Init(RcTextureDesc desc) = 0; - virtual void Done() = 0; + BaseTexture(); + virtual ~BaseTexture(); - bool IsLoaded() const { return _desc._width != 0; } - Str GetName() const { return _C(_name); } + public: + virtual void Init(RcTextureDesc desc) = 0; + virtual void Done() = 0; - RcTextureDesc GetDesc() const { return _desc; } - RcVector4 GetClearValue() const { return _desc._clearValue; } - Format GetFormat() const { return _desc._format; } - int GetWidth() const { return _desc._width; } - int GetHeight() const { return _desc._height; } - int GetDepth() const { return _desc._depth; } - int GetMipLevelCount() const { return _desc._mipLevels; } - int GetArrayLayerCount() const { return _desc._arrayLayers; } + bool IsLoaded() const { return _desc._width != 0; } + Str GetName() const { return _C(_name); } - int GetPart() const { return _part; } - RcVector4 GetSize() const { return _size; } - bool IsSRGB() const; - Format ToTextureBcFormat(IO::RcDDSHeader header, IO::RcDDSHeaderDXT10 header10) const; + RcTextureDesc GetDesc() const { return _desc; } + RcVector4 GetClearValue() const { return _desc._clearValue; } + Format GetFormat() const { return _desc._format; } + int GetWidth() const { return _desc._width; } + int GetHeight() const { return _desc._height; } + int GetDepth() const { return _desc._depth; } + int GetMipLevelCount() const { return _desc._mipLevels; } + int GetArrayLayerCount() const { return _desc._arrayLayers; } - void SetLoadingFlags(TextureDesc::Flags flags) { _desc._flags = flags; } - void SetLoadingSamplerDesc(PcSamplerDesc pSamplerDesc) { _desc._pSamplerDesc = pSamplerDesc; } + int GetPart() const { return _part; } + RcVector4 GetSize() const { return _size; } + bool IsSRGB() const; + Format ToTextureBcFormat(IO::RcDDSHeader header, IO::RcDDSHeaderDXT10 header10) const; - void LoadDDS(CSZ url, int texturePart = 0); - void LoadDDS(CSZ url, RcBlob blob); - void LoadDDSArray(CSZ* urls); + void SetLoadingFlags(TextureDesc::Flags flags) { _desc._flags = flags; } + void SetLoadingSamplerDesc(PcSamplerDesc pSamplerDesc) { _desc._pSamplerDesc = pSamplerDesc; } - virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; + void LoadDDS(CSZ url, int texturePart = 0); + void LoadDDS(CSZ url, RcBlob blob); + void LoadDDSArray(CSZ* urls); - virtual void UpdateSubresource(const void* p, int mipLevel = 0, int arrayLayer = 0, BaseCommandBuffer* pCB = nullptr) = 0; - virtual bool ReadbackSubresource(void* p, bool recordCopyCommand = true, BaseCommandBuffer* pCB = nullptr) = 0; + virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; - virtual void GenerateMips(BaseCommandBuffer* pCB = nullptr) = 0; + virtual void UpdateSubresource(const void* p, int mipLevel = 0, int arrayLayer = 0, BaseCommandBuffer* pCB = nullptr) = 0; + virtual bool ReadbackSubresource(void* p, bool recordCopyCommand = true, BaseCommandBuffer* pCB = nullptr) = 0; - static int FormatToBytesPerPixel(Format format); - static bool IsSRGBFormat(Format format); - static bool IsBC(Format format); - static bool Is4BitsBC(Format format); - static bool IsDepthFormat(Format format); - }; - VERUS_TYPEDEFS(BaseTexture); + virtual void GenerateMips(BaseCommandBuffer* pCB = nullptr) = 0; - class TexturePtr : public Ptr - { - public: - TexturePtr() = default; - TexturePtr(nullptr_t) : Ptr(nullptr) {} + static int FormatToBytesPerPixel(Format format); + static bool IsSRGBFormat(Format format); + static bool IsBC(Format format); + static bool Is4BitsBC(Format format); + static bool IsDepthFormat(Format format); + }; + VERUS_TYPEDEFS(BaseTexture); - void Init(RcTextureDesc desc); + class TexturePtr : public Ptr + { + public: + TexturePtr() = default; + TexturePtr(nullptr_t) : Ptr(nullptr) {} - static TexturePtr From(PBaseTexture p); - }; - VERUS_TYPEDEFS(TexturePtr); + void Init(RcTextureDesc desc); - class TexturePwn : public TexturePtr - { - public: - ~TexturePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(TexturePwn); + static TexturePtr From(PBaseTexture p); + }; + VERUS_TYPEDEFS(TexturePtr); - template - class TexturePwns : public Pwns - { - }; - } + class TexturePwn : public TexturePtr + { + public: + ~TexturePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(TexturePwn); + + template + class TexturePwns : public Pwns + { + }; } diff --git a/Verus/src/CGI/DebugDraw.h b/Verus/src/CGI/DebugDraw.h index 2af512c..fde1118 100644 --- a/Verus/src/CGI/DebugDraw.h +++ b/Verus/src/CGI/DebugDraw.h @@ -1,77 +1,74 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class DebugDraw : public Singleton, public Object { - class DebugDraw : public Singleton, public Object - { #include "../Shaders/DebugDraw.inc.hlsl" - enum PIPE - { - PIPE_POINTS, - PIPE_POINTS_NO_Z, - PIPE_LINES, - PIPE_LINES_NO_Z, - PIPE_POLY, - PIPE_POLY_NO_Z, - PIPE_COUNT - }; - - public: - enum class Type : int - { - points, - lines, - poly - }; - - private: - struct Vertex - { - float _pos[3]; - BYTE _color[4]; - }; - - static UB_DebugDraw s_ubDebugDraw; - - GeometryPwn _geo; - ShaderPwn _shader; - PipelinePwns _pipe; - Vector _vDynamicBuffer; - UINT64 _currentFrame = UINT64_MAX; - const int _maxVerts = 0x10000; - int _vertCount = 0; - int _offset = 0; - int _peakLoad = 0; - Type _type = Type::points; - - public: - DebugDraw(); - ~DebugDraw(); - - void Init(); - void Done(); - - void Begin(Type type, PcTransform3 pMat = nullptr, bool zEnable = true); - void End(); - - bool AddPoint( - RcPoint3 pos, - UINT32 color); - bool AddLine( - RcPoint3 posA, - RcPoint3 posB, - UINT32 colorA, - UINT32 colorB = 0); - bool AddTriangle( - RcPoint3 posA, - RcPoint3 posB, - RcPoint3 posC, - UINT32 color); + enum PIPE + { + PIPE_POINTS, + PIPE_POINTS_NO_Z, + PIPE_LINES, + PIPE_LINES_NO_Z, + PIPE_POLY, + PIPE_POLY_NO_Z, + PIPE_COUNT }; - VERUS_TYPEDEFS(DebugDraw); - } + + public: + enum class Type : int + { + points, + lines, + poly + }; + + private: + struct Vertex + { + float _pos[3]; + BYTE _color[4]; + }; + + static UB_DebugDraw s_ubDebugDraw; + + GeometryPwn _geo; + ShaderPwn _shader; + PipelinePwns _pipe; + Vector _vDynamicBuffer; + UINT64 _currentFrame = UINT64_MAX; + const int _maxVerts = 0x10000; + int _vertCount = 0; + int _offset = 0; + int _peakLoad = 0; + Type _type = Type::points; + + public: + DebugDraw(); + ~DebugDraw(); + + void Init(); + void Done(); + + void Begin(Type type, PcTransform3 pMat = nullptr, bool zEnable = true); + void End(); + + bool AddPoint( + RcPoint3 pos, + UINT32 color); + bool AddLine( + RcPoint3 posA, + RcPoint3 posB, + UINT32 colorA, + UINT32 colorB = 0); + bool AddTriangle( + RcPoint3 posA, + RcPoint3 posB, + RcPoint3 posC, + UINT32 color); + }; + VERUS_TYPEDEFS(DebugDraw); } diff --git a/Verus/src/CGI/DeferredShading.h b/Verus/src/CGI/DeferredShading.h index 97a493f..e7fd603 100644 --- a/Verus/src/CGI/DeferredShading.h +++ b/Verus/src/CGI/DeferredShading.h @@ -1,20 +1,18 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + enum class LightType : int { - enum class LightType : int - { - none, - dir, - omni, - spot - }; + none, + dir, + omni, + spot + }; - class DeferredShading : public Object - { + class DeferredShading : public Object + { #include "../Shaders/DS.inc.hlsl" #include "../Shaders/DS_Ambient.inc.hlsl" #include "../Shaders/DS_AmbientNode.inc.hlsl" @@ -23,207 +21,206 @@ namespace verus #include "../Shaders/DS_Reflection.inc.hlsl" #include "../Shaders/DS_BakeSprites.inc.hlsl" - enum SHADER - { - SHADER_LIGHT, - SHADER_AMBIENT, - SHADER_AMBIENT_NODE, - SHADER_PROJECT_NODE, - SHADER_COMPOSE, - SHADER_REFLECTION, - SHADER_BAKE_SPRITES, - SHADER_COUNT - }; - - enum PIPE - { - PIPE_INSTANCED_DIR, - PIPE_INSTANCED_OMNI, - PIPE_INSTANCED_SPOT, - PIPE_AMBIENT, - PIPE_AMBIENT_NODE_MUL, - PIPE_AMBIENT_NODE_ADD, - PIPE_PROJECT_NODE, - PIPE_COMPOSE, - PIPE_REFLECTION, - PIPE_REFLECTION_DEBUG, - PIPE_TONE_MAPPING, - PIPE_QUAD, - PIPE_BAKE_SPRITES, - PIPE_COUNT - }; - - enum TEX - { - TEX_GBUFFER_0, // {Albedo.rgb, SSSHue}. - TEX_GBUFFER_1, // {Normal.xy, Emission, MotionBlur}. - TEX_GBUFFER_2, // {Occlusion, Roughness, Metallic, WrapDiffuse}. - TEX_GBUFFER_3, // {Tangent.xy, AnisoSpec, RoughDiffuse}. - - TEX_LIGHT_ACC_AMBIENT, - TEX_LIGHT_ACC_DIFFUSE, - TEX_LIGHT_ACC_SPECULAR, - - TEX_COMPOSED_A, - TEX_COMPOSED_B, - - TEX_COUNT - }; - - static UB_View s_ubView; - static UB_SubpassFS s_ubSubpassFS; - static UB_ShadowFS s_ubShadowFS; - static UB_MeshVS s_ubMeshVS; - static UB_Object s_ubObject; - - static UB_AmbientVS s_ubAmbientVS; - static UB_AmbientFS s_ubAmbientFS; - - static UB_AmbientNodeView s_ubAmbientNodeView; - static UB_AmbientNodeSubpassFS s_ubAmbientNodeSubpassFS; - static UB_AmbientNodeMeshVS s_ubAmbientNodeMeshVS; - static UB_AmbientNodeObject s_ubAmbientNodeObject; - - static UB_ProjectNodeView s_ubProjectNodeView; - static UB_ProjectNodeSubpassFS s_ubProjectNodeSubpassFS; - static UB_ProjectNodeMeshVS s_ubProjectNodeMeshVS; - static UB_ProjectNodeTextureFS s_ubProjectNodeTextureFS; - static UB_ProjectNodeObject s_ubProjectNodeObject; - - static UB_ComposeVS s_ubComposeVS; - static UB_ComposeFS s_ubComposeFS; - - static UB_ReflectionVS s_ubReflectionVS; - static UB_ReflectionFS s_ubReflectionFS; - - static UB_BakeSpritesVS s_ubBakeSpritesVS; - static UB_BakeSpritesFS s_ubBakeSpritesFS; - - Vector4 _backgroundColor = Vector4(0); - ShaderPwns _shader; - PipelinePwns _pipe; - TexturePwns _tex; - TexturePtr _texTerrainHeightmap; - TexturePtr _texTerrainBlend; - UINT64 _frame = 0; - - RPHandle _rph; - RPHandle _rphCompose; - RPHandle _rphForwardRendering; - RPHandle _rphReflection; - RPHandle _rphBakeSprites; - - FBHandle _fbh; - FBHandle _fbhCompose; - FBHandle _fbhForwardRendering; - FBHandle _fbhReflection; - FBHandle _fbhBakeSprites; - - CSHandle _cshLight; - CSHandle _cshLightShadow; - CSHandle _cshAmbient; - CSHandle _cshAmbientNode; - CSHandle _cshProjectNode; - CSHandle _cshCompose; - CSHandle _cshReflection; - CSHandle _cshToneMapping; - CSHandle _cshQuad[7]; - CSHandle _cshBakeSprites; - - int _terrainMapSide = 1; - - bool _activeGeometryPass = false; - bool _activeLightingPass = false; - bool _activeForwardRendering = false; - bool _async_initPipe = false; - - public: - DeferredShading(); - ~DeferredShading(); - - void Init(); - void InitGBuffers(int w, int h); - void InitByBloom(TexturePtr tex); - void InitByCascadedShadowMapBaker(TexturePtr texShadow); - void InitByTerrain(TexturePtr texHeightmap, TexturePtr texBlend, int mapSide); - - void Done(); - - void OnSwapChainResized(bool init, bool done); - - static bool IsLoaded(); - - void ResetInstanceCount(); - void Draw(int gbuffer, - RcVector4 rMultiplexer = Vector4(1, 0, 0, 0), - RcVector4 gMultiplexer = Vector4(0, 1, 0, 0), - RcVector4 bMultiplexer = Vector4(0, 0, 1, 0), - RcVector4 aMultiplexer = Vector4(0, 0, 0, 1)); - - RPHandle GetRenderPassHandle() const { return _rph; } - RPHandle GetRenderPassHandle_ForwardRendering() const { return _rphForwardRendering; } - - // - void BeginGeometryPass(); - void EndGeometryPass(); - bool BeginLightingPass(bool ambient = true, bool terrainOcclusion = true); - void EndLightingPass(); - void BeginComposeAndForwardRendering(bool underwaterMask = true); - void EndComposeAndForwardRendering(); - void DrawReflection(); - void ToneMapping(); - bool IsActiveGeometryPass() const { return _activeGeometryPass; } - bool IsActiveLightingPass() const { return _activeLightingPass; } - bool IsActiveForwardRendering() const { return _activeForwardRendering; } - // - - // - static bool IsLightURL(CSZ url); - void BindPipeline_NewLightType(CommandBufferPtr cb, LightType type, bool wireframe = false); - void BindDescriptors_MeshVS(CommandBufferPtr cb); - static UB_MeshVS& GetUbMeshVS() { return s_ubMeshVS; } - CSHandle BindDescriptorSetTexturesForVSM(TexturePtr texShadow); - void BindDescriptorsForVSM(CommandBufferPtr cb, int firstInstance, CSHandle complexSetHandle, float presence); - // - - // - void BindPipeline_NewAmbientNodePriority(CommandBufferPtr cb, int firstInstance, bool add); - void BindDescriptors_AmbientNodeMeshVS(CommandBufferPtr cb); - static UB_AmbientNodeMeshVS& GetUbAmbientNodeMeshVS() { return s_ubAmbientNodeMeshVS; } - // - - // - void BindPipeline_ProjectNode(CommandBufferPtr cb); - void BindDescriptors_ProjectNodeMeshVS(CommandBufferPtr cb); - static UB_ProjectNodeMeshVS& GetUbProjectNodeMeshVS() { return s_ubProjectNodeMeshVS; } - void BindDescriptors_ProjectNodeTextureFS(CommandBufferPtr cb, CSHandle csh); - void BindDescriptors_ProjectNodeObject(CommandBufferPtr cb); - static UB_ProjectNodeObject& GetUbProjectNodeObject() { return s_ubProjectNodeObject; } - // - - void Load(); - - ShaderPtr GetLightShader() const; - ShaderPtr GetAmbientNodeShader() const; - ShaderPtr GetProjectNodeShader() const; - - TexturePtr GetGBuffer(int index) const; - TexturePtr GetLightAccAmbientTexture() const; - TexturePtr GetLightAccDiffuseTexture() const; - TexturePtr GetLightAccSpecularTexture() const; - TexturePtr GetComposedTextureA() const; - TexturePtr GetComposedTextureB() const; - - static Vector4 GetClearValueForGBuffer0(float albedo = 0); - static Vector4 GetClearValueForGBuffer1(float normal = 0, float motionBlur = 1); - static Vector4 GetClearValueForGBuffer2(float roughness = 0); - static Vector4 GetClearValueForGBuffer3(float tangent = 0); - - void SetBackgroundColor(RcVector4 backgroundColor) { _backgroundColor = backgroundColor; } - - void BakeSprites(TexturePtr texGBufferIn[4], TexturePtr texGBufferOut[4], PBaseCommandBuffer pCB = nullptr); - void BakeSpritesCleanup(); + enum SHADER + { + SHADER_LIGHT, + SHADER_AMBIENT, + SHADER_AMBIENT_NODE, + SHADER_PROJECT_NODE, + SHADER_COMPOSE, + SHADER_REFLECTION, + SHADER_BAKE_SPRITES, + SHADER_COUNT }; - VERUS_TYPEDEFS(DeferredShading); - } + + enum PIPE + { + PIPE_INSTANCED_DIR, + PIPE_INSTANCED_OMNI, + PIPE_INSTANCED_SPOT, + PIPE_AMBIENT, + PIPE_AMBIENT_NODE_MUL, + PIPE_AMBIENT_NODE_ADD, + PIPE_PROJECT_NODE, + PIPE_COMPOSE, + PIPE_REFLECTION, + PIPE_REFLECTION_DEBUG, + PIPE_TONE_MAPPING, + PIPE_QUAD, + PIPE_BAKE_SPRITES, + PIPE_COUNT + }; + + enum TEX + { + TEX_GBUFFER_0, // {Albedo.rgb, SSSHue}. + TEX_GBUFFER_1, // {Normal.xy, Emission, MotionBlur}. + TEX_GBUFFER_2, // {Occlusion, Roughness, Metallic, WrapDiffuse}. + TEX_GBUFFER_3, // {Tangent.xy, AnisoSpec, RoughDiffuse}. + + TEX_LIGHT_ACC_AMBIENT, + TEX_LIGHT_ACC_DIFFUSE, + TEX_LIGHT_ACC_SPECULAR, + + TEX_COMPOSED_A, + TEX_COMPOSED_B, + + TEX_COUNT + }; + + static UB_View s_ubView; + static UB_SubpassFS s_ubSubpassFS; + static UB_ShadowFS s_ubShadowFS; + static UB_MeshVS s_ubMeshVS; + static UB_Object s_ubObject; + + static UB_AmbientVS s_ubAmbientVS; + static UB_AmbientFS s_ubAmbientFS; + + static UB_AmbientNodeView s_ubAmbientNodeView; + static UB_AmbientNodeSubpassFS s_ubAmbientNodeSubpassFS; + static UB_AmbientNodeMeshVS s_ubAmbientNodeMeshVS; + static UB_AmbientNodeObject s_ubAmbientNodeObject; + + static UB_ProjectNodeView s_ubProjectNodeView; + static UB_ProjectNodeSubpassFS s_ubProjectNodeSubpassFS; + static UB_ProjectNodeMeshVS s_ubProjectNodeMeshVS; + static UB_ProjectNodeTextureFS s_ubProjectNodeTextureFS; + static UB_ProjectNodeObject s_ubProjectNodeObject; + + static UB_ComposeVS s_ubComposeVS; + static UB_ComposeFS s_ubComposeFS; + + static UB_ReflectionVS s_ubReflectionVS; + static UB_ReflectionFS s_ubReflectionFS; + + static UB_BakeSpritesVS s_ubBakeSpritesVS; + static UB_BakeSpritesFS s_ubBakeSpritesFS; + + Vector4 _backgroundColor = Vector4(0); + ShaderPwns _shader; + PipelinePwns _pipe; + TexturePwns _tex; + TexturePtr _texTerrainHeightmap; + TexturePtr _texTerrainBlend; + UINT64 _frame = 0; + + RPHandle _rph; + RPHandle _rphCompose; + RPHandle _rphForwardRendering; + RPHandle _rphReflection; + RPHandle _rphBakeSprites; + + FBHandle _fbh; + FBHandle _fbhCompose; + FBHandle _fbhForwardRendering; + FBHandle _fbhReflection; + FBHandle _fbhBakeSprites; + + CSHandle _cshLight; + CSHandle _cshLightShadow; + CSHandle _cshAmbient; + CSHandle _cshAmbientNode; + CSHandle _cshProjectNode; + CSHandle _cshCompose; + CSHandle _cshReflection; + CSHandle _cshToneMapping; + CSHandle _cshQuad[7]; + CSHandle _cshBakeSprites; + + int _terrainMapSide = 1; + + bool _activeGeometryPass = false; + bool _activeLightingPass = false; + bool _activeForwardRendering = false; + bool _async_initPipe = false; + + public: + DeferredShading(); + ~DeferredShading(); + + void Init(); + void InitGBuffers(int w, int h); + void InitByBloom(TexturePtr tex); + void InitByCascadedShadowMapBaker(TexturePtr texShadow); + void InitByTerrain(TexturePtr texHeightmap, TexturePtr texBlend, int mapSide); + + void Done(); + + void OnSwapChainResized(bool init, bool done); + + static bool IsLoaded(); + + void ResetInstanceCount(); + void Draw(int gbuffer, + RcVector4 rMultiplexer = Vector4(1, 0, 0, 0), + RcVector4 gMultiplexer = Vector4(0, 1, 0, 0), + RcVector4 bMultiplexer = Vector4(0, 0, 1, 0), + RcVector4 aMultiplexer = Vector4(0, 0, 0, 1)); + + RPHandle GetRenderPassHandle() const { return _rph; } + RPHandle GetRenderPassHandle_ForwardRendering() const { return _rphForwardRendering; } + + // + void BeginGeometryPass(); + void EndGeometryPass(); + bool BeginLightingPass(bool ambient = true, bool terrainOcclusion = true); + void EndLightingPass(); + void BeginComposeAndForwardRendering(bool underwaterMask = true); + void EndComposeAndForwardRendering(); + void DrawReflection(); + void ToneMapping(); + bool IsActiveGeometryPass() const { return _activeGeometryPass; } + bool IsActiveLightingPass() const { return _activeLightingPass; } + bool IsActiveForwardRendering() const { return _activeForwardRendering; } + // + + // + static bool IsLightURL(CSZ url); + void BindPipeline_NewLightType(CommandBufferPtr cb, LightType type, bool wireframe = false); + void BindDescriptors_MeshVS(CommandBufferPtr cb); + static UB_MeshVS& GetUbMeshVS() { return s_ubMeshVS; } + CSHandle BindDescriptorSetTexturesForVSM(TexturePtr texShadow); + void BindDescriptorsForVSM(CommandBufferPtr cb, int firstInstance, CSHandle complexSetHandle, float presence); + // + + // + void BindPipeline_NewAmbientNodePriority(CommandBufferPtr cb, int firstInstance, bool add); + void BindDescriptors_AmbientNodeMeshVS(CommandBufferPtr cb); + static UB_AmbientNodeMeshVS& GetUbAmbientNodeMeshVS() { return s_ubAmbientNodeMeshVS; } + // + + // + void BindPipeline_ProjectNode(CommandBufferPtr cb); + void BindDescriptors_ProjectNodeMeshVS(CommandBufferPtr cb); + static UB_ProjectNodeMeshVS& GetUbProjectNodeMeshVS() { return s_ubProjectNodeMeshVS; } + void BindDescriptors_ProjectNodeTextureFS(CommandBufferPtr cb, CSHandle csh); + void BindDescriptors_ProjectNodeObject(CommandBufferPtr cb); + static UB_ProjectNodeObject& GetUbProjectNodeObject() { return s_ubProjectNodeObject; } + // + + void Load(); + + ShaderPtr GetLightShader() const; + ShaderPtr GetAmbientNodeShader() const; + ShaderPtr GetProjectNodeShader() const; + + TexturePtr GetGBuffer(int index) const; + TexturePtr GetLightAccAmbientTexture() const; + TexturePtr GetLightAccDiffuseTexture() const; + TexturePtr GetLightAccSpecularTexture() const; + TexturePtr GetComposedTextureA() const; + TexturePtr GetComposedTextureB() const; + + static Vector4 GetClearValueForGBuffer0(float albedo = 0); + static Vector4 GetClearValueForGBuffer1(float normal = 0, float motionBlur = 1); + static Vector4 GetClearValueForGBuffer2(float roughness = 0); + static Vector4 GetClearValueForGBuffer3(float tangent = 0); + + void SetBackgroundColor(RcVector4 backgroundColor) { _backgroundColor = backgroundColor; } + + void BakeSprites(TexturePtr texGBufferIn[4], TexturePtr texGBufferOut[4], PBaseCommandBuffer pCB = nullptr); + void BakeSpritesCleanup(); + }; + VERUS_TYPEDEFS(DeferredShading); } diff --git a/Verus/src/CGI/DynamicBuffer.h b/Verus/src/CGI/DynamicBuffer.h index 5af5fc0..2ef37d1 100644 --- a/Verus/src/CGI/DynamicBuffer.h +++ b/Verus/src/CGI/DynamicBuffer.h @@ -1,89 +1,86 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + template + class DynamicBuffer : public GeometryPwn { - template - class DynamicBuffer : public GeometryPwn + Vector _vVB; + int _maxVerts = 1024; + int _vertCount = 0; + int _firstVertex = 0; + + public: + DynamicBuffer() { - Vector _vVB; - int _maxVerts = 1024; - int _vertCount = 0; - int _firstVertex = 0; + } - public: - DynamicBuffer() - { - } + ~DynamicBuffer() + { + } - ~DynamicBuffer() - { - } + void Init(RcGeometryDesc desc, int maxVerts = 1024) + { + _maxVerts = maxVerts; + GeometryDesc dynDesc(desc); + dynDesc._dynBindingsMask = 0x1; + GeometryPwn::Init(dynDesc); + } - void Init(RcGeometryDesc desc, int maxVerts = 1024) - { - _maxVerts = maxVerts; - GeometryDesc dynDesc(desc); - dynDesc._dynBindingsMask = 0x1; - GeometryPwn::Init(dynDesc); - } + void CreateVertexBuffer() + { + _vVB.resize(_maxVerts); + (*this)->CreateVertexBuffer(_maxVerts, 0); + } - void CreateVertexBuffer() - { - _vVB.resize(_maxVerts); - (*this)->CreateVertexBuffer(_maxVerts, 0); - } + void Reset() + { + _vertCount = 0; + _firstVertex = 0; + } - void Reset() - { - _vertCount = 0; - _firstVertex = 0; - } + void Begin() + { + _firstVertex = _vertCount; + } - void Begin() + void End(BaseCommandBuffer* pCB = nullptr) + { + VERUS_QREF_RENDERER; + const int vertCount = _vertCount - _firstVertex; + if (vertCount) { - _firstVertex = _vertCount; + if (!pCB) + pCB = renderer.GetCommandBuffer().Get(); + (*this)->UpdateVertexBuffer(&_vVB[_firstVertex], 0, pCB, vertCount, _firstVertex); + pCB->Draw(vertCount, 1, _firstVertex); } + } - void End(BaseCommandBuffer* pCB = nullptr) - { - VERUS_QREF_RENDERER; - const int vertCount = _vertCount - _firstVertex; - if (vertCount) - { - if (!pCB) - pCB = renderer.GetCommandBuffer().Get(); - (*this)->UpdateVertexBuffer(&_vVB[_firstVertex], 0, pCB, vertCount, _firstVertex); - pCB->Draw(vertCount, 1, _firstVertex); - } - } + bool Add(const T& v) + { + if (_vertCount + 1 > _maxVerts) + return false; + _vVB[_vertCount++] = v; + return true; + } - bool Add(const T& v) - { - if (_vertCount + 1 > _maxVerts) - return false; - _vVB[_vertCount++] = v; - return true; - } - - bool AddQuad( - const T& a0, - const T& a1, - const T& b0, - const T& b1) - { - if (_vertCount + 6 > _maxVerts) - return false; - _vVB[_vertCount++] = a0; - _vVB[_vertCount++] = b0; - _vVB[_vertCount++] = a1; - _vVB[_vertCount++] = a1; - _vVB[_vertCount++] = b0; - _vVB[_vertCount++] = b1; - return true; - } - }; - } + bool AddQuad( + const T& a0, + const T& a1, + const T& b0, + const T& b1) + { + if (_vertCount + 6 > _maxVerts) + return false; + _vVB[_vertCount++] = a0; + _vVB[_vertCount++] = b0; + _vVB[_vertCount++] = a1; + _vVB[_vertCount++] = a1; + _vVB[_vertCount++] = b0; + _vVB[_vertCount++] = b1; + return true; + } + }; } diff --git a/Verus/src/CGI/Formats.h b/Verus/src/CGI/Formats.h index 806bce6..c65d219 100644 --- a/Verus/src/CGI/Formats.h +++ b/Verus/src/CGI/Formats.h @@ -1,54 +1,51 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + // See: https://vulkan.gpuinfo.org/listformats.php?platform=android + enum class Format : int { - // See: https://vulkan.gpuinfo.org/listformats.php?platform=android - enum class Format : int - { - // Special Formats: - unormR10G10B10A2, - sintR16, - floatR11G11B10, + // Special Formats: + unormR10G10B10A2, + sintR16, + floatR11G11B10, - // Unsigned Formats: - unormR8, - unormR8G8, - unormR8G8B8A8, - unormB8G8R8A8, - srgbR8G8B8A8, - srgbB8G8R8A8, + // Unsigned Formats: + unormR8, + unormR8G8, + unormR8G8B8A8, + unormB8G8R8A8, + srgbR8G8B8A8, + srgbB8G8R8A8, - // Floating-Point Formats: - floatR16, - floatR16G16, - floatR16G16B16A16, + // Floating-Point Formats: + floatR16, + floatR16G16, + floatR16G16B16A16, - // IEEE Formats: - floatR32, - floatR32G32, - floatR32G32B32A32, + // IEEE Formats: + floatR32, + floatR32G32, + floatR32G32B32A32, - // Depth-Stencil: - unormD16, - unormD24uintS8, - floatD32, + // Depth-Stencil: + unormD16, + unormD24uintS8, + floatD32, - // Compressed Texture Formats: - unormBC1, // Deprecated RGBA. - unormBC2, // Deprecated RGBA. - unormBC3, // Deprecated RGBA. - unormBC4, // R. - unormBC5, // RG. - unormBC7, // RGBA. - snormBC4, // R. - snormBC5, // RG. - srgbBC1, // Deprecated RGBA. - srgbBC2, // Deprecated RGBA. - srgbBC3, // Deprecated RGBA. - srgbBC7 // RGBA. - }; - } + // Compressed Texture Formats: + unormBC1, // Deprecated RGBA. + unormBC2, // Deprecated RGBA. + unormBC3, // Deprecated RGBA. + unormBC4, // R. + unormBC5, // RG. + unormBC7, // RGBA. + snormBC4, // R. + snormBC5, // RG. + srgbBC1, // Deprecated RGBA. + srgbBC2, // Deprecated RGBA. + srgbBC3, // Deprecated RGBA. + srgbBC7 // RGBA. + }; } diff --git a/Verus/src/CGI/RenderPass.h b/Verus/src/CGI/RenderPass.h index ceff8be..0e99b4c 100644 --- a/Verus/src/CGI/RenderPass.h +++ b/Verus/src/CGI/RenderPass.h @@ -1,93 +1,87 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI::RP { - namespace CGI + class Attachment { - namespace RP + public: + enum class LoadOp : int { - class Attachment - { - public: - enum class LoadOp : int - { - load, - clear, - dontCare - }; + load, + clear, + dontCare + }; - enum class StoreOp : int - { - store, - dontCare - }; + enum class StoreOp : int + { + store, + dontCare + }; - CSZ _name = nullptr; - Format _format = Format::unormR8G8B8A8; - int _sampleCount = 1; - LoadOp _loadOp = LoadOp::load; - StoreOp _storeOp = StoreOp::store; - LoadOp _stencilLoadOp = LoadOp::dontCare; - StoreOp _stencilStoreOp = StoreOp::dontCare; - ImageLayout _initialLayout = ImageLayout::undefined; - ImageLayout _finalLayout = ImageLayout::undefined; + CSZ _name = nullptr; + Format _format = Format::unormR8G8B8A8; + int _sampleCount = 1; + LoadOp _loadOp = LoadOp::load; + StoreOp _storeOp = StoreOp::store; + LoadOp _stencilLoadOp = LoadOp::dontCare; + StoreOp _stencilStoreOp = StoreOp::dontCare; + ImageLayout _initialLayout = ImageLayout::undefined; + ImageLayout _finalLayout = ImageLayout::undefined; - Attachment(CSZ name, Format format, int sampleCount = 1); + Attachment(CSZ name, Format format, int sampleCount = 1); - Attachment& SetLoadOp(LoadOp op); - Attachment& LoadOpClear(); - Attachment& LoadOpDontCare(); - Attachment& SetStoreOp(StoreOp op); - Attachment& StoreOpDontCare(); - Attachment& Layout(ImageLayout whenBegins, ImageLayout whenEnds); - Attachment& Layout(ImageLayout both); - }; - VERUS_TYPEDEFS(Attachment); + Attachment& SetLoadOp(LoadOp op); + Attachment& LoadOpClear(); + Attachment& LoadOpDontCare(); + Attachment& SetStoreOp(StoreOp op); + Attachment& StoreOpDontCare(); + Attachment& Layout(ImageLayout whenBegins, ImageLayout whenEnds); + Attachment& Layout(ImageLayout both); + }; + VERUS_TYPEDEFS(Attachment); - class Ref - { - public: - CSZ _name = nullptr; - ImageLayout _layout = ImageLayout::undefined; + class Ref + { + public: + CSZ _name = nullptr; + ImageLayout _layout = ImageLayout::undefined; - Ref() = default; - Ref(CSZ name, ImageLayout layout) : _name(name), _layout(layout) {} - }; - VERUS_TYPEDEFS(Ref); + Ref() = default; + Ref(CSZ name, ImageLayout layout) : _name(name), _layout(layout) {} + }; + VERUS_TYPEDEFS(Ref); - class Subpass - { - public: - CSZ _name = nullptr; - std::initializer_list _ilInput; - std::initializer_list _ilColor; - std::initializer_list _ilResolve; - std::initializer_list _ilPreserve; - Ref _depthStencil; + class Subpass + { + public: + CSZ _name = nullptr; + std::initializer_list _ilInput; + std::initializer_list _ilColor; + std::initializer_list _ilResolve; + std::initializer_list _ilPreserve; + Ref _depthStencil; - Subpass(CSZ name); + Subpass(CSZ name); - Subpass& Input(std::initializer_list il); - Subpass& Color(std::initializer_list il); - Subpass& Resolve(std::initializer_list il); - Subpass& Preserve(std::initializer_list il); - Subpass& DepthStencil(Ref r); - }; - VERUS_TYPEDEFS(Subpass); + Subpass& Input(std::initializer_list il); + Subpass& Color(std::initializer_list il); + Subpass& Resolve(std::initializer_list il); + Subpass& Preserve(std::initializer_list il); + Subpass& DepthStencil(Ref r); + }; + VERUS_TYPEDEFS(Subpass); - class Dependency - { - public: - CSZ _srcSubpass = nullptr; - CSZ _dstSubpass = nullptr; - int _mode = 0; + class Dependency + { + public: + CSZ _srcSubpass = nullptr; + CSZ _dstSubpass = nullptr; + int _mode = 0; - Dependency(CSZ src = nullptr, CSZ dst = nullptr); + Dependency(CSZ src = nullptr, CSZ dst = nullptr); - Dependency& Mode(int mode); - }; - VERUS_TYPEDEFS(Dependency); - } - } + Dependency& Mode(int mode); + }; + VERUS_TYPEDEFS(Dependency); } diff --git a/Verus/src/CGI/Renderer.h b/Verus/src/CGI/Renderer.h index 3a5642d..a2509eb 100644 --- a/Verus/src/CGI/Renderer.h +++ b/Verus/src/CGI/Renderer.h @@ -1,209 +1,206 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + struct RendererDelegate { - struct RendererDelegate - { - virtual void Renderer_OnDraw() = 0; - virtual void Renderer_OnDrawView(RcViewDesc viewDesc) = 0; - }; - VERUS_TYPEDEFS(RendererDelegate); + virtual void Renderer_OnDraw() = 0; + virtual void Renderer_OnDrawView(RcViewDesc viewDesc) = 0; + }; + VERUS_TYPEDEFS(RendererDelegate); - class Renderer : public Singleton, public Object - { + class Renderer : public Singleton, public Object + { #include "../Shaders/GenerateMips.inc.hlsl" #include "../Shaders/GenerateCubeMapMips.inc.hlsl" #include "../Shaders/Quad.inc.hlsl" - enum SHADER - { - SHADER_GENERATE_MIPS, - SHADER_GENERATE_CUBE_MAP_MIPS, - SHADER_QUAD, - SHADER_COUNT - }; - - enum PIPE - { - PIPE_GENERATE_MIPS, - PIPE_GENERATE_MIPS_EXPOSURE, - PIPE_GENERATE_CUBE_MAP_MIPS, - PIPE_OFFSCREEN_COLOR, - PIPE_COUNT - }; - - enum TEX - { - TEX_OFFSCREEN_COLOR, - TEX_DEPTH_STENCIL, - TEX_COUNT - }; - - struct Utilization - { - String _name; - INT64 _value = 0; - INT64 _total = 0; - float _fraction = 0; - float _balance = 0; - }; - VERUS_TYPEDEFS(Utilization); - - struct Vertex - { - glm::vec2 _pos; - }; - - Vector _vUtilization; - App::PWindow _pMainWindow = nullptr; - PBaseRenderer _pBaseRenderer = nullptr; - PRendererDelegate _pRendererDelegate = nullptr; - CommandBufferPwn _commandBuffer; - GeometryPwn _geoQuad; - ShaderPwns _shader; - PipelinePwns _pipe; - TexturePwns _tex; - DeferredShading _ds; - UINT64 _frameCount = 0; - Gapi _gapi = Gapi::unknown; - int _screenSwapChainWidth = 0; - int _screenSwapChainHeight = 0; - int _combinedSwapChainWidth = 0; - int _combinedSwapChainHeight = 0; - ViewType _currentViewType = ViewType::none; - int _currentViewIndex = 0; - int _currentViewWidth = 0; - int _currentViewHeight = 0; - int _currentViewX = 0; - int _currentViewY = 0; - float _preferredZNear = 0.1f; - float _preferredZFar = 10000; - float _fps = 30; - float _exposure[2] = {}; // Linear and EV. - RPHandle _rphScreenSwapChain; - RPHandle _rphScreenSwapChainWithDepth; - Vector _fbhScreenSwapChain; - Vector _fbhScreenSwapChainWithDepth; - RPHandle _rphOffscreen; - RPHandle _rphOffscreenWithDepth; - FBHandle _fbhOffscreen; - FBHandle _fbhOffscreenWithDepth; - CSHandle _cshOffscreenColor; - UB_GenerateMips _ubGenerateMips; - UB_GenerateCubeMapMips _ubGenerateCubeMapMips; - UB_QuadVS _ubQuadVS; - UB_QuadFS _ubQuadFS; - int _utilIgnoreIfTotal = 0; - bool _utilSortByBalance = false; - bool _autoExposure = true; - bool _allowInitShaders = true; - bool _showUtilization = false; - - public: - Renderer(); - ~Renderer(); - - // Device-specific: - PBaseRenderer operator->(); - static bool IsLoaded(); - - void Init(PRendererDelegate pDelegate, bool allowInitShaders = true); - void InitCmd(); - void Done(); - - // Frame cycle: - void Update(); - void Draw(); - void BeginFrame(); - void AcquireSwapChainImage(); - void EndFrame(); - - // Window: - App::PWindow GetMainWindow() const { return _pMainWindow; } - App::PWindow SetMainWindow(App::PWindow p) { return Utils::Swap(_pMainWindow, p); } - bool OnWindowSizeChanged(int w, int h); - - // Swap chain & view: - void UpdateCombinedSwapChainSize(); - VERUS_P(void OnScreenSwapChainResized(bool init, bool done)); - int GetScreenSwapChainWidth() const { return _screenSwapChainWidth; } - int GetScreenSwapChainHeight() const { return _screenSwapChainHeight; } - int GetCombinedSwapChainWidth() const { return _combinedSwapChainWidth; } - int GetCombinedSwapChainHeight() const { return _combinedSwapChainHeight; } - ViewType GetCurrentViewType() const { return _currentViewType; } - int GetCurrentViewWidth() const { return _currentViewWidth; } - int GetCurrentViewHeight() const { return _currentViewHeight; } - int GetCurrentViewX() const { return _currentViewX; } - int GetCurrentViewY() const { return _currentViewY; } - float GetCurrentViewAspectRatio() const; - static Format GetSwapChainFormat() { return Format::srgbB8G8R8A8; } - float GetPreferredZNear() const { return _preferredZNear; } - float GetPreferredZFar() const { return _preferredZFar; } - - // Simple (fullscreen) quad: - void DrawQuad(PBaseCommandBuffer pCB = nullptr); - void DrawOffscreenColor(PBaseCommandBuffer pCB = nullptr, bool endRenderPass = true); - void DrawOffscreenColorSwitchRenderPass(PBaseCommandBuffer pCB = nullptr); - - CommandBufferPtr GetCommandBuffer() const { return _commandBuffer; } - TexturePtr GetTexOffscreenColor() const; - TexturePtr GetTexDepthStencil() const; - RDeferredShading GetDS() { return _ds; } - - void OnShaderError(CSZ s); - void OnShaderWarning(CSZ s); - - // ImGui: - virtual void ImGuiSetCurrentContext(ImGuiContext* pContext); - void ImGuiUpdateStyle(); - - // Frame rate: - float GetFps() const { return _fps; } - UINT64 GetFrameCount() const { return _frameCount; } - - // RenderPass & Framebuffer: - RPHandle GetRenderPassHandle_ScreenSwapChain() const; - RPHandle GetRenderPassHandle_ScreenSwapChainWithDepth() const; - RPHandle GetRenderPassHandle_Offscreen() const; - RPHandle GetRenderPassHandle_OffscreenWithDepth() const; - RPHandle GetRenderPassHandle_Auto() const; - RPHandle GetRenderPassHandle_AutoWithDepth() const; - FBHandle GetFramebufferHandle_ScreenSwapChain(int index) const; - FBHandle GetFramebufferHandle_ScreenSwapChainWithDepth(int index) const; - FBHandle GetFramebufferHandle_Offscreen() const; - FBHandle GetFramebufferHandle_OffscreenWithDepth() const; - FBHandle GetFramebufferHandle_Auto(int index) const; - FBHandle GetFramebufferHandle_AutoWithDepth(int index) const; - - // Generate mips: - ShaderPtr GetShaderGenerateMips() const; - ShaderPtr GetShaderGenerateCubeMapMips() const; - PipelinePtr GetPipelineGenerateMips(bool exposure = false) const; - PipelinePtr GetPipelineGenerateCubeMapMips() const; - UB_GenerateMips& GetUbGenerateMips(); - UB_GenerateCubeMapMips& GetUbGenerateCubeMapMips(); - - // Quad: - GeometryPtr GetGeoQuad() const; - ShaderPtr GetShaderQuad() const; - UB_QuadVS& GetUbQuadVS(); - UB_QuadFS& GetUbQuadFS(); - void ResetQuadMultiplexer(); - - // Exposure: - bool IsAutoExposureEnabled() const { return _autoExposure; } - void EnableAutoExposure(bool b = true) { _autoExposure = b; } - float GetExposure() const { return _exposure[0]; } - float GetExposureValue() const { return _exposure[1]; } - void SetExposureValue(float ev); - - void ToggleUtilization() { _showUtilization = !_showUtilization; } - void UpdateUtilization(); - void AddUtilization(CSZ name, INT64 value, INT64 total); + enum SHADER + { + SHADER_GENERATE_MIPS, + SHADER_GENERATE_CUBE_MAP_MIPS, + SHADER_QUAD, + SHADER_COUNT }; - VERUS_TYPEDEFS(Renderer); - } + + enum PIPE + { + PIPE_GENERATE_MIPS, + PIPE_GENERATE_MIPS_EXPOSURE, + PIPE_GENERATE_CUBE_MAP_MIPS, + PIPE_OFFSCREEN_COLOR, + PIPE_COUNT + }; + + enum TEX + { + TEX_OFFSCREEN_COLOR, + TEX_DEPTH_STENCIL, + TEX_COUNT + }; + + struct Utilization + { + String _name; + INT64 _value = 0; + INT64 _total = 0; + float _fraction = 0; + float _balance = 0; + }; + VERUS_TYPEDEFS(Utilization); + + struct Vertex + { + glm::vec2 _pos; + }; + + Vector _vUtilization; + App::PWindow _pMainWindow = nullptr; + PBaseRenderer _pBaseRenderer = nullptr; + PRendererDelegate _pRendererDelegate = nullptr; + CommandBufferPwn _commandBuffer; + GeometryPwn _geoQuad; + ShaderPwns _shader; + PipelinePwns _pipe; + TexturePwns _tex; + DeferredShading _ds; + UINT64 _frameCount = 0; + Gapi _gapi = Gapi::unknown; + int _screenSwapChainWidth = 0; + int _screenSwapChainHeight = 0; + int _combinedSwapChainWidth = 0; + int _combinedSwapChainHeight = 0; + ViewType _currentViewType = ViewType::none; + int _currentViewIndex = 0; + int _currentViewWidth = 0; + int _currentViewHeight = 0; + int _currentViewX = 0; + int _currentViewY = 0; + float _preferredZNear = 0.1f; + float _preferredZFar = 10000; + float _fps = 30; + float _exposure[2] = {}; // Linear and EV. + RPHandle _rphScreenSwapChain; + RPHandle _rphScreenSwapChainWithDepth; + Vector _fbhScreenSwapChain; + Vector _fbhScreenSwapChainWithDepth; + RPHandle _rphOffscreen; + RPHandle _rphOffscreenWithDepth; + FBHandle _fbhOffscreen; + FBHandle _fbhOffscreenWithDepth; + CSHandle _cshOffscreenColor; + UB_GenerateMips _ubGenerateMips; + UB_GenerateCubeMapMips _ubGenerateCubeMapMips; + UB_QuadVS _ubQuadVS; + UB_QuadFS _ubQuadFS; + int _utilIgnoreIfTotal = 0; + bool _utilSortByBalance = false; + bool _autoExposure = true; + bool _allowInitShaders = true; + bool _showUtilization = false; + + public: + Renderer(); + ~Renderer(); + + // Device-specific: + PBaseRenderer operator->(); + static bool IsLoaded(); + + void Init(PRendererDelegate pDelegate, bool allowInitShaders = true); + void InitCmd(); + void Done(); + + // Frame cycle: + void Update(); + void Draw(); + void BeginFrame(); + void AcquireSwapChainImage(); + void EndFrame(); + + // Window: + App::PWindow GetMainWindow() const { return _pMainWindow; } + App::PWindow SetMainWindow(App::PWindow p) { return Utils::Swap(_pMainWindow, p); } + bool OnWindowSizeChanged(int w, int h); + + // Swap chain & view: + void UpdateCombinedSwapChainSize(); + VERUS_P(void OnScreenSwapChainResized(bool init, bool done)); + int GetScreenSwapChainWidth() const { return _screenSwapChainWidth; } + int GetScreenSwapChainHeight() const { return _screenSwapChainHeight; } + int GetCombinedSwapChainWidth() const { return _combinedSwapChainWidth; } + int GetCombinedSwapChainHeight() const { return _combinedSwapChainHeight; } + ViewType GetCurrentViewType() const { return _currentViewType; } + int GetCurrentViewWidth() const { return _currentViewWidth; } + int GetCurrentViewHeight() const { return _currentViewHeight; } + int GetCurrentViewX() const { return _currentViewX; } + int GetCurrentViewY() const { return _currentViewY; } + float GetCurrentViewAspectRatio() const; + static Format GetSwapChainFormat() { return Format::srgbB8G8R8A8; } + float GetPreferredZNear() const { return _preferredZNear; } + float GetPreferredZFar() const { return _preferredZFar; } + + // Simple (fullscreen) quad: + void DrawQuad(PBaseCommandBuffer pCB = nullptr); + void DrawOffscreenColor(PBaseCommandBuffer pCB = nullptr, bool endRenderPass = true); + void DrawOffscreenColorSwitchRenderPass(PBaseCommandBuffer pCB = nullptr); + + CommandBufferPtr GetCommandBuffer() const { return _commandBuffer; } + TexturePtr GetTexOffscreenColor() const; + TexturePtr GetTexDepthStencil() const; + RDeferredShading GetDS() { return _ds; } + + void OnShaderError(CSZ s); + void OnShaderWarning(CSZ s); + + // ImGui: + virtual void ImGuiSetCurrentContext(ImGuiContext* pContext); + void ImGuiUpdateStyle(); + + // Frame rate: + float GetFps() const { return _fps; } + UINT64 GetFrameCount() const { return _frameCount; } + + // RenderPass & Framebuffer: + RPHandle GetRenderPassHandle_ScreenSwapChain() const; + RPHandle GetRenderPassHandle_ScreenSwapChainWithDepth() const; + RPHandle GetRenderPassHandle_Offscreen() const; + RPHandle GetRenderPassHandle_OffscreenWithDepth() const; + RPHandle GetRenderPassHandle_Auto() const; + RPHandle GetRenderPassHandle_AutoWithDepth() const; + FBHandle GetFramebufferHandle_ScreenSwapChain(int index) const; + FBHandle GetFramebufferHandle_ScreenSwapChainWithDepth(int index) const; + FBHandle GetFramebufferHandle_Offscreen() const; + FBHandle GetFramebufferHandle_OffscreenWithDepth() const; + FBHandle GetFramebufferHandle_Auto(int index) const; + FBHandle GetFramebufferHandle_AutoWithDepth(int index) const; + + // Generate mips: + ShaderPtr GetShaderGenerateMips() const; + ShaderPtr GetShaderGenerateCubeMapMips() const; + PipelinePtr GetPipelineGenerateMips(bool exposure = false) const; + PipelinePtr GetPipelineGenerateCubeMapMips() const; + UB_GenerateMips& GetUbGenerateMips(); + UB_GenerateCubeMapMips& GetUbGenerateCubeMapMips(); + + // Quad: + GeometryPtr GetGeoQuad() const; + ShaderPtr GetShaderQuad() const; + UB_QuadVS& GetUbQuadVS(); + UB_QuadFS& GetUbQuadFS(); + void ResetQuadMultiplexer(); + + // Exposure: + bool IsAutoExposureEnabled() const { return _autoExposure; } + void EnableAutoExposure(bool b = true) { _autoExposure = b; } + float GetExposure() const { return _exposure[0]; } + float GetExposureValue() const { return _exposure[1]; } + void SetExposureValue(float ev); + + void ToggleUtilization() { _showUtilization = !_showUtilization; } + void UpdateUtilization(); + void AddUtilization(CSZ name, INT64 value, INT64 total); + }; + VERUS_TYPEDEFS(Renderer); } diff --git a/Verus/src/CGI/RendererParser.h b/Verus/src/CGI/RendererParser.h index a78b8fa..5fded9f 100644 --- a/Verus/src/CGI/RendererParser.h +++ b/Verus/src/CGI/RendererParser.h @@ -1,20 +1,17 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class RendererParser { - class RendererParser - { - static int StrCompare(const void* pA, const void* pB); + static int StrCompare(const void* pA, const void* pB); - public: - static int Expect(CSZ& p, CSZ* ppOptions); - static int ExpectBlendOp(CSZ& p); - static int ExpectCompFunc(CSZ& p, char end, bool skipSpace); - static int ExpectStencilOp(CSZ& p, char end, bool skipSpace); - static int SkipSpace(CSZ& p); - }; - } + public: + static int Expect(CSZ& p, CSZ* ppOptions); + static int ExpectBlendOp(CSZ& p); + static int ExpectCompFunc(CSZ& p, char end, bool skipSpace); + static int ExpectStencilOp(CSZ& p, char end, bool skipSpace); + static int SkipSpace(CSZ& p); + }; } diff --git a/Verus/src/CGI/Scheduled.h b/Verus/src/CGI/Scheduled.h index 03491a1..1d28829 100644 --- a/Verus/src/CGI/Scheduled.h +++ b/Verus/src/CGI/Scheduled.h @@ -1,21 +1,18 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class Scheduled { - class Scheduled - { - UINT64 _doneFrame = UINT64_MAX; + UINT64 _doneFrame = UINT64_MAX; - public: - virtual Continue Scheduled_Update() { return Continue::no; } + public: + virtual Continue Scheduled_Update() { return Continue::no; } - void Schedule(INT64 extraFrameCount = -1); - void ForceScheduled(); - bool IsScheduledAllowed(); - }; - VERUS_TYPEDEFS(Scheduled); - } + void Schedule(INT64 extraFrameCount = -1); + void ForceScheduled(); + bool IsScheduledAllowed(); + }; + VERUS_TYPEDEFS(Scheduled); } diff --git a/Verus/src/CGI/TextureRAM.h b/Verus/src/CGI/TextureRAM.h index 160a6c6..6aacbc4 100644 --- a/Verus/src/CGI/TextureRAM.h +++ b/Verus/src/CGI/TextureRAM.h @@ -1,28 +1,25 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + class TextureRAM : public BaseTexture { - class TextureRAM : public BaseTexture - { - Vector _vBuffer; + Vector _vBuffer; - public: - TextureRAM(); - virtual ~TextureRAM() override; + public: + TextureRAM(); + virtual ~TextureRAM() override; - virtual void Init(RcTextureDesc desc) override; - virtual void Done() override; + virtual void Init(RcTextureDesc desc) override; + virtual void Done() override; - virtual void UpdateSubresource(const void* p, int mipLevel, int arrayLayer, PBaseCommandBuffer pCB) override; - virtual bool ReadbackSubresource(void* p, bool recordCopyCommand, PBaseCommandBuffer pCB) override; + virtual void UpdateSubresource(const void* p, int mipLevel, int arrayLayer, PBaseCommandBuffer pCB) override; + virtual bool ReadbackSubresource(void* p, bool recordCopyCommand, PBaseCommandBuffer pCB) override; - virtual void GenerateMips(PBaseCommandBuffer pCB) override; + virtual void GenerateMips(PBaseCommandBuffer pCB) override; - const BYTE* GetData() const { VERUS_RT_ASSERT(IsLoaded()); return _vBuffer.data(); } - }; - VERUS_TYPEDEFS(TextureRAM); - } + const BYTE* GetData() const { VERUS_RT_ASSERT(IsLoaded()); return _vBuffer.data(); } + }; + VERUS_TYPEDEFS(TextureRAM); } diff --git a/Verus/src/CGI/Types.h b/Verus/src/CGI/Types.h index a4d78f5..5f28015 100644 --- a/Verus/src/CGI/Types.h +++ b/Verus/src/CGI/Types.h @@ -1,217 +1,214 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI + enum class CompareOp : int { - enum class CompareOp : int - { - never, - less, // < - equal, // == - lessOrEqual, // <= - greater, // > - notEqual, // != - greaterOrEqual, // >= - always - }; + never, + less, // < + equal, // == + lessOrEqual, // <= + greater, // > + notEqual, // != + greaterOrEqual, // >= + always + }; - enum class CubeMapFace : int - { - posX, - negX, - posY, - negY, - posZ, - negZ, - count, - all, // Match texture index to cube map face when creating framebuffer. - none = -1 - }; + enum class CubeMapFace : int + { + posX, + negX, + posY, + negY, + posZ, + negZ, + count, + all, // Match texture index to cube map face when creating framebuffer. + none = -1 + }; - enum class PolygonMode : int - { - fill, - line - }; + enum class PolygonMode : int + { + fill, + line + }; - enum class CullMode : int - { - none, - front, - back - }; + enum class CullMode : int + { + none, + front, + back + }; - struct PipelineRasterizationState - { - PolygonMode _polygonMode = PolygonMode::fill; - CullMode _cullMode = CullMode::back; - float _depthBiasConstantFactor = 0; - float _depthBiasClamp = 0; - float _depthBiasSlopeFactor = 0; - bool _depthBiasEnable = false; - }; + struct PipelineRasterizationState + { + PolygonMode _polygonMode = PolygonMode::fill; + CullMode _cullMode = CullMode::back; + float _depthBiasConstantFactor = 0; + float _depthBiasClamp = 0; + float _depthBiasSlopeFactor = 0; + bool _depthBiasEnable = false; + }; - enum class PrimitiveTopology : int - { - pointList, - lineList, - lineStrip, - triangleList, - triangleStrip, - patchList3, - patchList4 - }; + enum class PrimitiveTopology : int + { + pointList, + lineList, + lineStrip, + triangleList, + triangleStrip, + patchList3, + patchList4 + }; - enum class ImageLayout : int - { - undefined, // Does not support device access, the contents of the memory are not guaranteed to be preserved. - general, // Supports all types of device access. - colorAttachment, // Must only be used as a color or resolve attachment. - depthStencilAttachment, // Must only be used as a depth/stencil or depth/stencil resolve attachment. - depthStencilReadOnly, // Must only be used as a read-only depth/stencil attachment or as a read-only image in a shader. - xsReadOnly, // Must only be used as a read-only image in any shader. - fsReadOnly, // Must only be used as a read-only image in fragment shader. - transferSrc, // Must only be used as a source image of a transfer command. - transferDst, // Must only be used as a destination image of a transfer command. - presentSrc // Must only be used for presenting a presentable image for display. - }; + enum class ImageLayout : int + { + undefined, // Does not support device access, the contents of the memory are not guaranteed to be preserved. + general, // Supports all types of device access. + colorAttachment, // Must only be used as a color or resolve attachment. + depthStencilAttachment, // Must only be used as a depth/stencil or depth/stencil resolve attachment. + depthStencilReadOnly, // Must only be used as a read-only depth/stencil attachment or as a read-only image in a shader. + xsReadOnly, // Must only be used as a read-only image in any shader. + fsReadOnly, // Must only be used as a read-only image in fragment shader. + transferSrc, // Must only be used as a source image of a transfer command. + transferDst, // Must only be used as a destination image of a transfer command. + presentSrc // Must only be used for presenting a presentable image for display. + }; - enum class Sampler : int - { - custom, // Not immutable, not static sampler. - inputAttach, // SubpassInput<>, which is Vulkan-specific, nearestMipN elsewhere. - storageImage, // RWTexture2D<>, UAV. - lodBias, - shadow, - aniso, // Most common sampler for 3D. - anisoClamp, - anisoSharp, // For UI. - linearMipL, - nearestMipL, - linearMipN, - nearestMipN, - linearClampMipL, - nearestClampMipL, - linearClampMipN, - nearestClampMipN, - count - }; + enum class Sampler : int + { + custom, // Not immutable, not static sampler. + inputAttach, // SubpassInput<>, which is Vulkan-specific, nearestMipN elsewhere. + storageImage, // RWTexture2D<>, UAV. + lodBias, + shadow, + aniso, // Most common sampler for 3D. + anisoClamp, + anisoSharp, // For UI. + linearMipL, + nearestMipL, + linearMipN, + nearestMipN, + linearClampMipL, + nearestClampMipL, + linearClampMipN, + nearestClampMipN, + count + }; - enum class ShaderStageFlags : UINT32 - { - // Classic pipeline: - vs = (1 << 0), // Vertex shader. - hs = (1 << 1), // Hull shader. Also known as tessellation control shader. - ds = (1 << 2), // Domain shader. Also known as tessellation evaluation shader. - gs = (1 << 3), // Geometry shader. - fs = (1 << 4), // Fragment shader. Also known as pixel shader. + enum class ShaderStageFlags : UINT32 + { + // Classic pipeline: + vs = (1 << 0), // Vertex shader. + hs = (1 << 1), // Hull shader. Also known as tessellation control shader. + ds = (1 << 2), // Domain shader. Also known as tessellation evaluation shader. + gs = (1 << 3), // Geometry shader. + fs = (1 << 4), // Fragment shader. Also known as pixel shader. - cs = (1 << 5), // Compute shader. Also known as kernel shader. + cs = (1 << 5), // Compute shader. Also known as kernel shader. - // Raytracing: - rtrg = (1 << 6), // Ray generation shader. - rtah = (1 << 7), // Any hit shader. - rtch = (1 << 8), // Closest hit shader. - rtm = (1 << 9), // Miss shader. - rti = (1 << 10), // Intersection shader. - rtc = (1 << 11), // Callable shader. + // Raytracing: + rtrg = (1 << 6), // Ray generation shader. + rtah = (1 << 7), // Any hit shader. + rtch = (1 << 8), // Closest hit shader. + rtm = (1 << 9), // Miss shader. + rti = (1 << 10), // Intersection shader. + rtc = (1 << 11), // Callable shader. - // Mesh shading pipeline: - ts = (1 << 12), // Task shader. Also known as amplification shader. - ms = (1 << 13), // Mesh shader. + // Mesh shading pipeline: + ts = (1 << 12), // Task shader. Also known as amplification shader. + ms = (1 << 13), // Mesh shader. - vs_fs = vs | fs, - vs_hs_ds = vs | hs | ds, - vs_hs_ds_fs = vs | hs | ds | fs - }; + vs_fs = vs | fs, + vs_hs_ds = vs | hs | ds, + vs_hs_ds_fs = vs | hs | ds | fs + }; - enum class ViaType : int - { - floats, - halfs, - shorts, - ubytes - }; + enum class ViaType : int + { + floats, + halfs, + shorts, + ubytes + }; - // See: https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3ddeclusage - enum class ViaUsage : int - { - position, // "POSITION" in glTF. - blendWeights, // "WEIGHTS_0" in glTF. - blendIndices, // "JOINTS_0" in glTF. - normal, // "NORMAL" in glTF. - tangent, // "TANGENT" in glTF. - binormal, - color, // "COLOR_X" in glTF. - psize, - texCoord, // "TEXCOORD_X" in glTF. - instData, - attr - }; + // See: https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3ddeclusage + enum class ViaUsage : int + { + position, // "POSITION" in glTF. + blendWeights, // "WEIGHTS_0" in glTF. + blendIndices, // "JOINTS_0" in glTF. + normal, // "NORMAL" in glTF. + tangent, // "TANGENT" in glTF. + binormal, + color, // "COLOR_X" in glTF. + psize, + texCoord, // "TEXCOORD_X" in glTF. + instData, + attr + }; - // See: https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dvertexelement9 - struct VertexInputAttrDesc - { - int _binding; - int _offset; - ViaType _type; - int _components; - ViaUsage _usage; - int _usageIndex; + // See: https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dvertexelement9 + struct VertexInputAttrDesc + { + int _binding; + int _offset; + ViaType _type; + int _components; + ViaUsage _usage; + int _usageIndex; - static constexpr VertexInputAttrDesc End() { return { -1, -1, ViaType::floats, 0, ViaUsage::position, 0 }; } - }; - VERUS_TYPEDEFS(VertexInputAttrDesc); + static constexpr VertexInputAttrDesc End() { return { -1, -1, ViaType::floats, 0, ViaUsage::position, 0 }; } + }; + VERUS_TYPEDEFS(VertexInputAttrDesc); - class RPHandle : public BaseHandle - { - public: - static RPHandle Make(int value) { return BaseHandle::Make(value); } - }; + class RPHandle : public BaseHandle + { + public: + static RPHandle Make(int value) { return BaseHandle::Make(value); } + }; - class FBHandle : public BaseHandle - { - public: - static FBHandle Make(int value) { return BaseHandle::Make(value); } - }; + class FBHandle : public BaseHandle + { + public: + static FBHandle Make(int value) { return BaseHandle::Make(value); } + }; - class CSHandle : public BaseHandle - { - public: - static CSHandle Make(int value) { return BaseHandle::Make(value); } - }; + class CSHandle : public BaseHandle + { + public: + static CSHandle Make(int value) { return BaseHandle::Make(value); } + }; - enum class ViewType : int - { - none, // Undefined or common (layout) view. - screen, // View for main window. - splitScreen2H, - splitScreen2V, - splitScreen2X, - splitScreen4, - openXR // Per eye view of OpenXR. - }; + enum class ViewType : int + { + none, // Undefined or common (layout) view. + screen, // View for main window. + splitScreen2H, + splitScreen2V, + splitScreen2X, + splitScreen4, + openXR // Per eye view of OpenXR. + }; - struct ViewDesc - { - Transform3 _matV = Transform3::identity(); - Matrix4 _matP = Matrix4::identity(); - Math::Pose _pose; - float _fovLeft = 0; - float _fovRight = 0; - float _fovUp = 0; - float _fovDown = 0; - float _zNear = 0; - float _zFar = 0; - int _vpX = 0; - int _vpY = 0; - int _vpWidth = 0; - int _vpHeight = 0; - ViewType _type = ViewType::none; - int _index = 0; // To distinguish between left and right eye or player index in split screen mode. - }; - VERUS_TYPEDEFS(ViewDesc); - } + struct ViewDesc + { + Transform3 _matV = Transform3::identity(); + Matrix4 _matP = Matrix4::identity(); + Math::Pose _pose; + float _fovLeft = 0; + float _fovRight = 0; + float _fovUp = 0; + float _fovDown = 0; + float _zNear = 0; + float _zFar = 0; + int _vpX = 0; + int _vpY = 0; + int _vpWidth = 0; + int _vpHeight = 0; + ViewType _type = ViewType::none; + int _index = 0; // To distinguish between left and right eye or player index in split screen mode. + }; + VERUS_TYPEDEFS(ViewDesc); } diff --git a/Verus/src/D/AssertionCompileTime.h b/Verus/src/D/AssertionCompileTime.h index be0d6ea..32d00c9 100644 --- a/Verus/src/D/AssertionCompileTime.h +++ b/Verus/src/D/AssertionCompileTime.h @@ -1,4 +1,4 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -#define VERUS_CT_ASSERT(x) static_assert(x, "VERUS_CT_ASSERT") +#define VERUS_CT_ASSERT(x) static_assert(x) diff --git a/Verus/src/D/Log.h b/Verus/src/D/Log.h index 15ec860..0ca5f90 100644 --- a/Verus/src/D/Log.h +++ b/Verus/src/D/Log.h @@ -6,33 +6,30 @@ #define VERUS_LOG_INFO(txt) {StringStream ss_Log; ss_Log << txt; D::Log::I().Write(_C(ss_Log.str()), std::this_thread::get_id(), __FILE__, __LINE__, D::Log::Severity::info);} #define VERUS_LOG_DEBUG(txt) {StringStream ss_Log; ss_Log << txt; D::Log::I().Write(_C(ss_Log.str()), std::this_thread::get_id(), __FILE__, __LINE__, D::Log::Severity::debug);} -namespace verus +namespace verus::D { - namespace D + class Log : public Singleton { - class Log : public Singleton + public: + enum class Severity : int { - public: - enum class Severity : int - { - error, - warning, - info, - debug - }; - - private: - std::mutex _mutex; - std::string _pathname; - - public: - std::mutex& GetMutex() { return _mutex; } - - void Write(CSZ txt, std::thread::id tid, CSZ filename, UINT32 line, Severity severity); - - static void FormatTime(char* buffer, size_t size); - static CSZ GetSeverityLetter(Severity severity); - static String ExtractFilename(CSZ filename); + error, + warning, + info, + debug }; - } + + private: + std::mutex _mutex; + std::string _pathname; + + public: + std::mutex& GetMutex() { return _mutex; } + + void Write(CSZ txt, std::thread::id tid, CSZ filename, UINT32 line, Severity severity); + + static void FormatTime(char* buffer, size_t size); + static CSZ GetSeverityLetter(Severity severity); + static String ExtractFilename(CSZ filename); + }; } diff --git a/Verus/src/D/Recoverable.h b/Verus/src/D/Recoverable.h index 379d284..e142995 100644 --- a/Verus/src/D/Recoverable.h +++ b/Verus/src/D/Recoverable.h @@ -1,33 +1,30 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::D { - namespace D + class Recoverable : public RuntimeError { - class Recoverable : public RuntimeError + public: + Recoverable(std::thread::id tid = std::this_thread::get_id(), CSZ file = "", UINT32 line = __LINE__) : RuntimeError(tid, file, line) {} + Recoverable(const Recoverable& that) { - public: - Recoverable(std::thread::id tid = std::this_thread::get_id(), CSZ file = "", UINT32 line = __LINE__) : RuntimeError(tid, file, line) {} - Recoverable(const Recoverable& that) - { - *this = that; - } - Recoverable& operator=(const Recoverable& that) - { - RuntimeError::operator=(that); - return *this; - } + *this = that; + } + Recoverable& operator=(const Recoverable& that) + { + RuntimeError::operator=(that); + return *this; + } - template - Recoverable& operator<<(const T& t) - { - RuntimeError::operator<<(t); - return *this; - } - }; - VERUS_TYPEDEFS(Recoverable); - } + template + Recoverable& operator<<(const T& t) + { + RuntimeError::operator<<(t); + return *this; + } + }; + VERUS_TYPEDEFS(Recoverable); } #define VERUS_RECOVERABLE verus::D::Recoverable(std::this_thread::get_id(), __FILE__, __LINE__) diff --git a/Verus/src/D/RuntimeError.h b/Verus/src/D/RuntimeError.h index 11701f8..b4ce0d0 100644 --- a/Verus/src/D/RuntimeError.h +++ b/Verus/src/D/RuntimeError.h @@ -1,68 +1,65 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::D { - namespace D + // See: https://marknelson.us/posts/2007/11/13/no-exceptions.html + class RuntimeError : public std::exception { - // See: https://marknelson.us/posts/2007/11/13/no-exceptions.html - class RuntimeError : public std::exception + mutable StringStream _ss; + mutable String _what; + std::thread::id _tid; + String _file; + UINT32 _line = 0; + + public: + RuntimeError(std::thread::id tid = std::this_thread::get_id(), CSZ file = "", UINT32 line = __LINE__) : + _tid(tid), _line(line) { - mutable StringStream _ss; - mutable String _what; - std::thread::id _tid; - String _file; - UINT32 _line = 0; + CSZ p = strrchr(file, '/'); + if (!p) + p = strrchr(file, '\\'); + _file = p ? p + 1 : file; + } + RuntimeError(const RuntimeError& that) + { + *this = that; + } + RuntimeError& operator=(const RuntimeError& that) + { + _what += that._what; + _what += that._ss.str(); + _tid = that._tid; + _file = that._file; + _line = that._line; + return *this; + } + virtual ~RuntimeError() throw() {} - public: - RuntimeError(std::thread::id tid = std::this_thread::get_id(), CSZ file = "", UINT32 line = __LINE__) : - _tid(tid), _line(line) + virtual CSZ what() const throw() + { + if (_ss.str().size()) { - CSZ p = strrchr(file, '/'); - if (!p) - p = strrchr(file, '\\'); - _file = p ? p + 1 : file; + _what += _ss.str(); + _ss.str(""); } - RuntimeError(const RuntimeError& that) - { - *this = that; - } - RuntimeError& operator=(const RuntimeError& that) - { - _what += that._what; - _what += that._ss.str(); - _tid = that._tid; - _file = that._file; - _line = that._line; - return *this; - } - virtual ~RuntimeError() throw() {} + return _C(_what); + } - virtual CSZ what() const throw() - { - if (_ss.str().size()) - { - _what += _ss.str(); - _ss.str(""); - } - return _C(_what); - } + std::thread::id GetThreadID() const { return _tid; } + CSZ GetFile() const { return _C(_file); } + UINT32 GetLine() const { return _line; } - std::thread::id GetThreadID() const { return _tid; } - CSZ GetFile() const { return _C(_file); } - UINT32 GetLine() const { return _line; } + template + RuntimeError& operator<<(const T& t) + { + _ss << t; + return *this; + } - template - RuntimeError& operator<<(const T& t) - { - _ss << t; - return *this; - } - - bool IsRaised() const { return !!strlen(what()); } - }; - VERUS_TYPEDEFS(RuntimeError); - } + bool IsRaised() const { return !!strlen(what()); } + }; + VERUS_TYPEDEFS(RuntimeError); } #define VERUS_RUNTIME_ERROR verus::D::RuntimeError(std::this_thread::get_id(), __FILE__, __LINE__) diff --git a/Verus/src/Effects/Bloom.h b/Verus/src/Effects/Bloom.h index d88a33f..74b457f 100644 --- a/Verus/src/Effects/Bloom.h +++ b/Verus/src/Effects/Bloom.h @@ -1,69 +1,66 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Effects { - namespace Effects + class Bloom : public Singleton, public Object { - class Bloom : public Singleton, public Object - { #include "../Shaders/Bloom.inc.hlsl" - enum PIPE - { - PIPE_MAIN, - PIPE_LIGHT_SHAFTS, - PIPE_COUNT - }; - - enum TEX - { - TEX_PING, - TEX_PONG, - TEX_COUNT - }; - - static UB_BloomVS s_ubBloomVS; - static UB_BloomFS s_ubBloomFS; - static UB_BloomLightShaftsFS s_ubBloomLightShaftsFS; - - CGI::ShaderPwn _shader; - CGI::PipelinePwns _pipe; - CGI::TexturePwns _tex; - CGI::TexturePtr _texCSMB; - CGI::RPHandle _rph; - CGI::RPHandle _rphLightShafts; - CGI::FBHandle _fbh; - CGI::CSHandle _csh; - CGI::CSHandle _cshLightShafts; - float _colorScale = 0.7f; - float _colorBias = 1.4f; - float _maxDist = 20; - float _sunGloss = 128; - float _wideStrength = 0.15f; - float _sunStrength = 0.35f; - bool _blur = true; - bool _blurLightShafts = true; - bool _editMode = false; - - public: - Bloom(); - ~Bloom(); - - void Init(); - void InitByCascadedShadowMapBaker(CGI::TexturePtr texShadow); - void Done(); - - void OnSwapChainResized(); - - void Generate(); - - CGI::TexturePtr GetTexture() const; - CGI::TexturePtr GetPongTexture() const; - - bool IsEditMode() const { return _editMode; } - void ToggleEditMode() { _editMode = !_editMode; } + enum PIPE + { + PIPE_MAIN, + PIPE_LIGHT_SHAFTS, + PIPE_COUNT }; - VERUS_TYPEDEFS(Bloom); - } + + enum TEX + { + TEX_PING, + TEX_PONG, + TEX_COUNT + }; + + static UB_BloomVS s_ubBloomVS; + static UB_BloomFS s_ubBloomFS; + static UB_BloomLightShaftsFS s_ubBloomLightShaftsFS; + + CGI::ShaderPwn _shader; + CGI::PipelinePwns _pipe; + CGI::TexturePwns _tex; + CGI::TexturePtr _texCSMB; + CGI::RPHandle _rph; + CGI::RPHandle _rphLightShafts; + CGI::FBHandle _fbh; + CGI::CSHandle _csh; + CGI::CSHandle _cshLightShafts; + float _colorScale = 0.7f; + float _colorBias = 1.4f; + float _maxDist = 20; + float _sunGloss = 128; + float _wideStrength = 0.15f; + float _sunStrength = 0.35f; + bool _blur = true; + bool _blurLightShafts = true; + bool _editMode = false; + + public: + Bloom(); + ~Bloom(); + + void Init(); + void InitByCascadedShadowMapBaker(CGI::TexturePtr texShadow); + void Done(); + + void OnSwapChainResized(); + + void Generate(); + + CGI::TexturePtr GetTexture() const; + CGI::TexturePtr GetPongTexture() const; + + bool IsEditMode() const { return _editMode; } + void ToggleEditMode() { _editMode = !_editMode; } + }; + VERUS_TYPEDEFS(Bloom); } diff --git a/Verus/src/Effects/Blur.h b/Verus/src/Effects/Blur.h index 0af16a5..7c493ec 100644 --- a/Verus/src/Effects/Blur.h +++ b/Verus/src/Effects/Blur.h @@ -1,127 +1,124 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Effects { - namespace Effects + class Blur : public Singleton, public Object { - class Blur : public Singleton, public Object - { #include "../Shaders/Blur.inc.hlsl" - enum PIPE - { - PIPE_U, - PIPE_V, + enum PIPE + { + PIPE_U, + PIPE_V, - PIPE_VSM_U, - PIPE_VSM_V, + PIPE_VSM_U, + PIPE_VSM_V, - PIPE_SSAO, + PIPE_SSAO, - PIPE_RESOLVE_DITHERING, - PIPE_SHARPEN, + PIPE_RESOLVE_DITHERING, + PIPE_SHARPEN, - PIPE_DOF_U, - PIPE_DOF_V, + PIPE_DOF_U, + PIPE_DOF_V, - PIPE_BLOOM_U, - PIPE_BLOOM_V, - PIPE_BLOOM_LIGHT_SHAFTS_U, - PIPE_BLOOM_LIGHT_SHAFTS_V, + PIPE_BLOOM_U, + PIPE_BLOOM_V, + PIPE_BLOOM_LIGHT_SHAFTS_U, + PIPE_BLOOM_LIGHT_SHAFTS_V, - PIPE_AA, - PIPE_AA_OFF, - PIPE_MOTION_BLUR, - PIPE_MOTION_BLUR_OFF, + PIPE_AA, + PIPE_AA_OFF, + PIPE_MOTION_BLUR, + PIPE_MOTION_BLUR_OFF, - PIPE_COUNT - }; - - struct Handles - { - CGI::RPHandle _rphU; - CGI::RPHandle _rphV; - CGI::FBHandle _fbhU; - CGI::FBHandle _fbhV; - CGI::CSHandle _cshU; - CGI::CSHandle _cshV; - - void FreeDescriptorSets(CGI::ShaderPtr shader); - void DeleteFramebuffers(); - void DeleteRenderPasses(); - }; - - static UB_BlurVS s_ubBlurVS; - static UB_BlurFS s_ubBlurFS; - static UB_ExtraBlurFS s_ubExtraBlurFS; - - CGI::ShaderPwn _shader; - CGI::PipelinePwns _pipe; - - CGI::RPHandle _rphVsmU; - CGI::RPHandle _rphVsmV; - - CGI::RPHandle _rphSsao; - CGI::FBHandle _fbhSsao; - CGI::CSHandle _cshSsao; - - Handles _rdsHandles; - CGI::CSHandle _cshRdsExtra; - - Handles _dofHandles; - CGI::CSHandle _cshDofExtra; - - Handles _bloomHandles; - - CGI::RPHandle _rphAntiAliasing; - CGI::FBHandle _fbhAntiAliasing; - CGI::CSHandle _cshAntiAliasing; - CGI::CSHandle _cshAntiAliasingExtra; - - CGI::RPHandle _rphMotionBlur; - CGI::FBHandle _fbhMotionBlur; - CGI::CSHandle _cshMotionBlur; - CGI::CSHandle _cshMotionBlurExtra; - - float _dofFocusDist = 10; - float _dofRadius = 0.005f; - float _bloomRadius = 0.02f; - float _bloomLightShaftsRadius = 0.002f; - bool _enableDepthOfField = false; - - public: - Blur(); - ~Blur(); - - void Init(); - void Done(); - - void OnSwapChainResized(); - - CGI::ShaderPtr GetShader() const { return _shader; } - - void GenerateForVSM(CGI::FBHandle fbhU, CGI::FBHandle fbhV, CGI::CSHandle cshU, CGI::CSHandle cshV, - RcVector4 rc, RcVector4 zNearFarEx); - void GenerateForSsao(); - void GenerateForResolveDitheringAndSharpen(); - void GenerateForDepthOfField(); - void GenerateForBloom(bool forLightShafts); - void GenerateForAntiAliasing(); - void GenerateForMotionBlur(); - - void UpdateUniformBuffer(float radius, int sampleCount, int texSize = 0, float samplesPerPixel = 1, int maxSamples = 61); - - CGI::RPHandle GetRenderPassHandleForVsmU() const { return _rphVsmU; } - CGI::RPHandle GetRenderPassHandleForVsmV() const { return _rphVsmV; } - - bool IsDepthOfFieldEnabled() const { return _enableDepthOfField; } - void EnableDepthOfField(bool b) { _enableDepthOfField = b; } - float GetDofFocusDistance() const { return _dofFocusDist; } - void SetDofFocusDistance(float dist) { _dofFocusDist = dist; } - float GetDofRadius() const { return _dofRadius; } - void SetDofRadius(float radius) { _dofRadius = radius; } + PIPE_COUNT }; - VERUS_TYPEDEFS(Blur); - } + + struct Handles + { + CGI::RPHandle _rphU; + CGI::RPHandle _rphV; + CGI::FBHandle _fbhU; + CGI::FBHandle _fbhV; + CGI::CSHandle _cshU; + CGI::CSHandle _cshV; + + void FreeDescriptorSets(CGI::ShaderPtr shader); + void DeleteFramebuffers(); + void DeleteRenderPasses(); + }; + + static UB_BlurVS s_ubBlurVS; + static UB_BlurFS s_ubBlurFS; + static UB_ExtraBlurFS s_ubExtraBlurFS; + + CGI::ShaderPwn _shader; + CGI::PipelinePwns _pipe; + + CGI::RPHandle _rphVsmU; + CGI::RPHandle _rphVsmV; + + CGI::RPHandle _rphSsao; + CGI::FBHandle _fbhSsao; + CGI::CSHandle _cshSsao; + + Handles _rdsHandles; + CGI::CSHandle _cshRdsExtra; + + Handles _dofHandles; + CGI::CSHandle _cshDofExtra; + + Handles _bloomHandles; + + CGI::RPHandle _rphAntiAliasing; + CGI::FBHandle _fbhAntiAliasing; + CGI::CSHandle _cshAntiAliasing; + CGI::CSHandle _cshAntiAliasingExtra; + + CGI::RPHandle _rphMotionBlur; + CGI::FBHandle _fbhMotionBlur; + CGI::CSHandle _cshMotionBlur; + CGI::CSHandle _cshMotionBlurExtra; + + float _dofFocusDist = 10; + float _dofRadius = 0.005f; + float _bloomRadius = 0.02f; + float _bloomLightShaftsRadius = 0.002f; + bool _enableDepthOfField = false; + + public: + Blur(); + ~Blur(); + + void Init(); + void Done(); + + void OnSwapChainResized(); + + CGI::ShaderPtr GetShader() const { return _shader; } + + void GenerateForVSM(CGI::FBHandle fbhU, CGI::FBHandle fbhV, CGI::CSHandle cshU, CGI::CSHandle cshV, + RcVector4 rc, RcVector4 zNearFarEx); + void GenerateForSsao(); + void GenerateForResolveDitheringAndSharpen(); + void GenerateForDepthOfField(); + void GenerateForBloom(bool forLightShafts); + void GenerateForAntiAliasing(); + void GenerateForMotionBlur(); + + void UpdateUniformBuffer(float radius, int sampleCount, int texSize = 0, float samplesPerPixel = 1, int maxSamples = 61); + + CGI::RPHandle GetRenderPassHandleForVsmU() const { return _rphVsmU; } + CGI::RPHandle GetRenderPassHandleForVsmV() const { return _rphVsmV; } + + bool IsDepthOfFieldEnabled() const { return _enableDepthOfField; } + void EnableDepthOfField(bool b) { _enableDepthOfField = b; } + float GetDofFocusDistance() const { return _dofFocusDist; } + void SetDofFocusDistance(float dist) { _dofFocusDist = dist; } + float GetDofRadius() const { return _dofRadius; } + void SetDofRadius(float radius) { _dofRadius = radius; } + }; + VERUS_TYPEDEFS(Blur); } diff --git a/Verus/src/Effects/Cinema.h b/Verus/src/Effects/Cinema.h index 9d3c85a..0db8193 100644 --- a/Verus/src/Effects/Cinema.h +++ b/Verus/src/Effects/Cinema.h @@ -1,40 +1,37 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Effects { - namespace Effects + class Cinema : public Singleton, public Object { - class Cinema : public Singleton, public Object - { #include "../Shaders/Cinema.inc.hlsl" - static UB_CinemaVS s_ubCinemaVS; - static UB_CinemaFS s_ubCinemaFS; + static UB_CinemaVS s_ubCinemaVS; + static UB_CinemaFS s_ubCinemaFS; - CGI::ShaderPwn _shader; - CGI::PipelinePwn _pipe; - CGI::TexturePwn _texFilmGrain; - CGI::CSHandle _csh; - float _uOffset = 0; - float _vOffset = 0; - float _brightness = 1; - float _flickerStrength = 0.02f; - float _noiseStrength = 0.2f; - bool _editMode = false; + CGI::ShaderPwn _shader; + CGI::PipelinePwn _pipe; + CGI::TexturePwn _texFilmGrain; + CGI::CSHandle _csh; + float _uOffset = 0; + float _vOffset = 0; + float _brightness = 1; + float _flickerStrength = 0.02f; + float _noiseStrength = 0.2f; + bool _editMode = false; - public: - Cinema(); - ~Cinema(); + public: + Cinema(); + ~Cinema(); - void Init(); - void Done(); + void Init(); + void Done(); - void Draw(); + void Draw(); - bool IsEditMode() const { return _editMode; } - void ToggleEditMode() { _editMode = !_editMode; } - }; - VERUS_TYPEDEFS(Cinema); - } + bool IsEditMode() const { return _editMode; } + void ToggleEditMode() { _editMode = !_editMode; } + }; + VERUS_TYPEDEFS(Cinema); } diff --git a/Verus/src/Effects/Particles.h b/Verus/src/Effects/Particles.h index 8d4da3b..4c6c673 100644 --- a/Verus/src/Effects/Particles.h +++ b/Verus/src/Effects/Particles.h @@ -1,188 +1,185 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Effects { - namespace Effects + enum class BillboardType : int { - enum class BillboardType : int - { - none, - screenViewplaneOriented, - screenViewpointOriented, - worldViewplaneOriented, - worldViewpointOriented, - axial - }; + none, + screenViewplaneOriented, + screenViewpointOriented, + worldViewplaneOriented, + worldViewpointOriented, + axial + }; - class Particle - { - public: - Point3 _position = Point3(0); - Point3 _prevPosition = Point3(0); - Vector3 _velocity = Vector3(0, 1, 0); - Vector3 _axis = Vector3(0, 1, 0); - Vector4 _tcOffset = Vector4(0); - Vector4 _beginColor = Vector4::Replicate(1); - Vector4 _endColor = Vector4::Replicate(1); - void* _pUser = nullptr; - float _invTotalTime = 0; - float _timeLeft = -1; - float _beginAdditive = 0; - float _endAdditive = 0; - float _beginSize = 0; - float _endSize = 0; - float _beginSpin = 0; - float _endSpin = 0; - bool _inContact = false; - }; - VERUS_TYPEDEFS(Particle); + class Particle + { + public: + Point3 _position = Point3(0); + Point3 _prevPosition = Point3(0); + Vector3 _velocity = Vector3(0, 1, 0); + Vector3 _axis = Vector3(0, 1, 0); + Vector4 _tcOffset = Vector4(0); + Vector4 _beginColor = Vector4::Replicate(1); + Vector4 _endColor = Vector4::Replicate(1); + void* _pUser = nullptr; + float _invTotalTime = 0; + float _timeLeft = -1; + float _beginAdditive = 0; + float _endAdditive = 0; + float _beginSize = 0; + float _endSize = 0; + float _beginSpin = 0; + float _endSpin = 0; + bool _inContact = false; + }; + VERUS_TYPEDEFS(Particle); - class Particles; - class ParticlesDelegate - { - public: - virtual void Particles_OnUpdate(Particles& particles, int index, RParticle particle, - RVector3 up, RVector3 normal, RTransform3 matAim) = 0; - }; - VERUS_TYPEDEFS(ParticlesDelegate); + class Particles; + class ParticlesDelegate + { + public: + virtual void Particles_OnUpdate(Particles& particles, int index, RParticle particle, + RVector3 up, RVector3 normal, RTransform3 matAim) = 0; + }; + VERUS_TYPEDEFS(ParticlesDelegate); - class Particles : public Object - { + class Particles : public Object + { #include "../Shaders/Particles.inc.hlsl" - enum PIPE - { - PIPE_MAIN, - PIPE_BILLBOARDS, - PIPE_COUNT - }; - - struct Vertex - { - glm::vec4 pos; - glm::vec2 tc0; - UINT32 color; - float psize; - }; - VERUS_TYPEDEFS(Vertex); - - static CGI::ShaderPwn s_shader; - static CGI::PipelinePwns s_pipe; - static UB_ParticlesVS s_ubParticlesVS; - static UB_ParticlesFS s_ubParticlesFS; - - Vector4 _tilesetSize = Vector4::Replicate(1); - Vector3 _lifeTimeRange = Vector3(0, 1, 1); - Vector3 _speedRange = Vector3(0, 1, 1); - Vector3 _beginAdditiveRange = Vector3(0); - Vector3 _endAdditiveRange = Vector3(0); - Vector4 _beginColorMin = Vector4(0); - Vector4 _beginColorDelta = Vector4(0); - Vector4 _endColorMin = Vector4(0); - Vector4 _endColorDelta = Vector4(0); - Vector3 _beginSizeRange = Vector3(0, 1, 1); - Vector3 _endSizeRange = Vector3(0, 1, 1); - Vector3 _beginSpinRange = Vector3(0, 1, 1); - Vector3 _endSpinRange = Vector3(0, 1, 1); - Vector3 _gravity = Vector3(0, -9.8f, 0); - String _url; - Vector _vParticles; - Vector _vVB; - Vector _vIB; - CGI::GeometryPwn _geo; - CGI::TexturePwn _tex; - CGI::CSHandle _csh; - PParticlesDelegate _pDelegate = nullptr; - const float* _pUserZone = nullptr; - BillboardType _billboardType = BillboardType::none; - int _tilesetX = 0; - int _tilesetY = 0; - int _indexCount = 0; - int _capacity = 0; - int _addAt = 0; - int _drawCount = 0; - float _ratio = 1; - float _brightness = 1; - float _bounceStrength = 0.5f; - float _gravityStrength = 1; - float _windStrength = 0; - float _flowRemainder = 0; - float _particlesPerSecond = 0; - float _zone = 0; - bool _collide = false; - bool _decal = false; - bool _flowEnabled = true; - - public: - Particles(); - ~Particles(); - - static void InitStatic(); - static void DoneStatic(); - - void Init(CSZ url); - void Done(); - - void Update(); // Call this after adding particles! - void Draw(); - - Str GetURL() const { return _C(_url); } - int GetTilesetX() const { return _tilesetX; } - int GetTilesetY() const { return _tilesetY; } - int GetCapacity() const { return _capacity; } - int GetDrawCount() const { return _drawCount; } - - PParticlesDelegate SetDelegate(PParticlesDelegate p) { return Utils::Swap(_pDelegate, p); } - void SetUserZone(const float* pZone) { _pUserZone = pZone; } - - void GetLifeTime(float& mn, float& mx) const; - void SetLifeTime(float mn, float mx); - void GetSpeed(float& mn, float& mx) const; - void SetSpeed(float mn, float mx); - void GetBeginAdditive(float& mn, float& mx) const; - void SetBeginAdditive(float mn, float mx); - void GetBeginColor(RVector4 mn, RVector4 mx) const; - void SetBeginColor(RcVector4 mn, RcVector4 mx); - void GetEndColor(RVector4 mn, RVector4 mx) const; - void SetEndColor(RcVector4 mn, RcVector4 mx); - void GetEndAdditive(float& mn, float& mx) const; - void SetEndAdditive(float mn, float mx); - void GetBeginSize(float& mn, float& mx) const; - void SetBeginSize(float mn, float mx); - void GetEndSize(float& mn, float& mx) const; - void SetEndSize(float mn, float mx); - void GetBeginSpin(float& mn, float& mx) const; - void SetBeginSpin(float mn, float mx); - void GetEndSpin(float& mn, float& mx) const; - void SetEndSpin(float mn, float mx); - float GetBrightness() const { return _brightness; } - void SetBrightness(float value) { _brightness = value; } - float GetBounce() const { return _bounceStrength; } - void SetBounce(float value) { _bounceStrength = value; } - float GetGravity() const { return _gravityStrength; } - void SetGravity(float value) { _gravityStrength = value; } - float GetWind() const { return _windStrength; } - void SetWind(float value) { _windStrength = value; } - float GetParticlesPerSecond() const { return _particlesPerSecond; } - void SetParticlesPerSecond(float value) { _particlesPerSecond = value; } - float GetZone() const { return _zone; } - void SetZone(float value) { _zone = value; } - - int Add(RcPoint3 pos, RcVector3 dir, - float scale = 1, PcVector4 pUserColor = nullptr, void* pUser = nullptr); - void AddFlow(RcPoint3 pos, RcVector3 dirOffset, - float scale = 1, PcVector4 pUserColor = nullptr, float* pUserFlowRemainder = nullptr, float intensity = 1); - bool IsFlowEnabled() const { return _flowEnabled; } - void EnableFlow(bool b = true) { _flowEnabled = b; } - - bool TimeCorrectedVerletIntegration(RParticle particle, RPoint3 point, RVector3 normal); - bool EulerIntegration(RParticle particle, RPoint3 point, RVector3 normal); - - void PushPointSprite(int index, RcVector4 color, float size, float additive); - void PushBillboard(int index, RcVector4 color, RcTransform3 matW, float additive); - Transform3 GetBillboardMatrix(int index, float size, float spin, RcVector3 up, RcVector3 normal, RTransform3 matAim); + enum PIPE + { + PIPE_MAIN, + PIPE_BILLBOARDS, + PIPE_COUNT }; - VERUS_TYPEDEFS(Particles); - } + + struct Vertex + { + glm::vec4 pos; + glm::vec2 tc0; + UINT32 color; + float psize; + }; + VERUS_TYPEDEFS(Vertex); + + static CGI::ShaderPwn s_shader; + static CGI::PipelinePwns s_pipe; + static UB_ParticlesVS s_ubParticlesVS; + static UB_ParticlesFS s_ubParticlesFS; + + Vector4 _tilesetSize = Vector4::Replicate(1); + Vector3 _lifeTimeRange = Vector3(0, 1, 1); + Vector3 _speedRange = Vector3(0, 1, 1); + Vector3 _beginAdditiveRange = Vector3(0); + Vector3 _endAdditiveRange = Vector3(0); + Vector4 _beginColorMin = Vector4(0); + Vector4 _beginColorDelta = Vector4(0); + Vector4 _endColorMin = Vector4(0); + Vector4 _endColorDelta = Vector4(0); + Vector3 _beginSizeRange = Vector3(0, 1, 1); + Vector3 _endSizeRange = Vector3(0, 1, 1); + Vector3 _beginSpinRange = Vector3(0, 1, 1); + Vector3 _endSpinRange = Vector3(0, 1, 1); + Vector3 _gravity = Vector3(0, -9.8f, 0); + String _url; + Vector _vParticles; + Vector _vVB; + Vector _vIB; + CGI::GeometryPwn _geo; + CGI::TexturePwn _tex; + CGI::CSHandle _csh; + PParticlesDelegate _pDelegate = nullptr; + const float* _pUserZone = nullptr; + BillboardType _billboardType = BillboardType::none; + int _tilesetX = 0; + int _tilesetY = 0; + int _indexCount = 0; + int _capacity = 0; + int _addAt = 0; + int _drawCount = 0; + float _ratio = 1; + float _brightness = 1; + float _bounceStrength = 0.5f; + float _gravityStrength = 1; + float _windStrength = 0; + float _flowRemainder = 0; + float _particlesPerSecond = 0; + float _zone = 0; + bool _collide = false; + bool _decal = false; + bool _flowEnabled = true; + + public: + Particles(); + ~Particles(); + + static void InitStatic(); + static void DoneStatic(); + + void Init(CSZ url); + void Done(); + + void Update(); // Call this after adding particles! + void Draw(); + + Str GetURL() const { return _C(_url); } + int GetTilesetX() const { return _tilesetX; } + int GetTilesetY() const { return _tilesetY; } + int GetCapacity() const { return _capacity; } + int GetDrawCount() const { return _drawCount; } + + PParticlesDelegate SetDelegate(PParticlesDelegate p) { return Utils::Swap(_pDelegate, p); } + void SetUserZone(const float* pZone) { _pUserZone = pZone; } + + void GetLifeTime(float& mn, float& mx) const; + void SetLifeTime(float mn, float mx); + void GetSpeed(float& mn, float& mx) const; + void SetSpeed(float mn, float mx); + void GetBeginAdditive(float& mn, float& mx) const; + void SetBeginAdditive(float mn, float mx); + void GetBeginColor(RVector4 mn, RVector4 mx) const; + void SetBeginColor(RcVector4 mn, RcVector4 mx); + void GetEndColor(RVector4 mn, RVector4 mx) const; + void SetEndColor(RcVector4 mn, RcVector4 mx); + void GetEndAdditive(float& mn, float& mx) const; + void SetEndAdditive(float mn, float mx); + void GetBeginSize(float& mn, float& mx) const; + void SetBeginSize(float mn, float mx); + void GetEndSize(float& mn, float& mx) const; + void SetEndSize(float mn, float mx); + void GetBeginSpin(float& mn, float& mx) const; + void SetBeginSpin(float mn, float mx); + void GetEndSpin(float& mn, float& mx) const; + void SetEndSpin(float mn, float mx); + float GetBrightness() const { return _brightness; } + void SetBrightness(float value) { _brightness = value; } + float GetBounce() const { return _bounceStrength; } + void SetBounce(float value) { _bounceStrength = value; } + float GetGravity() const { return _gravityStrength; } + void SetGravity(float value) { _gravityStrength = value; } + float GetWind() const { return _windStrength; } + void SetWind(float value) { _windStrength = value; } + float GetParticlesPerSecond() const { return _particlesPerSecond; } + void SetParticlesPerSecond(float value) { _particlesPerSecond = value; } + float GetZone() const { return _zone; } + void SetZone(float value) { _zone = value; } + + int Add(RcPoint3 pos, RcVector3 dir, + float scale = 1, PcVector4 pUserColor = nullptr, void* pUser = nullptr); + void AddFlow(RcPoint3 pos, RcVector3 dirOffset, + float scale = 1, PcVector4 pUserColor = nullptr, float* pUserFlowRemainder = nullptr, float intensity = 1); + bool IsFlowEnabled() const { return _flowEnabled; } + void EnableFlow(bool b = true) { _flowEnabled = b; } + + bool TimeCorrectedVerletIntegration(RParticle particle, RPoint3 point, RVector3 normal); + bool EulerIntegration(RParticle particle, RPoint3 point, RVector3 normal); + + void PushPointSprite(int index, RcVector4 color, float size, float additive); + void PushBillboard(int index, RcVector4 color, RcTransform3 matW, float additive); + Transform3 GetBillboardMatrix(int index, float size, float spin, RcVector3 up, RcVector3 normal, RTransform3 matAim); + }; + VERUS_TYPEDEFS(Particles); } diff --git a/Verus/src/Effects/Ssao.h b/Verus/src/Effects/Ssao.h index ef79c58..e7c63c3 100644 --- a/Verus/src/Effects/Ssao.h +++ b/Verus/src/Effects/Ssao.h @@ -1,47 +1,44 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Effects { - namespace Effects + class Ssao : public Singleton, public Object { - class Ssao : public Singleton, public Object - { #include "../Shaders/Ssao.inc.hlsl" - static UB_SsaoVS s_ubSsaoVS; - static UB_SsaoFS s_ubSsaoFS; + static UB_SsaoVS s_ubSsaoVS; + static UB_SsaoFS s_ubSsaoFS; - CGI::ShaderPwn _shader; - CGI::PipelinePwn _pipe; - CGI::TexturePwn _texRandNormals; - CGI::RPHandle _rph; - CGI::FBHandle _fbh; - CGI::CSHandle _csh; - float _smallRad = 0.02f; - float _largeRad = 0.05f; - float _weightScale = 10; - float _weightBias = 2.5f; - bool _blur = true; - bool _editMode = false; + CGI::ShaderPwn _shader; + CGI::PipelinePwn _pipe; + CGI::TexturePwn _texRandNormals; + CGI::RPHandle _rph; + CGI::FBHandle _fbh; + CGI::CSHandle _csh; + float _smallRad = 0.02f; + float _largeRad = 0.05f; + float _weightScale = 10; + float _weightBias = 2.5f; + bool _blur = true; + bool _editMode = false; - public: - Ssao(); - ~Ssao(); + public: + Ssao(); + ~Ssao(); - void Init(); - void InitCmd(); - void Done(); + void Init(); + void InitCmd(); + void Done(); - void OnSwapChainResized(); + void OnSwapChainResized(); - void Generate(); + void Generate(); - void UpdateRandNormalsTexture(); + void UpdateRandNormalsTexture(); - bool IsEditMode() const { return _editMode; } - void ToggleEditMode() { _editMode = !_editMode; } - }; - VERUS_TYPEDEFS(Ssao); - } + bool IsEditMode() const { return _editMode; } + void ToggleEditMode() { _editMode = !_editMode; } + }; + VERUS_TYPEDEFS(Ssao); } diff --git a/Verus/src/Effects/Ssr.h b/Verus/src/Effects/Ssr.h index 8a627d4..1f6c188 100644 --- a/Verus/src/Effects/Ssr.h +++ b/Verus/src/Effects/Ssr.h @@ -1,55 +1,52 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Effects { - namespace Effects + class Ssr : public Singleton, public Object { - class Ssr : public Singleton, public Object - { #include "../Shaders/Ssr.inc.hlsl" - enum PIPE - { - PIPE_MAIN, - PIPE_DEBUG_CUBE_MAP, - PIPE_COUNT - }; - - static UB_SsrVS s_ubSsrVS; - static UB_SsrFS s_ubSsrFS; - - CGI::ShaderPwn _shader; - CGI::PipelinePwns _pipe; - CGI::RPHandle _rph; - CGI::FBHandle _fbh; - CGI::CSHandle _csh; - float _radius = 2.2f; - float _depthBias = 0.03f; - float _thickness = 0.3f; - float _equalizeDist = 20; - bool _cubeMapDebugMode = false; - bool _editMode = false; - - public: - Ssr(); - ~Ssr(); - - void Init(); - void Done(); - - void OnSwapChainResized(); - - bool BindDescriptorSetTextures(); - - void Generate(); - - bool IsCubeMapDebugMode() const { return _cubeMapDebugMode; } - void ToggleCubeMapDebugMode() { _cubeMapDebugMode = !_cubeMapDebugMode; } - - bool IsEditMode() const { return _editMode; } - void ToggleEditMode() { _editMode = !_editMode; } + enum PIPE + { + PIPE_MAIN, + PIPE_DEBUG_CUBE_MAP, + PIPE_COUNT }; - VERUS_TYPEDEFS(Ssr); - } + + static UB_SsrVS s_ubSsrVS; + static UB_SsrFS s_ubSsrFS; + + CGI::ShaderPwn _shader; + CGI::PipelinePwns _pipe; + CGI::RPHandle _rph; + CGI::FBHandle _fbh; + CGI::CSHandle _csh; + float _radius = 2.2f; + float _depthBias = 0.03f; + float _thickness = 0.3f; + float _equalizeDist = 20; + bool _cubeMapDebugMode = false; + bool _editMode = false; + + public: + Ssr(); + ~Ssr(); + + void Init(); + void Done(); + + void OnSwapChainResized(); + + bool BindDescriptorSetTextures(); + + void Generate(); + + bool IsCubeMapDebugMode() const { return _cubeMapDebugMode; } + void ToggleCubeMapDebugMode() { _cubeMapDebugMode = !_cubeMapDebugMode; } + + bool IsEditMode() const { return _editMode; } + void ToggleEditMode() { _editMode = !_editMode; } + }; + VERUS_TYPEDEFS(Ssr); } diff --git a/Verus/src/Extra/BaseConvert.h b/Verus/src/Extra/BaseConvert.h index 7df3379..c5289fb 100644 --- a/Verus/src/Extra/BaseConvert.h +++ b/Verus/src/Extra/BaseConvert.h @@ -1,244 +1,241 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Extra { - namespace Extra + struct BaseConvertDelegate; + + class BaseConvert { - struct BaseConvertDelegate; - - class BaseConvert + public: + class Mesh { public: - class Mesh + enum class Found : int { - public: - enum class Found : int - { - null = 0, - faces = (1 << 0), - posAndTexCoord0 = (1 << 1), - normals = (1 << 2), - tangentSpace = (1 << 3), - skinning = (1 << 4), - texCoord1 = (1 << 5) - }; - - struct UberVertex - { - glm::vec3 _pos; - glm::vec3 _nrm; - glm::vec2 _tc0; - glm::vec2 _tc1; - glm::vec3 _tan; - glm::vec3 _bin; - UINT32 _bi[4]; - float _bw[4]; - int _currentWeight = 0; - - UberVertex(); - bool operator==(const UberVertex& that) const; - void Add(UINT32 index, float weight); - void CompileBits(UINT32& ii, UINT32& ww) const; - UINT32 GetDominantIndex(); - }; - VERUS_TYPEDEFS(UberVertex); - - struct Face - { - UINT16 _indices[3]; - }; - VERUS_TYPEDEFS(Face); - - struct Bone - { - String _name; - String _parentName; - glm::mat4 _trLocal; - glm::mat4 _trGlobal; - glm::mat4 _trToBoneSpace; // Inverse of Global. - bool _usedInSkin = false; - }; - VERUS_TYPEDEFS(Bone); - - private: - struct Vec3Short - { - short _x; - short _y; - short _z; - }; - - struct Vec2Short - { - short _u; - short _v; - }; - - struct Vec3Char - { - char _x; - char _y; - char _z; - }; - - struct Aabb - { - glm::vec3 _mn = glm::vec3(+FLT_MAX); - glm::vec3 _mx = glm::vec3(-FLT_MAX); - - void Reset(); - void Include(const glm::vec3& point); - glm::vec3 GetExtents() const; - }; - - BaseConvert* _pBaseConvert = nullptr; - String _name; - String _copyOf; - Vector _vUberVerts; - Vector _vFaces; - Vector _vZipPos; - Vector _vZipNormal; - Vector _vZipTan; - Vector _vZipBin; - Vector _vZipTc0; - Vector _vZipTc1; - Vector _vBones; - int _vertCount = 0; - int _faceCount = 0; - int _boneCount = 0; - glm::vec3 _posScale; - glm::vec3 _posBias; - glm::vec2 _tc0Scale; - glm::vec2 _tc0Bias; - glm::vec2 _tc1Scale; - glm::vec2 _tc1Bias; - glm::mat4 _matBoneAxis; - glm::mat4 _matGlobal; - glm::mat4 _worldSpace; - Found _found = Found::null; - int _materialIndex = 0; - - public: - Mesh(BaseConvert* pBaseConvert); - ~Mesh(); - - PBone FindBone(CSZ name); - - VERUS_P(void CleanBones()); - VERUS_P(void Optimize()); - VERUS_P(void RecalculateTangentSpace()); - VERUS_P(void Compress()); - void SerializeX3D3(IO::RFile file); - - RcString GetName() const { return _name; } - void SetName(CSZ name) { _name = name; } - - const glm::mat4& GetBoneAxisMatrix() const { return _matBoneAxis; } - - const glm::mat4& GetGlobalMatrix() const { return _matGlobal; } - void SetGlobalMatrix(const glm::mat4& mat) { _matGlobal = mat; } - - const glm::mat4& GetWorldSpaceMatrix() const { return _worldSpace; } - void SetWorldSpaceMatrix(const glm::mat4& mat) { _worldSpace = mat; } - - int GetVertCount() const { return _vertCount; } - int GetFaceCount() const { return _faceCount; } - int GetBoneCount() const { return _boneCount; } - void SetVertCount(int count) { _vertCount = count; } - void SetFaceCount(int count) { _faceCount = count; } - void SetBoneCount(int count) { _boneCount = count; } - - void ResizeVertsArray(int size) { _vUberVerts.resize(size); } - void ResizeFacesArray(int size) { _vFaces.resize(size); } - - RUberVertex GetSetVertexAt(int index) { return _vUberVerts[index]; } - RFace GetSetFaceAt(int index) { return _vFaces[index]; } - - void AddFoundFlag(Found flag) { _found |= flag; } - - int GetNextBoneIndex() const { return Utils::Cast32(_vBones.size()); } - void AddBone(RcBone bone) { _vBones.push_back(bone); } - - bool IsCopyOf(Mesh& that); - bool IsCopy() const { return !_copyOf.empty(); } - RcString GetCopyOfName() const { return _copyOf; } - - int GetMaterialIndex() const { return _materialIndex; } - void SetMaterialIndex(int index) { _materialIndex = index; } - }; - VERUS_TYPEDEFS(Mesh); - - struct SubKey - { - Quat _q; - bool _redundant = false; + null = 0, + faces = (1 << 0), + posAndTexCoord0 = (1 << 1), + normals = (1 << 2), + tangentSpace = (1 << 3), + skinning = (1 << 4), + texCoord1 = (1 << 5) }; - struct AnimationKey // Represents one bone's channel in motion file. + struct UberVertex { - Vector _vFrame; - int _type = 0; - int _logicFrameCount = 0; + glm::vec3 _pos; + glm::vec3 _nrm; + glm::vec2 _tc0; + glm::vec2 _tc1; + glm::vec3 _tan; + glm::vec3 _bin; + UINT32 _bi[4]; + float _bw[4]; + int _currentWeight = 0; - void DetectRedundantFrames(float threshold = 0.0001f); + UberVertex(); + bool operator==(const UberVertex& that) const; + void Add(UINT32 index, float weight); + void CompileBits(UINT32& ii, UINT32& ww) const; + UINT32 GetDominantIndex(); + }; + VERUS_TYPEDEFS(UberVertex); + + struct Face + { + UINT16 _indices[3]; + }; + VERUS_TYPEDEFS(Face); + + struct Bone + { + String _name; + String _parentName; + glm::mat4 _trLocal; + glm::mat4 _trGlobal; + glm::mat4 _trToBoneSpace; // Inverse of Global. + bool _usedInSkin = false; + }; + VERUS_TYPEDEFS(Bone); + + private: + struct Vec3Short + { + short _x; + short _y; + short _z; }; - struct Animation // Represents one bone in motion file. + struct Vec2Short { - String _name; - Vector _vAnimKeys; + short _u; + short _v; }; - struct AnimationSet // Represents one motion file. + struct Vec3Char { - String _name; - Vector _vAnimations; - - void CleanUp(); + char _x; + char _y; + char _z; }; - protected: - typedef Map TMapBoneNames; + struct Aabb + { + glm::vec3 _mn = glm::vec3(+FLT_MAX); + glm::vec3 _mx = glm::vec3(-FLT_MAX); - TMapBoneNames _mapBoneNames; - BaseConvertDelegate* _pDelegate = nullptr; - Vector _vMeshes; - Vector _vAnimSets; - std::unique_ptr _pCurrentMesh; + void Reset(); + void Include(const glm::vec3& point); + glm::vec3 GetExtents() const; + }; + + BaseConvert* _pBaseConvert = nullptr; + String _name; + String _copyOf; + Vector _vUberVerts; + Vector _vFaces; + Vector _vZipPos; + Vector _vZipNormal; + Vector _vZipTan; + Vector _vZipBin; + Vector _vZipTc0; + Vector _vZipTc1; + Vector _vBones; + int _vertCount = 0; + int _faceCount = 0; + int _boneCount = 0; + glm::vec3 _posScale; + glm::vec3 _posBias; + glm::vec2 _tc0Scale; + glm::vec2 _tc0Bias; + glm::vec2 _tc1Scale; + glm::vec2 _tc1Bias; + glm::mat4 _matBoneAxis; + glm::mat4 _matGlobal; + glm::mat4 _worldSpace; + Found _found = Found::null; + int _materialIndex = 0; public: - BaseConvert(); - ~BaseConvert(); + Mesh(BaseConvert* pBaseConvert); + ~Mesh(); - void LoadBoneNames(CSZ pathname); - String RenameBone(CSZ name); + PBone FindBone(CSZ name); - protected: - PMesh AddMesh(PMesh pMesh); - PMesh FindMesh(CSZ name); - void DeleteAll(); + VERUS_P(void CleanBones()); + VERUS_P(void Optimize()); + VERUS_P(void RecalculateTangentSpace()); + VERUS_P(void Compress()); + void SerializeX3D3(IO::RFile file); - void OnProgress(float percent); - void OnProgressText(CSZ txt); + RcString GetName() const { return _name; } + void SetName(CSZ name) { _name = name; } - virtual bool UseAreaBasedNormals() { return false; } - virtual bool UseRigidBones() { return false; } - virtual Str GetPathname() { return ""; } + const glm::mat4& GetBoneAxisMatrix() const { return _matBoneAxis; } - void SerializeMotions(SZ pathname); + const glm::mat4& GetGlobalMatrix() const { return _matGlobal; } + void SetGlobalMatrix(const glm::mat4& mat) { _matGlobal = mat; } + + const glm::mat4& GetWorldSpaceMatrix() const { return _worldSpace; } + void SetWorldSpaceMatrix(const glm::mat4& mat) { _worldSpace = mat; } + + int GetVertCount() const { return _vertCount; } + int GetFaceCount() const { return _faceCount; } + int GetBoneCount() const { return _boneCount; } + void SetVertCount(int count) { _vertCount = count; } + void SetFaceCount(int count) { _faceCount = count; } + void SetBoneCount(int count) { _boneCount = count; } + + void ResizeVertsArray(int size) { _vUberVerts.resize(size); } + void ResizeFacesArray(int size) { _vFaces.resize(size); } + + RUberVertex GetSetVertexAt(int index) { return _vUberVerts[index]; } + RFace GetSetFaceAt(int index) { return _vFaces[index]; } + + void AddFoundFlag(Found flag) { _found |= flag; } + + int GetNextBoneIndex() const { return Utils::Cast32(_vBones.size()); } + void AddBone(RcBone bone) { _vBones.push_back(bone); } + + bool IsCopyOf(Mesh& that); + bool IsCopy() const { return !_copyOf.empty(); } + RcString GetCopyOfName() const { return _copyOf; } + + int GetMaterialIndex() const { return _materialIndex; } + void SetMaterialIndex(int index) { _materialIndex = index; } }; - VERUS_TYPEDEFS(BaseConvert); + VERUS_TYPEDEFS(Mesh); - struct BaseConvertDelegate + struct SubKey { - virtual void BaseConvert_OnProgress(float percent) = 0; - virtual void BaseConvert_OnProgressText(CSZ txt) = 0; - virtual void BaseConvert_Optimize( - Vector& vVB, - Vector& vIB) = 0; - virtual bool BaseConvert_CanOverwriteFile(CSZ filename) { return true; } + Quat _q; + bool _redundant = false; }; - VERUS_TYPEDEFS(BaseConvertDelegate); - } + + struct AnimationKey // Represents one bone's channel in motion file. + { + Vector _vFrame; + int _type = 0; + int _logicFrameCount = 0; + + void DetectRedundantFrames(float threshold = 0.0001f); + }; + + struct Animation // Represents one bone in motion file. + { + String _name; + Vector _vAnimKeys; + }; + + struct AnimationSet // Represents one motion file. + { + String _name; + Vector _vAnimations; + + void CleanUp(); + }; + + protected: + typedef Map TMapBoneNames; + + TMapBoneNames _mapBoneNames; + BaseConvertDelegate* _pDelegate = nullptr; + Vector _vMeshes; + Vector _vAnimSets; + std::unique_ptr _pCurrentMesh; + + public: + BaseConvert(); + ~BaseConvert(); + + void LoadBoneNames(CSZ pathname); + String RenameBone(CSZ name); + + protected: + PMesh AddMesh(PMesh pMesh); + PMesh FindMesh(CSZ name); + void DeleteAll(); + + void OnProgress(float percent); + void OnProgressText(CSZ txt); + + virtual bool UseAreaBasedNormals() { return false; } + virtual bool UseRigidBones() { return false; } + virtual Str GetPathname() { return ""; } + + void SerializeMotions(SZ pathname); + }; + VERUS_TYPEDEFS(BaseConvert); + + struct BaseConvertDelegate + { + virtual void BaseConvert_OnProgress(float percent) = 0; + virtual void BaseConvert_OnProgressText(CSZ txt) = 0; + virtual void BaseConvert_Optimize( + Vector& vVB, + Vector& vIB) = 0; + virtual bool BaseConvert_CanOverwriteFile(CSZ filename) { return true; } + }; + VERUS_TYPEDEFS(BaseConvertDelegate); } diff --git a/Verus/src/Extra/ConvertGLTF.h b/Verus/src/Extra/ConvertGLTF.h index c949737..46c07c4 100644 --- a/Verus/src/Extra/ConvertGLTF.h +++ b/Verus/src/Extra/ConvertGLTF.h @@ -1,76 +1,73 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Extra { - namespace Extra + class ConvertGLTF : public Singleton, public Object, public BaseConvert { - class ConvertGLTF : public Singleton, public Object, public BaseConvert + public: + struct Desc { - public: - struct Desc - { - glm::vec3 _bias = glm::vec3(0); - float _scaleFactor = 1; - float _angle = 0; - float _areaBasedNormals = 0; - bool _flipNormals = false; - bool _flipFaces = false; - bool _useRigidBones = false; - bool _convertAsScene = false; - }; - VERUS_TYPEDEFS(Desc); - - private: - struct NodeExtraData - { - int _parent = -1; - glm::mat4 _trLocal; - glm::mat4 _trGlobal; - }; - - tinygltf::TinyGLTF _context; - tinygltf::Model _model; - String _pathname; - Vector _vData; - Vector _vNodeExtraData; - std::future _future; - Desc _desc; - - public: - ConvertGLTF(); - ~ConvertGLTF(); - - void Init(PBaseConvertDelegate p, RcDesc desc); - void Done(); - - virtual bool UseAreaBasedNormals() override; - virtual bool UseRigidBones() override; - virtual Str GetPathname() override; - - void ParseData(CSZ pathname); - void SerializeAll(CSZ pathname); - - void AsyncRun(CSZ pathname); - void AsyncJoin(); - bool IsAsyncStarted() const; - bool IsAsyncFinished() const; - - private: - void LoadFromFile(CSZ pathname); - - void ProcessNodeRecursive(const tinygltf::Node& node, int nodeIndex, bool computeExtraData); - void ProcessMesh(const tinygltf::Mesh& mesh, int nodeIndex, int skinIndex); - void ProcessSkin(const tinygltf::Skin& skin); - void ProcessAnimation(const tinygltf::Animation& anim); - - void TryResizeVertsArray(int vertCount); - - static glm::vec3 ToVec3(const double* p); - static glm::quat ToQuat(const double* p); - static glm::mat4 ToMat4(const double* p); - static glm::mat4 GetNodeMatrix(const tinygltf::Node& node); + glm::vec3 _bias = glm::vec3(0); + float _scaleFactor = 1; + float _angle = 0; + float _areaBasedNormals = 0; + bool _flipNormals = false; + bool _flipFaces = false; + bool _useRigidBones = false; + bool _convertAsScene = false; }; - VERUS_TYPEDEFS(ConvertGLTF); - } + VERUS_TYPEDEFS(Desc); + + private: + struct NodeExtraData + { + int _parent = -1; + glm::mat4 _trLocal; + glm::mat4 _trGlobal; + }; + + tinygltf::TinyGLTF _context; + tinygltf::Model _model; + String _pathname; + Vector _vData; + Vector _vNodeExtraData; + std::future _future; + Desc _desc; + + public: + ConvertGLTF(); + ~ConvertGLTF(); + + void Init(PBaseConvertDelegate p, RcDesc desc); + void Done(); + + virtual bool UseAreaBasedNormals() override; + virtual bool UseRigidBones() override; + virtual Str GetPathname() override; + + void ParseData(CSZ pathname); + void SerializeAll(CSZ pathname); + + void AsyncRun(CSZ pathname); + void AsyncJoin(); + bool IsAsyncStarted() const; + bool IsAsyncFinished() const; + + private: + void LoadFromFile(CSZ pathname); + + void ProcessNodeRecursive(const tinygltf::Node& node, int nodeIndex, bool computeExtraData); + void ProcessMesh(const tinygltf::Mesh& mesh, int nodeIndex, int skinIndex); + void ProcessSkin(const tinygltf::Skin& skin); + void ProcessAnimation(const tinygltf::Animation& anim); + + void TryResizeVertsArray(int vertCount); + + static glm::vec3 ToVec3(const double* p); + static glm::quat ToQuat(const double* p); + static glm::mat4 ToMat4(const double* p); + static glm::mat4 GetNodeMatrix(const tinygltf::Node& node); + }; + VERUS_TYPEDEFS(ConvertGLTF); } diff --git a/Verus/src/Extra/ConvertX.h b/Verus/src/Extra/ConvertX.h index 45c5c31..1b68911 100644 --- a/Verus/src/Extra/ConvertX.h +++ b/Verus/src/Extra/ConvertX.h @@ -1,127 +1,124 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Extra { - namespace Extra + class ConvertX : public Singleton, public Object, public BaseConvert { - class ConvertX : public Singleton, public Object, public BaseConvert + public: + struct Desc { - public: - struct Desc - { - glm::vec3 _bias = glm::vec3(0); - float _scaleFactor = 1; - float _angle = 0; - float _areaBasedNormals = 0; - bool _useRigidBones = false; - bool _convertAsScene = false; - bool _useDefaultMaterial = false; - bool _rightHanded = true; - }; - VERUS_TYPEDEFS(Desc); - - private: - struct Frame - { - String _name; - String _parentName; - glm::mat4 _trLocal; - glm::mat4 _trGlobal; - }; - VERUS_TYPEDEFS(Frame); - - struct Material - { - String _name; - String _copyOf; - String _textureFilename; - glm::vec4 _faceColor; - glm::vec3 _specularColor; - glm::vec3 _emissiveColor; - float _power = 1; - - bool IsCopyOf(const Material& that) - { - const float e = 0.01f; - return - _textureFilename == that._textureFilename && - glm::all(glm::epsilonEqual(_faceColor, that._faceColor, e)) && - glm::all(glm::epsilonEqual(_specularColor, that._specularColor, e)) && - glm::all(glm::epsilonEqual(_emissiveColor, that._emissiveColor, e)) && - glm::epsilonEqual(_power, that._power, e); - } - }; - VERUS_TYPEDEFS(Material); - - typedef Map TMapFrames; - - Transform3 _trRoot; - String _currentMesh; - String _pathname; - Vector _vData; - const char* _pData; - const char* _pDataBegin; - TMapFrames _mapFrames; - Vector _stackFrames; - Vector _vMaterials; - std::future _future; - Desc _desc; - int _depth = 0; - StringStream _ssDebug; - - public: - ConvertX(); - ~ConvertX(); - - void Init(PBaseConvertDelegate p, RcDesc desc); - void Done(); - - virtual bool UseAreaBasedNormals() override; - virtual bool UseRigidBones() override; - virtual Str GetPathname() override; - - void ParseData(CSZ pathname); - void SerializeAll(CSZ pathname); - - void AsyncRun(CSZ pathname); - void AsyncJoin(); - bool IsAsyncStarted() const; - bool IsAsyncFinished() const; - - private: - void LoadFromFile(CSZ pathname); - - void StreamReadUntil(SZ dest, int destSize, CSZ separator); - void StreamSkipWhitespace(); - void StreamSkipUntil(char c); - - void FixBones(); - - void ParseBlockRecursive(CSZ type, CSZ blockName); - void ParseBlockData_Mesh(); - void ParseBlockData_MeshTextureCoords(); - void ParseBlockData_MeshNormals(); - void ParseBlockData_FVFData(bool declData); - void ParseBlockData_XSkinMeshHeader(); - void ParseBlockData_SkinWeights(); - void ParseBlockData_Frame(CSZ blockName); - void ParseBlockData_FrameTransformMatrix(); - void ParseBlockData_AnimationSet(CSZ blockName); - void ParseBlockData_Animation(CSZ blockName); - void ParseBlockData_AnimationKey(); - void ParseBlockData_Material(); - void ParseBlockData_TextureFilename(); - void ParseBlockData_MeshMaterialList(); - - void OnProgress(float percent); - void OnProgressText(CSZ txt); - - void Debug(CSZ txt); - - void DetectMaterialCopies(); - String GetXmlMaterial(int i); + glm::vec3 _bias = glm::vec3(0); + float _scaleFactor = 1; + float _angle = 0; + float _areaBasedNormals = 0; + bool _useRigidBones = false; + bool _convertAsScene = false; + bool _useDefaultMaterial = false; + bool _rightHanded = true; }; - VERUS_TYPEDEFS(ConvertX); - } + VERUS_TYPEDEFS(Desc); + + private: + struct Frame + { + String _name; + String _parentName; + glm::mat4 _trLocal; + glm::mat4 _trGlobal; + }; + VERUS_TYPEDEFS(Frame); + + struct Material + { + String _name; + String _copyOf; + String _textureFilename; + glm::vec4 _faceColor; + glm::vec3 _specularColor; + glm::vec3 _emissiveColor; + float _power = 1; + + bool IsCopyOf(const Material& that) + { + const float e = 0.01f; + return + _textureFilename == that._textureFilename && + glm::all(glm::epsilonEqual(_faceColor, that._faceColor, e)) && + glm::all(glm::epsilonEqual(_specularColor, that._specularColor, e)) && + glm::all(glm::epsilonEqual(_emissiveColor, that._emissiveColor, e)) && + glm::epsilonEqual(_power, that._power, e); + } + }; + VERUS_TYPEDEFS(Material); + + typedef Map TMapFrames; + + Transform3 _trRoot; + String _currentMesh; + String _pathname; + Vector _vData; + const char* _pData; + const char* _pDataBegin; + TMapFrames _mapFrames; + Vector _stackFrames; + Vector _vMaterials; + std::future _future; + Desc _desc; + int _depth = 0; + StringStream _ssDebug; + + public: + ConvertX(); + ~ConvertX(); + + void Init(PBaseConvertDelegate p, RcDesc desc); + void Done(); + + virtual bool UseAreaBasedNormals() override; + virtual bool UseRigidBones() override; + virtual Str GetPathname() override; + + void ParseData(CSZ pathname); + void SerializeAll(CSZ pathname); + + void AsyncRun(CSZ pathname); + void AsyncJoin(); + bool IsAsyncStarted() const; + bool IsAsyncFinished() const; + + private: + void LoadFromFile(CSZ pathname); + + void StreamReadUntil(SZ dest, int destSize, CSZ separator); + void StreamSkipWhitespace(); + void StreamSkipUntil(char c); + + void FixBones(); + + void ParseBlockRecursive(CSZ type, CSZ blockName); + void ParseBlockData_Mesh(); + void ParseBlockData_MeshTextureCoords(); + void ParseBlockData_MeshNormals(); + void ParseBlockData_FVFData(bool declData); + void ParseBlockData_XSkinMeshHeader(); + void ParseBlockData_SkinWeights(); + void ParseBlockData_Frame(CSZ blockName); + void ParseBlockData_FrameTransformMatrix(); + void ParseBlockData_AnimationSet(CSZ blockName); + void ParseBlockData_Animation(CSZ blockName); + void ParseBlockData_AnimationKey(); + void ParseBlockData_Material(); + void ParseBlockData_TextureFilename(); + void ParseBlockData_MeshMaterialList(); + + void OnProgress(float percent); + void OnProgressText(CSZ txt); + + void Debug(CSZ txt); + + void DetectMaterialCopies(); + String GetXmlMaterial(int i); + }; + VERUS_TYPEDEFS(ConvertX); } diff --git a/Verus/src/GUI/Animator.h b/Verus/src/GUI/Animator.h index 4483c87..1eef3b1 100644 --- a/Verus/src/GUI/Animator.h +++ b/Verus/src/GUI/Animator.h @@ -1,118 +1,115 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + template + struct Animated { - template - struct Animated + T _from = 0; + T _to = 0; + T _current = 0; + float _time = 0; + float _invDuration = 0; + float _delay = 0; + Easing _easing = Easing::none; + + T Lerp(const T& a, const T& b, float ratio) { - T _from = 0; - T _to = 0; - T _current = 0; - float _time = 0; - float _invDuration = 0; - float _delay = 0; - Easing _easing = Easing::none; + return Math::Lerp(a, b, ratio); + } - T Lerp(const T& a, const T& b, float ratio) - { - return Math::Lerp(a, b, ratio); - } - - void Update(float dt) - { - if (_invDuration > 0) - { - if (_time >= 0) - _time += dt; - const float ratio = Math::Clamp((_time - _delay) * _invDuration, 0, 1); - const float ratioWithEasing = Math::ApplyEasing(_easing, ratio); - _current = Lerp(_from, _to, ratioWithEasing); - if (dt > 0 && ratio >= 1) - _invDuration = -_invDuration; - } - } - - void Reset(float reverseTime) - { - _current = _from; - _time = reverseTime; - _invDuration = abs(_invDuration); - Update(0); - } - }; - - class Widget; - class Animator + void Update(float dt) { - struct Video + if (_invDuration > 0) { - int _columnCount = 1; - int _rowCount = 1; - int _frameCount = 1; - float _time = 0; - float _invDuration = 0; - float _delay = 0; - float _uScale = 1; - float _vScale = 1; - float _uBias = 0; - float _vBias = 0; + if (_time >= 0) + _time += dt; + const float ratio = Math::Clamp((_time - _delay) * _invDuration, 0, 1); + const float ratioWithEasing = Math::ApplyEasing(_easing, ratio); + _current = Lerp(_from, _to, ratioWithEasing); + if (dt > 0 && ratio >= 1) + _invDuration = -_invDuration; + } + } - void Update(float dt); - void Reset(float reverseTime); - } _video; + void Reset(float reverseTime) + { + _current = _from; + _time = reverseTime; + _invDuration = abs(_invDuration); + Update(0); + } + }; - Animated _animatedColor; - Animated _animatedRect; - float _postAngle = 0; - float _angle = 0; - float _angleSpeed = 0; - float _pulseScale = 1; - float _pulseScaleAdd = 0; - float _pulseSpeed = 0; - float _timeout = 0; - float _maxTimeout = -1; - float _originalW = 0; - bool _reverse = false; - bool _preserveAspectRatio = false; + class Widget; + class Animator + { + struct Video + { + int _columnCount = 1; + int _rowCount = 1; + int _frameCount = 1; + float _time = 0; + float _invDuration = 0; + float _delay = 0; + float _uScale = 1; + float _vScale = 1; + float _uBias = 0; + float _vBias = 0; - public: - Animator(); - ~Animator(); + void Update(float dt); + void Reset(float reverseTime); + } _video; - bool Update(); - void Parse(pugi::xml_node node, const Widget* pWidget); + Animated _animatedColor; + Animated _animatedRect; + float _postAngle = 0; + float _angle = 0; + float _angleSpeed = 0; + float _pulseScale = 1; + float _pulseScaleAdd = 0; + float _pulseSpeed = 0; + float _timeout = 0; + float _maxTimeout = -1; + float _originalW = 0; + bool _reverse = false; + bool _preserveAspectRatio = false; - void Reset(float reverseTime = 0); + public: + Animator(); + ~Animator(); - RcVector4 GetColor(RcVector4 original) const; - RcVector4 SetColor(RcVector4 color); - RcVector4 SetFromColor(RcVector4 color); + bool Update(); + void Parse(pugi::xml_node node, const Widget* pWidget); - float GetX(float original) const; - float GetY(float original) const; - float GetW(float original) const; - float GetH(float original) const; + void Reset(float reverseTime = 0); - float SetX(float x); - float SetY(float y); - float SetW(float w); - float SetH(float h); + RcVector4 GetColor(RcVector4 original) const; + RcVector4 SetColor(RcVector4 color); + RcVector4 SetFromColor(RcVector4 color); - bool GetVideoBias(float& ub, float& vb) const; + float GetX(float original) const; + float GetY(float original) const; + float GetW(float original) const; + float GetH(float original) const; - float GetAngle() const { return _angle; } - void SetAngle(float a) { _angle = a; } - float GetPostAngle() const { return _postAngle; } - void SetPostAngle(float a) { _postAngle = a; } + float SetX(float x); + float SetY(float y); + float SetW(float w); + float SetH(float h); - float GetPulseScale() const { return _pulseScale; } - float GetPulseScaleAdd() const { return _pulseScaleAdd; } + bool GetVideoBias(float& ub, float& vb) const; - void SetTimeout(float t); - }; - VERUS_TYPEDEFS(Animator); - } + float GetAngle() const { return _angle; } + void SetAngle(float a) { _angle = a; } + float GetPostAngle() const { return _postAngle; } + void SetPostAngle(float a) { _postAngle = a; } + + float GetPulseScale() const { return _pulseScale; } + float GetPulseScaleAdd() const { return _pulseScaleAdd; } + + void SetTimeout(float t); + }; + VERUS_TYPEDEFS(Animator); } diff --git a/Verus/src/GUI/Bars.h b/Verus/src/GUI/Bars.h index d07f0da..263e12b 100644 --- a/Verus/src/GUI/Bars.h +++ b/Verus/src/GUI/Bars.h @@ -1,24 +1,21 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class Bars : public Widget { - class Bars : public Widget - { - float _aspectRatio = 21 / 9.f; + float _aspectRatio = 21 / 9.f; - public: - Bars(); - virtual ~Bars(); + public: + Bars(); + virtual ~Bars(); - static PWidget Make(); + static PWidget Make(); - virtual void Update() override; - virtual void Draw() override; - virtual void Parse(pugi::xml_node node) override; - }; - VERUS_TYPEDEFS(Bars); - } + virtual void Update() override; + virtual void Draw() override; + virtual void Parse(pugi::xml_node node) override; + }; + VERUS_TYPEDEFS(Bars); } diff --git a/Verus/src/GUI/Button.h b/Verus/src/GUI/Button.h index 9b85387..c7f7416 100644 --- a/Verus/src/GUI/Button.h +++ b/Verus/src/GUI/Button.h @@ -1,27 +1,24 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class Button : public Widget { - class Button : public Widget - { - Label _label; - Image _image; - Image _icon; - bool _hasIcon = false; + Label _label; + Image _image; + Image _icon; + bool _hasIcon = false; - public: - Button(); - virtual ~Button(); + public: + Button(); + virtual ~Button(); - static PWidget Make(); + static PWidget Make(); - virtual void Update() override; - virtual void Draw() override; - virtual void Parse(pugi::xml_node node) override; - }; - VERUS_TYPEDEFS(Button); - } + virtual void Update() override; + virtual void Draw() override; + virtual void Parse(pugi::xml_node node) override; + }; + VERUS_TYPEDEFS(Button); } diff --git a/Verus/src/GUI/Chat.h b/Verus/src/GUI/Chat.h index 4a49e5b..2b76180 100644 --- a/Verus/src/GUI/Chat.h +++ b/Verus/src/GUI/Chat.h @@ -1,52 +1,49 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + enum class ChatMessageType : int { - enum class ChatMessageType : int + normal, + system + }; + + class Chat : public Object + { + struct Message { - normal, - system + String _text; + float _time = -FLT_MAX; + ChatMessageType _type = ChatMessageType::normal; }; + VERUS_TYPEDEFS(Message); - class Chat : public Object - { - struct Message - { - String _text; - float _time = -FLT_MAX; - ChatMessageType _type = ChatMessageType::normal; - }; - VERUS_TYPEDEFS(Message); + Vector _vMessages; + String _normalMsgColor; + String _systemMsgColor; + String _nameColor; + String _compiled; + WideString _compiledW; + float _keepFor = 0; + int _writeAt = 0; + int _oldWriteAt = -1; + int _oldMsgIndex = -1; - Vector _vMessages; - String _normalMsgColor; - String _systemMsgColor; - String _nameColor; - String _compiled; - WideString _compiledW; - float _keepFor = 0; - int _writeAt = 0; - int _oldWriteAt = -1; - int _oldMsgIndex = -1; + public: + Chat(); + ~Chat(); - public: - Chat(); - ~Chat(); + void Init(int keepCount = 4, float keepFor = 20); + void Done(); - void Init(int keepCount = 4, float keepFor = 20); - void Done(); + void AddMessage(CSZ txt, CSZ name, ChatMessageType type = ChatMessageType::normal); + CSZ GetText(); + CWSZ GetTextW(); - void AddMessage(CSZ txt, CSZ name, ChatMessageType type = ChatMessageType::normal); - CSZ GetText(); - CWSZ GetTextW(); - - void SetNormalMessageColor(UINT32 color); - void SetSystemMessageColor(UINT32 color); - void SetNameColor(UINT32 color); - }; - VERUS_TYPEDEFS(Chat); - } + void SetNormalMessageColor(UINT32 color); + void SetSystemMessageColor(UINT32 color); + void SetNameColor(UINT32 color); + }; + VERUS_TYPEDEFS(Chat); } diff --git a/Verus/src/GUI/Container.h b/Verus/src/GUI/Container.h index db18788..07b4c53 100644 --- a/Verus/src/GUI/Container.h +++ b/Verus/src/GUI/Container.h @@ -1,40 +1,37 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class Container { - class Container - { - typedef PWidget(*PFNCREATOR)(); - typedef Map TMapCreators; + typedef PWidget(*PFNCREATOR)(); + typedef Map TMapCreators; - TMapCreators _mapCreators; - Vector _vWidgets; + TMapCreators _mapCreators; + Vector _vWidgets; - public: - Container(); - virtual ~Container(); + public: + Container(); + virtual ~Container(); - VERUS_P(void RegisterAll()); - VERUS_P(void RegisterWidget(CSZ type, PFNCREATOR pCreator)); - VERUS_P(PWidget CreateWidget(CSZ type)); + VERUS_P(void RegisterAll()); + VERUS_P(void RegisterWidget(CSZ type, PFNCREATOR pCreator)); + VERUS_P(PWidget CreateWidget(CSZ type)); - void UpdateWidgets(); - void DrawWidgets(); + void UpdateWidgets(); + void DrawWidgets(); - void ParseWidgets(pugi::xml_node node, CSZ sizerID); + void ParseWidgets(pugi::xml_node node, CSZ sizerID); - void ResetAnimators(float reverseTime = 0); + void ResetAnimators(float reverseTime = 0); - virtual bool IsSizer() { return false; } + virtual bool IsSizer() { return false; } - PWidget GetHovered(float x, float y); - PWidget GetWidgetById(CSZ id); - int GetWidgetCount() const { return Utils::Cast32(_vWidgets.size()); } - int GetWidgetIndex(PWidget p); - }; - VERUS_TYPEDEFS(Container); - } + PWidget GetHovered(float x, float y); + PWidget GetWidgetById(CSZ id); + int GetWidgetCount() const { return Utils::Cast32(_vWidgets.size()); } + int GetWidgetIndex(PWidget p); + }; + VERUS_TYPEDEFS(Container); } diff --git a/Verus/src/GUI/Cursor.h b/Verus/src/GUI/Cursor.h index e4ef9f3..ad8e8c5 100644 --- a/Verus/src/GUI/Cursor.h +++ b/Verus/src/GUI/Cursor.h @@ -1,34 +1,31 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class Cursor : public Object { - class Cursor : public Object - { - World::TexturePwn _tex; - CGI::CSHandle _csh; - float _x = 0.5f; - float _y = 0.5f; - float _hotspotX = 0; - float _hotspotY = 0; + World::TexturePwn _tex; + CGI::CSHandle _csh; + float _x = 0.5f; + float _y = 0.5f; + float _hotspotX = 0; + float _hotspotY = 0; - public: - Cursor(); - ~Cursor(); + public: + Cursor(); + ~Cursor(); - void Init(); - void Done(); + void Init(); + void Done(); - void Draw(); + void Draw(); - void MoveHotspotTo(float x, float y); - void MoveBy(float x, float y); + void MoveHotspotTo(float x, float y); + void MoveBy(float x, float y); - float GetX() const { return _x; } - float GetY() const { return _y; } - }; - VERUS_TYPEDEFS(Cursor); - } + float GetX() const { return _x; } + float GetY() const { return _y; } + }; + VERUS_TYPEDEFS(Cursor); } diff --git a/Verus/src/GUI/Font.h b/Verus/src/GUI/Font.h index 97f45db..1e95a41 100644 --- a/Verus/src/GUI/Font.h +++ b/Verus/src/GUI/Font.h @@ -1,101 +1,98 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + // Module for drawing texture-based fonts. + // Use AngelCode Bitmap Font Generator to create required files. + // Geometry uses -32767 to 32767 short texture coordinates. + class Font : public Object { - // Module for drawing texture-based fonts. - // Use AngelCode Bitmap Font Generator to create required files. - // Geometry uses -32767 to 32767 short texture coordinates. - class Font : public Object - { - public: + public: #include "../Shaders/Font.inc.hlsl" - struct CharInfo - { - int _x; - int _y; - int _w; - int _h; - int _xoffset; - int _yoffset; - int _xadvance; - short _s; - short _t; - short _sEnd; - short _tEnd; - }; - VERUS_TYPEDEFS(CharInfo); - - struct Kerning - { - Map _mapAmount; - }; - VERUS_TYPEDEFS(Kerning); - - struct Vertex - { - float _x, _y; - short _s, _t; - BYTE _color[4]; - }; - - typedef Map TMapCharInfo; - typedef Map TMapKerning; - - private: - static CGI::ShaderPwn s_shader; - static UB_FontVS s_ubFontVS; - static UB_FontFS s_ubFontFS; - - CGI::DynamicBuffer _dynBuffer; - CGI::PipelinePwn _pipe; - CGI::TexturePwn _tex; - CGI::CSHandle _csh; - TMapCharInfo _mapCharInfo; - TMapKerning _mapKerning; - int _lineHeight = 0; - int _texSize = 0; - UINT32 _overrideColor = 0; - - public: - struct DrawDesc - { - CWSZ _text = nullptr; - float _x = 0; - float _y = 0; - float _w = 1; - float _h = 1; - int _skippedLineCount = 0; - float _scale = 1; - bool _center = false; - bool _preserveAspectRatio = false; - UINT32 _colorFont = VERUS_COLOR_WHITE; - }; - VERUS_TYPEDEFS(DrawDesc); - - Font(); - ~Font(); - - static void InitStatic(); - static void DoneStatic(); - - void Init(CSZ url); - void Done(); - - void ResetDynamicBuffer(); - - int GetLineHeight() const { return _lineHeight; } - - void Draw(RcDrawDesc dd); - float DrawWord(CWSZ word, int wordLen, float xoffset, float yoffset, bool onlyCalcWidth, UINT32 color, float xScale, float yScale); - int GetTextWidth(CWSZ text, int textLen = -1); - - static float ToFloatX(int size, float scale); - static float ToFloatY(int size, float scale); + struct CharInfo + { + int _x; + int _y; + int _w; + int _h; + int _xoffset; + int _yoffset; + int _xadvance; + short _s; + short _t; + short _sEnd; + short _tEnd; }; - VERUS_TYPEDEFS(Font); - } + VERUS_TYPEDEFS(CharInfo); + + struct Kerning + { + Map _mapAmount; + }; + VERUS_TYPEDEFS(Kerning); + + struct Vertex + { + float _x, _y; + short _s, _t; + BYTE _color[4]; + }; + + typedef Map TMapCharInfo; + typedef Map TMapKerning; + + private: + static CGI::ShaderPwn s_shader; + static UB_FontVS s_ubFontVS; + static UB_FontFS s_ubFontFS; + + CGI::DynamicBuffer _dynBuffer; + CGI::PipelinePwn _pipe; + CGI::TexturePwn _tex; + CGI::CSHandle _csh; + TMapCharInfo _mapCharInfo; + TMapKerning _mapKerning; + int _lineHeight = 0; + int _texSize = 0; + UINT32 _overrideColor = 0; + + public: + struct DrawDesc + { + CWSZ _text = nullptr; + float _x = 0; + float _y = 0; + float _w = 1; + float _h = 1; + int _skippedLineCount = 0; + float _scale = 1; + bool _center = false; + bool _preserveAspectRatio = false; + UINT32 _colorFont = VERUS_COLOR_WHITE; + }; + VERUS_TYPEDEFS(DrawDesc); + + Font(); + ~Font(); + + static void InitStatic(); + static void DoneStatic(); + + void Init(CSZ url); + void Done(); + + void ResetDynamicBuffer(); + + int GetLineHeight() const { return _lineHeight; } + + void Draw(RcDrawDesc dd); + float DrawWord(CWSZ word, int wordLen, float xoffset, float yoffset, bool onlyCalcWidth, UINT32 color, float xScale, float yScale); + int GetTextWidth(CWSZ text, int textLen = -1); + + static float ToFloatX(int size, float scale); + static float ToFloatY(int size, float scale); + }; + VERUS_TYPEDEFS(Font); } diff --git a/Verus/src/GUI/Image.h b/Verus/src/GUI/Image.h index 178ae0d..a1212d9 100644 --- a/Verus/src/GUI/Image.h +++ b/Verus/src/GUI/Image.h @@ -1,35 +1,32 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class Image : public Widget { - class Image : public Widget - { - World::TexturePwn _tex; - CGI::CSHandle _csh; - Vector4 _tcScale = Vector4(1, 1); - Linear _tcBias; - Vector4 _tcScaleMask = Vector4(1, 1); - Vector4 _tcBiasMask = Vector4(0, 0); - bool _useMask = false; - bool _solidColor = false; - bool _add = false; + World::TexturePwn _tex; + CGI::CSHandle _csh; + Vector4 _tcScale = Vector4(1, 1); + Linear _tcBias; + Vector4 _tcScaleMask = Vector4(1, 1); + Vector4 _tcBiasMask = Vector4(0, 0); + bool _useMask = false; + bool _solidColor = false; + bool _add = false; - public: - Image(); - virtual ~Image(); + public: + Image(); + virtual ~Image(); - static PWidget Make(); + static PWidget Make(); - virtual void Update() override; - virtual void Draw() override; - virtual void Parse(pugi::xml_node node) override; + virtual void Update() override; + virtual void Draw() override; + virtual void Parse(pugi::xml_node node) override; - void SetBiasX(float a) { _tcBias.GetValue().setX(a); } - void SetBiasY(float a) { _tcBias.GetValue().setY(a); } - }; - VERUS_TYPEDEFS(Image); - } + void SetBiasX(float a) { _tcBias.GetValue().setX(a); } + void SetBiasY(float a) { _tcBias.GetValue().setY(a); } + }; + VERUS_TYPEDEFS(Image); } diff --git a/Verus/src/GUI/Label.h b/Verus/src/GUI/Label.h index 4e175a7..0dfad9f 100644 --- a/Verus/src/GUI/Label.h +++ b/Verus/src/GUI/Label.h @@ -1,43 +1,40 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class Label : public Widget, public InputFocus { - class Label : public Widget, public InputFocus - { - String _font; - Vector _vChoices; - float _fontScale = 1; - UINT32 _shadowColor = VERUS_COLOR_RGBA(0, 0, 0, 64); - bool _center = false; + String _font; + Vector _vChoices; + float _fontScale = 1; + UINT32 _shadowColor = VERUS_COLOR_RGBA(0, 0, 0, 64); + bool _center = false; - public: - Label(); - virtual ~Label(); + public: + Label(); + virtual ~Label(); - static PWidget Make(); + static PWidget Make(); - virtual void Update() override; - virtual void Draw() override; - virtual void Parse(pugi::xml_node node) override; - virtual PInputFocus AsInputFocus() override { return this; } + virtual void Update() override; + virtual void Draw() override; + virtual void Parse(pugi::xml_node node) override; + virtual PInputFocus AsInputFocus() override { return this; } - void SetShadowColor(UINT32 color) { _shadowColor = color; } + void SetShadowColor(UINT32 color) { _shadowColor = color; } - CSZ GetFont() const { return _C(_font); } - float GetFontScale() const { return _fontScale; } - float GetFontH() const; + CSZ GetFont() const { return _C(_font); } + float GetFontScale() const { return _fontScale; } + float GetFontH() const; - void SetChoice(CSZ s); - void SetChoiceValue(CWSZ s); - void NextChoiceValue(); - int GetChoiceIndex(CWSZ s = nullptr); - void SetChoiceIndex(int index); + void SetChoice(CSZ s); + void SetChoiceValue(CWSZ s); + void NextChoiceValue(); + int GetChoiceIndex(CWSZ s = nullptr); + void SetChoiceIndex(int index); - virtual bool InvokeOnClick(float x, float y) override; - }; - VERUS_TYPEDEFS(Label); - } + virtual bool InvokeOnClick(float x, float y) override; + }; + VERUS_TYPEDEFS(Label); } diff --git a/Verus/src/GUI/Sizer.h b/Verus/src/GUI/Sizer.h index 85c8f8b..4db24e9 100644 --- a/Verus/src/GUI/Sizer.h +++ b/Verus/src/GUI/Sizer.h @@ -1,32 +1,29 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class Sizer : public Widget, public Container { - class Sizer : public Widget, public Container - { - int _rows = 1; - int _cols = 1; - float _rowHeight = 0; - float _colWidth = 0; + int _rows = 1; + int _cols = 1; + float _rowHeight = 0; + float _colWidth = 0; - public: - Sizer(); - virtual ~Sizer(); + public: + Sizer(); + virtual ~Sizer(); - static PWidget Make(); + static PWidget Make(); - virtual void Update() override; - virtual void Draw() override; - virtual void Parse(pugi::xml_node node) override; + virtual void Update() override; + virtual void Draw() override; + virtual void Parse(pugi::xml_node node) override; - virtual PContainer AsContainer() override { return this; } - virtual bool IsSizer() override { return true; } + virtual PContainer AsContainer() override { return this; } + virtual bool IsSizer() override { return true; } - void GetWidgetAbsolutePosition(PWidget pWidget, float& x, float& y); - }; - VERUS_TYPEDEFS(Sizer); - } + void GetWidgetAbsolutePosition(PWidget pWidget, float& x, float& y); + }; + VERUS_TYPEDEFS(Sizer); } diff --git a/Verus/src/GUI/Table.h b/Verus/src/GUI/Table.h index 5b7c25a..ebf0d94 100644 --- a/Verus/src/GUI/Table.h +++ b/Verus/src/GUI/Table.h @@ -1,61 +1,58 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class Table : public Label { - class Table : public Label + struct Cell { - struct Cell - { - String _text; - const void* _pUser = nullptr; - UINT32 _color = VERUS_COLOR_WHITE; - }; - VERUS_TYPEDEFS(Cell); - - struct Row - { - Vector _vCells; - }; - VERUS_TYPEDEFS(Row); - - Row _header; - Vector _vRows; - int _offset = 0; - int _selectedRow = -1; - int _cols = 0; - float _rowHeight = 0.1f; - - public: - Table(); - virtual ~Table(); - - static PWidget Make(); - - virtual void Update() override; - virtual void Draw() override; - virtual void Parse(pugi::xml_node node) override; - virtual PInputFocus AsInputFocus() override { return this; } - - virtual bool InputFocus_KeyOnly() override { return true; } - virtual void InputFocus_Key(int scancode) override; - - void Clear(); - int GetRowCount() const { return Utils::Cast32(_vRows.size()); } - int GetSelectedRow() const { return _selectedRow; } - void SelectRow(int row) { _selectedRow = row; } - void SelectNextRow(); - void SelectPreviousRow(); - void GetCellData(int index, int col, CSZ& txt, UINT32& color, const void** ppUser = nullptr); - void UpdateRow(int index, int col, CSZ txt, UINT32 color = VERUS_COLOR_WHITE, const void* pUser = nullptr); - int AppendRow(); - void Sort(int col, bool asInt, bool descend); - - virtual bool InvokeOnClick(float x, float y) override; - virtual bool InvokeOnKey(int scancode) override; + String _text; + const void* _pUser = nullptr; + UINT32 _color = VERUS_COLOR_WHITE; }; - VERUS_TYPEDEFS(Table); - } + VERUS_TYPEDEFS(Cell); + + struct Row + { + Vector _vCells; + }; + VERUS_TYPEDEFS(Row); + + Row _header; + Vector _vRows; + int _offset = 0; + int _selectedRow = -1; + int _cols = 0; + float _rowHeight = 0.1f; + + public: + Table(); + virtual ~Table(); + + static PWidget Make(); + + virtual void Update() override; + virtual void Draw() override; + virtual void Parse(pugi::xml_node node) override; + virtual PInputFocus AsInputFocus() override { return this; } + + virtual bool InputFocus_KeyOnly() override { return true; } + virtual void InputFocus_Key(int scancode) override; + + void Clear(); + int GetRowCount() const { return Utils::Cast32(_vRows.size()); } + int GetSelectedRow() const { return _selectedRow; } + void SelectRow(int row) { _selectedRow = row; } + void SelectNextRow(); + void SelectPreviousRow(); + void GetCellData(int index, int col, CSZ& txt, UINT32& color, const void** ppUser = nullptr); + void UpdateRow(int index, int col, CSZ txt, UINT32 color = VERUS_COLOR_WHITE, const void* pUser = nullptr); + int AppendRow(); + void Sort(int col, bool asInt, bool descend); + + virtual bool InvokeOnClick(float x, float y) override; + virtual bool InvokeOnKey(int scancode) override; + }; + VERUS_TYPEDEFS(Table); } diff --git a/Verus/src/GUI/TextBox.h b/Verus/src/GUI/TextBox.h index 44faefa..777b8f5 100644 --- a/Verus/src/GUI/TextBox.h +++ b/Verus/src/GUI/TextBox.h @@ -1,56 +1,53 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class TextBox : public Label { - class TextBox : public Label + enum class Rule : int { - enum class Rule : int - { - none, - lower = (1 << 0), - upper = (1 << 1), - number = (1 << 2) - }; - - WideString _fullText; - int _cursor = 0; - int _viewOffset = 0; - int _maxLength = -1; - Cooldown _blinkCooldown = 0.5f; - Rule _rule = Rule::none; - bool _blinkState = false; - - public: - TextBox(); - virtual ~TextBox(); - - static PWidget Make(); - - virtual void Update() override; - virtual void Draw() override; - virtual void Parse(pugi::xml_node node) override; - virtual PInputFocus AsInputFocus() override { return this; } - - void Focus(); - virtual void InputFocus_AddChar(wchar_t c) override; - virtual void InputFocus_DeleteChar() override; - virtual void InputFocus_BackspaceChar() override; - virtual void InputFocus_SetCursor(int pos) override; - virtual void InputFocus_MoveCursor(int delta) override; - virtual void InputFocus_Enter() override; - virtual void InputFocus_Tab() override; - virtual void InputFocus_Key(int scancode) override; - virtual void InputFocus_OnFocus() override; - - void UpdateLabelText(); - - WideStr GetText() const; - void SetText(CWSZ txt); - void SetText(CSZ txt); + none, + lower = (1 << 0), + upper = (1 << 1), + number = (1 << 2) }; - VERUS_TYPEDEFS(TextBox); - } + + WideString _fullText; + int _cursor = 0; + int _viewOffset = 0; + int _maxLength = -1; + Cooldown _blinkCooldown = 0.5f; + Rule _rule = Rule::none; + bool _blinkState = false; + + public: + TextBox(); + virtual ~TextBox(); + + static PWidget Make(); + + virtual void Update() override; + virtual void Draw() override; + virtual void Parse(pugi::xml_node node) override; + virtual PInputFocus AsInputFocus() override { return this; } + + void Focus(); + virtual void InputFocus_AddChar(wchar_t c) override; + virtual void InputFocus_DeleteChar() override; + virtual void InputFocus_BackspaceChar() override; + virtual void InputFocus_SetCursor(int pos) override; + virtual void InputFocus_MoveCursor(int delta) override; + virtual void InputFocus_Enter() override; + virtual void InputFocus_Tab() override; + virtual void InputFocus_Key(int scancode) override; + virtual void InputFocus_OnFocus() override; + + void UpdateLabelText(); + + WideStr GetText() const; + void SetText(CWSZ txt); + void SetText(CSZ txt); + }; + VERUS_TYPEDEFS(TextBox); } diff --git a/Verus/src/GUI/View.h b/Verus/src/GUI/View.h index d090595..69a00eb 100644 --- a/Verus/src/GUI/View.h +++ b/Verus/src/GUI/View.h @@ -1,109 +1,106 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + struct InputFocus { - struct InputFocus + virtual bool InputFocus_KeyOnly() { return false; } + virtual void InputFocus_AddChar(wchar_t c) {} + virtual void InputFocus_DeleteChar() {} + virtual void InputFocus_BackspaceChar() {} + virtual void InputFocus_SetCursor(int pos) {} + virtual void InputFocus_MoveCursor(int delta) {} + virtual void InputFocus_Enter() {} + virtual void InputFocus_Tab() {} + virtual void InputFocus_Key(int scancode) {} + virtual void InputFocus_OnFocus() {} + }; + VERUS_TYPEDEFS(InputFocus); + + struct ViewDelegate + { + virtual void View_SetViewData(View* pView) = 0; + virtual void View_GetViewData(View* pView) = 0; + }; + VERUS_TYPEDEFS(ViewDelegate); + + // Views contain other controls. + // By default they have "done" state. + // You should call ViewManager::FadeTo() after loading. + class View : public Widget, public Container + { + friend class ViewManager; + + enum class State : int { - virtual bool InputFocus_KeyOnly() { return false; } - virtual void InputFocus_AddChar(wchar_t c) {} - virtual void InputFocus_DeleteChar() {} - virtual void InputFocus_BackspaceChar() {} - virtual void InputFocus_SetCursor(int pos) {} - virtual void InputFocus_MoveCursor(int delta) {} - virtual void InputFocus_Enter() {} - virtual void InputFocus_Tab() {} - virtual void InputFocus_Key(int scancode) {} - virtual void InputFocus_OnFocus() {} + fadeIn, + fadeOut, + active, + done }; - VERUS_TYPEDEFS(InputFocus); - struct ViewDelegate - { - virtual void View_SetViewData(View* pView) = 0; - virtual void View_GetViewData(View* pView) = 0; - }; - VERUS_TYPEDEFS(ViewDelegate); + typedef Map TMapStrings; - // Views contain other controls. - // By default they have "done" state. - // You should call ViewManager::FadeTo() after loading. - class View : public Widget, public Container - { - friend class ViewManager; + CGI::CSHandle _csh; + PViewDelegate _pDelegate = nullptr; + String _url; + String _name; + String _locale = "RU"; + TMapStrings _mapStrings; + Vector _vTabList; + World::TexturePwn _tex; + PWidget _pLastHovered = nullptr; + PInputFocus _pInputFocus = nullptr; + State _state = State::done; + Linear _fade; + float _fadeSpeed = 4; + bool _cursor = true; + bool _debug = false; + bool _skipNextKey = false; - enum class State : int - { - fadeIn, - fadeOut, - active, - done - }; + public: + View(); + ~View(); - typedef Map TMapStrings; + virtual void Update() override; + virtual void Draw() override; + virtual void Parse(pugi::xml_node node) override; - CGI::CSHandle _csh; - PViewDelegate _pDelegate = nullptr; - String _url; - String _name; - String _locale = "RU"; - TMapStrings _mapStrings; - Vector _vTabList; - World::TexturePwn _tex; - PWidget _pLastHovered = nullptr; - PInputFocus _pInputFocus = nullptr; - State _state = State::done; - Linear _fade; - float _fadeSpeed = 4; - bool _cursor = true; - bool _debug = false; - bool _skipNextKey = false; + PViewDelegate SetDelegate(PViewDelegate p) { return Utils::Swap(_pDelegate, p); } - public: - View(); - ~View(); + void ResetAnimators(float reverseTime = 0); - virtual void Update() override; - virtual void Draw() override; - virtual void Parse(pugi::xml_node node) override; + void SetData() { if (_pDelegate) _pDelegate->View_SetViewData(this); } + void GetData() { if (_pDelegate) _pDelegate->View_GetViewData(this); } - PViewDelegate SetDelegate(PViewDelegate p) { return Utils::Swap(_pDelegate, p); } + void OnClick(); + void OnDoubleClick(); + void OnKey(int scancode); + void OnChar(wchar_t c); - void ResetAnimators(float reverseTime = 0); + CSZ GetString(int id) const; - void SetData() { if (_pDelegate) _pDelegate->View_SetViewData(this); } - void GetData() { if (_pDelegate) _pDelegate->View_GetViewData(this); } + void BeginFadeIn(); + void BeginFadeOut(); - void OnClick(); - void OnDoubleClick(); - void OnKey(int scancode); - void OnChar(wchar_t c); + Str GetUrl() const { return _C(_url); } + Str GetName() const { return _C(_name); } + Str GetLocale() const { return _C(_locale); } - CSZ GetString(int id) const; + void HideCursor(bool hide = true) { _cursor = !hide; } + bool HasCursor() const { return _cursor; } + bool IsDebug() const { return _debug; } - void BeginFadeIn(); - void BeginFadeOut(); + State GetState() const { return _state; } + void SetState(State state) { _state = state; } - Str GetUrl() const { return _C(_url); } - Str GetName() const { return _C(_name); } - Str GetLocale() const { return _C(_locale); } + PInputFocus GetInFocus() const { return _pInputFocus; } + bool IsInFocus(PInputFocus p) const { return _pInputFocus == p; } + void SetFocus(PInputFocus p); + void SkipNextKey() { _skipNextKey = true; } - void HideCursor(bool hide = true) { _cursor = !hide; } - bool HasCursor() const { return _cursor; } - bool IsDebug() const { return _debug; } - - State GetState() const { return _state; } - void SetState(State state) { _state = state; } - - PInputFocus GetInFocus() const { return _pInputFocus; } - bool IsInFocus(PInputFocus p) const { return _pInputFocus == p; } - void SetFocus(PInputFocus p); - void SkipNextKey() { _skipNextKey = true; } - - void AddControlToTabList(PWidget p) { _vTabList.push_back(p); } - }; - VERUS_TYPEDEFS(View); - } + void AddControlToTabList(PWidget p) { _vTabList.push_back(p); } + }; + VERUS_TYPEDEFS(View); } diff --git a/Verus/src/GUI/ViewController.h b/Verus/src/GUI/ViewController.h index ee08a86..58d6399 100644 --- a/Verus/src/GUI/ViewController.h +++ b/Verus/src/GUI/ViewController.h @@ -1,51 +1,48 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + class ViewController : public Object, public ViewDelegate { - class ViewController : public Object, public ViewDelegate + PView _pView = nullptr; + + public: + ViewController(); + virtual ~ViewController(); + + void Init(CSZ url); + void Done(); + + void Reload(); + + PView GetView() { return _pView; } + PWidget GetWidgetById(CSZ id); + + template + T* Connect(T*& p, CSZ id) { - PView _pView = nullptr; + p = dynamic_cast(GetWidgetById(id)); + VERUS_RT_ASSERT(p); + return p; + } - public: - ViewController(); - virtual ~ViewController(); + void ConnectOnMouseEnter /**/(TFnEvent fn, CSZ id); + void ConnectOnMouseLeave /**/(TFnEvent fn, CSZ id); + void ConnectOnClick /**/(TFnEvent fn, CSZ id); + void ConnectOnDoubleClick/**/(TFnEvent fn, CSZ id); + void ConnectOnKey /**/(TFnEvent fn, CSZ id = nullptr); + void ConnectOnChar /**/(TFnEvent fn, CSZ id = nullptr); + void ConnectOnTimeout /**/(TFnEvent fn, CSZ id = nullptr); - void Init(CSZ url); - void Done(); + void BeginFadeTo(); + void Activate(); + void Deactivate(); - void Reload(); + virtual void View_SetViewData(PView pView) override {} + virtual void View_GetViewData(PView pView) override {} - PView GetView() { return _pView; } - PWidget GetWidgetById(CSZ id); - - template - T* Connect(T*& p, CSZ id) - { - p = dynamic_cast(GetWidgetById(id)); - VERUS_RT_ASSERT(p); - return p; - } - - void ConnectOnMouseEnter /**/(TFnEvent fn, CSZ id); - void ConnectOnMouseLeave /**/(TFnEvent fn, CSZ id); - void ConnectOnClick /**/(TFnEvent fn, CSZ id); - void ConnectOnDoubleClick/**/(TFnEvent fn, CSZ id); - void ConnectOnKey /**/(TFnEvent fn, CSZ id = nullptr); - void ConnectOnChar /**/(TFnEvent fn, CSZ id = nullptr); - void ConnectOnTimeout /**/(TFnEvent fn, CSZ id = nullptr); - - void BeginFadeTo(); - void Activate(); - void Deactivate(); - - virtual void View_SetViewData(PView pView) override {} - virtual void View_GetViewData(PView pView) override {} - - void OnKey(RcEventArgs args); - }; - VERUS_TYPEDEFS(ViewController); - } + void OnKey(RcEventArgs args); + }; + VERUS_TYPEDEFS(ViewController); } diff --git a/Verus/src/GUI/ViewManager.cpp b/Verus/src/GUI/ViewManager.cpp index d064a55..50b2567 100644 --- a/Verus/src/GUI/ViewManager.cpp +++ b/Verus/src/GUI/ViewManager.cpp @@ -123,8 +123,8 @@ bool ViewManager::Update() if (!_cshDebug.IsSet() && _tex[TEX_DEBUG]->IsLoaded()) _cshDebug = _shader->BindDescriptorSetTextures(1, { _tex[TEX_DEBUG] }); - for (auto& x : TStoreFonts::_map) - x.second.ResetDynamicBuffer(); + for (auto& [key, value] : TStoreFonts::_map) + value.ResetDynamicBuffer(); for (const auto& p : _vViews) p->Update(); diff --git a/Verus/src/GUI/ViewManager.h b/Verus/src/GUI/ViewManager.h index 3c3de6d..c373f6f 100644 --- a/Verus/src/GUI/ViewManager.h +++ b/Verus/src/GUI/ViewManager.h @@ -1,109 +1,106 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::GUI { - namespace GUI + // Ultimate GUI manager. + // Contains views ordered by z-depth. + // Contains fonts, cursor and GUI utility functions. + typedef StoreUniqueWithNoRefCount TStoreFonts; + class ViewManager : public Singleton, public Object, public Input::InputFocus, private TStoreFonts { - // Ultimate GUI manager. - // Contains views ordered by z-depth. - // Contains fonts, cursor and GUI utility functions. - typedef StoreUniqueWithNoRefCount TStoreFonts; - class ViewManager : public Singleton, public Object, public Input::InputFocus, private TStoreFonts - { - public: + public: #include "../Shaders/GUI.inc.hlsl" - enum PIPE - { - PIPE_MAIN, - PIPE_MAIN_ADD, - PIPE_MASK, - PIPE_MASK_ADD, - PIPE_SOLID_COLOR, - PIPE_COUNT - }; - - enum TEX - { - TEX_DEBUG, - TEX_DUMMY, - TEX_COUNT - }; - - private: - PView _pCurrentParseView = nullptr; - Vector _vViews; - Cursor _cursor; - CGI::ShaderPwn _shader; - CGI::PipelinePwns _pipe; - CGI::TexturePwns _tex; - CGI::CSHandle _cshDefault; - CGI::CSHandle _cshDebug; - String _fadeToView; - UB_Gui _ubGui; - UB_GuiFS _ubGuiFS; - bool _xrMatrixEnabled = true; - - public: - ViewManager(); - ~ViewManager(); - - void Init(bool hasCursor = true, bool canDebug = true); - void Done(); - - virtual void InputFocus_HandleInput() override; - virtual void InputFocus_OnKeyDown(int scancode) override; - virtual void InputFocus_OnTextInput(wchar_t c) override; - virtual void InputFocus_OnMouseMove(float dx, float dy) override; - bool Update(); - void Draw(); - - PView ParseView(CSZ url); - void DeleteView(PView pView); - void DeleteAllViews(); - - PFont LoadFont(CSZ url); - PFont FindFont(CSZ name = nullptr); - void DeleteFont(CSZ name); - void DeleteAllFonts(); - - RCursor GetCursor() { return _cursor; } - - void MsgBox(CSZ txt, int data); - void MsgBoxOK(CSZ id); - - PView GetViewByName(CSZ name); - PView GetViewByZ(int index) { return _vViews[index]; } - - PView MoveToFront /**/(CSZ viewName); - PView MoveToBack /**/(CSZ viewName); - PView BeginFadeTo /**/(CSZ viewName = ":VOID:"); - void BeginFadeOut(); - PView Activate(CSZ viewName); - PView Deactivate(CSZ viewName); - bool HasAllViewsInDoneState(); - bool HasSomeViewsInFadeState(); - VERUS_P(bool SwitchView()); - - CGI::ShaderPtr GetShader() { return _shader; } - void BindPipeline(PIPE pipe, CGI::CommandBufferPtr cb); - UB_Gui& GetUbGui() { return _ubGui; } - UB_GuiFS& GetUbGuiFS() { return _ubGuiFS; } - CGI::TexturePtr GetDebugTexture(); - CGI::CSHandle GetDefaultComplexSetHandle() const { return _cshDefault; } - CGI::CSHandle GetDebugComplexSetHandle() const { return _cshDebug; } - - PView GetCurrentParseView() { return _pCurrentParseView; } - - static float ParseCoordX(CSZ coord, float def = 0); - static float ParseCoordY(CSZ coord, float def = 0); - - void SetXrMatrixEnabled(bool b) { _xrMatrixEnabled = b; } - Matrix4 GetXrMatrix() const; - - static CSZ GetSingletonFailMessage() { return "Make_GUI(); // FAIL.\r\n"; } + enum PIPE + { + PIPE_MAIN, + PIPE_MAIN_ADD, + PIPE_MASK, + PIPE_MASK_ADD, + PIPE_SOLID_COLOR, + PIPE_COUNT }; - VERUS_TYPEDEFS(ViewManager); - } + + enum TEX + { + TEX_DEBUG, + TEX_DUMMY, + TEX_COUNT + }; + + private: + PView _pCurrentParseView = nullptr; + Vector _vViews; + Cursor _cursor; + CGI::ShaderPwn _shader; + CGI::PipelinePwns _pipe; + CGI::TexturePwns _tex; + CGI::CSHandle _cshDefault; + CGI::CSHandle _cshDebug; + String _fadeToView; + UB_Gui _ubGui; + UB_GuiFS _ubGuiFS; + bool _xrMatrixEnabled = true; + + public: + ViewManager(); + ~ViewManager(); + + void Init(bool hasCursor = true, bool canDebug = true); + void Done(); + + virtual void InputFocus_HandleInput() override; + virtual void InputFocus_OnKeyDown(int scancode) override; + virtual void InputFocus_OnTextInput(wchar_t c) override; + virtual void InputFocus_OnMouseMove(float dx, float dy) override; + bool Update(); + void Draw(); + + PView ParseView(CSZ url); + void DeleteView(PView pView); + void DeleteAllViews(); + + PFont LoadFont(CSZ url); + PFont FindFont(CSZ name = nullptr); + void DeleteFont(CSZ name); + void DeleteAllFonts(); + + RCursor GetCursor() { return _cursor; } + + void MsgBox(CSZ txt, int data); + void MsgBoxOK(CSZ id); + + PView GetViewByName(CSZ name); + PView GetViewByZ(int index) { return _vViews[index]; } + + PView MoveToFront /**/(CSZ viewName); + PView MoveToBack /**/(CSZ viewName); + PView BeginFadeTo /**/(CSZ viewName = ":VOID:"); + void BeginFadeOut(); + PView Activate(CSZ viewName); + PView Deactivate(CSZ viewName); + bool HasAllViewsInDoneState(); + bool HasSomeViewsInFadeState(); + VERUS_P(bool SwitchView()); + + CGI::ShaderPtr GetShader() { return _shader; } + void BindPipeline(PIPE pipe, CGI::CommandBufferPtr cb); + UB_Gui& GetUbGui() { return _ubGui; } + UB_GuiFS& GetUbGuiFS() { return _ubGuiFS; } + CGI::TexturePtr GetDebugTexture(); + CGI::CSHandle GetDefaultComplexSetHandle() const { return _cshDefault; } + CGI::CSHandle GetDebugComplexSetHandle() const { return _cshDebug; } + + PView GetCurrentParseView() { return _pCurrentParseView; } + + static float ParseCoordX(CSZ coord, float def = 0); + static float ParseCoordY(CSZ coord, float def = 0); + + void SetXrMatrixEnabled(bool b) { _xrMatrixEnabled = b; } + Matrix4 GetXrMatrix() const; + + static CSZ GetSingletonFailMessage() { return "Make_GUI(); // FAIL.\r\n"; } + }; + VERUS_TYPEDEFS(ViewManager); } diff --git a/Verus/src/GUI/Widget.h b/Verus/src/GUI/Widget.h index 8b6ee66..a475a0d 100644 --- a/Verus/src/GUI/Widget.h +++ b/Verus/src/GUI/Widget.h @@ -3,134 +3,131 @@ #define VERUS_EVENT_HANDLER(fn) std::bind(fn, this, std::placeholders::_1) -namespace verus +namespace verus::GUI { - namespace GUI + struct InputFocus; + class Widget; + class Container; + class View; + + struct EventArgs { - struct InputFocus; - class Widget; - class Container; - class View; + Str _view; + Str _id; + Widget* _pWidget; + int _char; - struct EventArgs - { - Str _view; - Str _id; - Widget* _pWidget; - int _char; + EventArgs(CSZ view, CSZ id, Widget* p, int c = 0) : + _view(view), _id(id), _pWidget(p), _char(c) {} + }; + VERUS_TYPEDEFS(EventArgs); - EventArgs(CSZ view, CSZ id, Widget* p, int c = 0) : - _view(view), _id(id), _pWidget(p), _char(c) {} - }; - VERUS_TYPEDEFS(EventArgs); + typedef std::function TFnEvent; - typedef std::function TFnEvent; + // Base class for all controls and even frames. + // Control has position, size, id text, value text (for buttons, labels, etc.). + // It can be enabled/disabled, visible/hidden. + // Control belongs to certain view and it's position is relative to sizer or owner view if no sizer is specified. + class Widget : public AllocatorAware + { + Animator _animator; + Vector4 _color = Vector4(1, 1, 1, 1); + String _id; + WideString _text; + Vector _vFixedText; + String _sizer; + String _ownerView; + TFnEvent _fnOnMouseEnter; + TFnEvent _fnOnMouseLeave; + TFnEvent _fnOnClick; + TFnEvent _fnOnDoubleClick; + TFnEvent _fnOnKey; + TFnEvent _fnOnChar; + TFnEvent _fnOnTimeout; + int _fixedTextLength = 0; + float _x = 0; + float _y = 0; + float _w = 1; + float _h = 1; + float _wScale = 1; + float _hScale = 1; + bool _disabled = false; + bool _hidden = false; - // Base class for all controls and even frames. - // Control has position, size, id text, value text (for buttons, labels, etc.). - // It can be enabled/disabled, visible/hidden. - // Control belongs to certain view and it's position is relative to sizer or owner view if no sizer is specified. - class Widget : public AllocatorAware - { - Animator _animator; - Vector4 _color = Vector4(1, 1, 1, 1); - String _id; - WideString _text; - Vector _vFixedText; - String _sizer; - String _ownerView; - TFnEvent _fnOnMouseEnter; - TFnEvent _fnOnMouseLeave; - TFnEvent _fnOnClick; - TFnEvent _fnOnDoubleClick; - TFnEvent _fnOnKey; - TFnEvent _fnOnChar; - TFnEvent _fnOnTimeout; - int _fixedTextLength = 0; - float _x = 0; - float _y = 0; - float _w = 1; - float _h = 1; - float _wScale = 1; - float _hScale = 1; - bool _disabled = false; - bool _hidden = false; + public: + Widget(); + virtual ~Widget(); - public: - Widget(); - virtual ~Widget(); + Str GetID() const { return _C(_id); } - Str GetID() const { return _C(_id); } + WideStr GetText() const; + void SetText(CWSZ text); + void SetText(CSZ text); - WideStr GetText() const; - void SetText(CWSZ text); - void SetText(CSZ text); + void DrawDebug(); + void DrawInputStyle(); - void DrawDebug(); - void DrawInputStyle(); + virtual void Update(); + virtual void Draw() {} + virtual void Parse(pugi::xml_node node); - virtual void Update(); - virtual void Draw() {} - virtual void Parse(pugi::xml_node node); + RAnimator GetAnimator() { return _animator; } - RAnimator GetAnimator() { return _animator; } + // Cast: + virtual InputFocus* AsInputFocus() { return nullptr; } + virtual Container* AsContainer() { return nullptr; } - // Cast: - virtual InputFocus* AsInputFocus() { return nullptr; } - virtual Container* AsContainer() { return nullptr; } + RcVector4 GetColor(bool original = false) const { return original ? _color : _animator.GetColor(_color); } + void SetColor(RcVector4 color) { _color = _animator.SetColor(color); } - RcVector4 GetColor(bool original = false) const { return original ? _color : _animator.GetColor(_color); } - void SetColor(RcVector4 color) { _color = _animator.SetColor(color); } + // Relative: + float GetX() const { return _animator.GetX(_x); } + float GetY() const { return _animator.GetY(_y); } + float GetW() const { return _animator.GetW(_w); } + float GetH() const { return _animator.GetH(_h); } - // Relative: - float GetX() const { return _animator.GetX(_x); } - float GetY() const { return _animator.GetY(_y); } - float GetW() const { return _animator.GetW(_w); } - float GetH() const { return _animator.GetH(_h); } + // Relative: + void SetX(float x) { _x = _animator.SetX(x); } + void SetY(float y) { _y = _animator.SetY(y); } + void SetW(float w) { _w = _animator.SetW(w); } + void SetH(float h) { _h = _animator.SetH(h); } - // Relative: - void SetX(float x) { _x = _animator.SetX(x); } - void SetY(float y) { _y = _animator.SetY(y); } - void SetW(float w) { _w = _animator.SetW(w); } - void SetH(float h) { _h = _animator.SetH(h); } + void GetRelativePosition(float& x, float& y); + void GetAbsolutePosition(float& x, float& y); + void GetViewport(int xywh[4]); - void GetRelativePosition(float& x, float& y); - void GetAbsolutePosition(float& x, float& y); - void GetViewport(int xywh[4]); + bool IsHovered(float x, float y); - bool IsHovered(float x, float y); + bool IsDisabled() const { return _disabled; } + void Disable(bool disable = true) { _disabled = disable; } - bool IsDisabled() const { return _disabled; } - void Disable(bool disable = true) { _disabled = disable; } + bool IsVisible() const { return !_hidden; } + void Show() { _hidden = false; } + void Hide(bool hide = true) { _hidden = hide; } - bool IsVisible() const { return !_hidden; } - void Show() { _hidden = false; } - void Hide(bool hide = true) { _hidden = hide; } + float GetWScale() const { return _wScale; } + float GetHScale() const { return _hScale; } + void SetScale(float x, float y) { _wScale = x; _hScale = y; } - float GetWScale() const { return _wScale; } - float GetHScale() const { return _hScale; } - void SetScale(float x, float y) { _wScale = x; _hScale = y; } + View* GetOwnerView(); + void ResetOwnerView(); + void SetSizer(CSZ sizer) { _sizer = sizer; } - View* GetOwnerView(); - void ResetOwnerView(); - void SetSizer(CSZ sizer) { _sizer = sizer; } - - // Events: - void ConnectOnMouseEnter /**/(TFnEvent fn) { _fnOnMouseEnter = fn; } - void ConnectOnMouseLeave /**/(TFnEvent fn) { _fnOnMouseLeave = fn; } - void ConnectOnClick /**/(TFnEvent fn) { _fnOnClick = fn; } - void ConnectOnDoubleClick/**/(TFnEvent fn) { _fnOnDoubleClick = fn; } - void ConnectOnKey /**/(TFnEvent fn) { _fnOnKey = fn; } - void ConnectOnChar /**/(TFnEvent fn) { _fnOnChar = fn; } - void ConnectOnTimeout /**/(TFnEvent fn) { _fnOnTimeout = fn; } - virtual bool InvokeOnMouseEnter(); - virtual bool InvokeOnMouseLeave(); - virtual bool InvokeOnClick(float x, float y); - virtual bool InvokeOnDoubleClick(float x, float y); - virtual bool InvokeOnKey(int scancode); - virtual bool InvokeOnChar(wchar_t c); - virtual bool InvokeOnTimeout(); - }; - VERUS_TYPEDEFS(Widget); - } + // Events: + void ConnectOnMouseEnter /**/(TFnEvent fn) { _fnOnMouseEnter = fn; } + void ConnectOnMouseLeave /**/(TFnEvent fn) { _fnOnMouseLeave = fn; } + void ConnectOnClick /**/(TFnEvent fn) { _fnOnClick = fn; } + void ConnectOnDoubleClick/**/(TFnEvent fn) { _fnOnDoubleClick = fn; } + void ConnectOnKey /**/(TFnEvent fn) { _fnOnKey = fn; } + void ConnectOnChar /**/(TFnEvent fn) { _fnOnChar = fn; } + void ConnectOnTimeout /**/(TFnEvent fn) { _fnOnTimeout = fn; } + virtual bool InvokeOnMouseEnter(); + virtual bool InvokeOnMouseLeave(); + virtual bool InvokeOnClick(float x, float y); + virtual bool InvokeOnDoubleClick(float x, float y); + virtual bool InvokeOnKey(int scancode); + virtual bool InvokeOnChar(wchar_t c); + virtual bool InvokeOnTimeout(); + }; + VERUS_TYPEDEFS(Widget); } diff --git a/Verus/src/Game/BaseCharacter.h b/Verus/src/Game/BaseCharacter.h index c37eae9..08bd368 100644 --- a/Verus/src/Game/BaseCharacter.h +++ b/Verus/src/Game/BaseCharacter.h @@ -1,88 +1,85 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class BaseCharacter : public Spirit { - class BaseCharacter : public Spirit - { - Vector3 _extraForce = Vector3(0); - Physics::CharacterController _cc; - float _idleRadius = 1; - float _idleHeight = 1; - float _stepHeight = 1; - float _airborneControl = 0.1f; - float _jumpSpeed = 6; - float _minCameraRadius = 0.1f; - float _maxCameraRadius = 7.5f; - Anim::Elastic _smoothSpeedOnGround; - Anim::Elastic _fallSpeed; - Linear _cameraRadius; - Cooldown _jumpCooldown = 0.25f; // To filter BaseCharacter_OnJump(). - Cooldown _wallHitCooldown = 2; - Cooldown _unstuckCooldown = 0.25f; - bool _airborne = false; - bool _ragdoll = false; + Vector3 _extraForce = Vector3(0); + Physics::CharacterController _cc; + float _idleRadius = 1; + float _idleHeight = 1; + float _stepHeight = 1; + float _airborneControl = 0.1f; + float _jumpSpeed = 6; + float _minCameraRadius = 0.1f; + float _maxCameraRadius = 7.5f; + Anim::Elastic _smoothSpeedOnGround; + Anim::Elastic _fallSpeed; + Linear _cameraRadius; + Cooldown _jumpCooldown = 0.25f; // To filter BaseCharacter_OnJump(). + Cooldown _wallHitCooldown = 2; + Cooldown _unstuckCooldown = 0.25f; + bool _airborne = false; + bool _ragdoll = false; - public: - BaseCharacter(); - virtual ~BaseCharacter(); + public: + BaseCharacter(); + virtual ~BaseCharacter(); - virtual void HandleActions() override; - virtual void Update() override; + virtual void HandleActions() override; + virtual void Update() override; - // Creates the underlying controller. - // EndRagdoll() calls this method automatically. - void InitController(); - void DoneController(); - Physics::RCharacterController GetController() { return _cc; } + // Creates the underlying controller. + // EndRagdoll() calls this method automatically. + void InitController(); + void DoneController(); + Physics::RCharacterController GetController() { return _cc; } - virtual void MoveTo(RcPoint3 pos) override; - virtual bool FitRemotePosition() override; + virtual void MoveTo(RcPoint3 pos) override; + virtual bool FitRemotePosition() override; - // Dimensions: - float GetIdleRadius() const { return _idleRadius; } - void SetIdleRadius(float r) { _idleRadius = r; } - float GetIdleHeight() const { return _idleHeight; } - void SetIdleHeight(float h) { _idleHeight = h; } + // Dimensions: + float GetIdleRadius() const { return _idleRadius; } + void SetIdleRadius(float r) { _idleRadius = r; } + float GetIdleHeight() const { return _idleHeight; } + void SetIdleHeight(float h) { _idleHeight = h; } - void SetStepHeight(float sh) { _stepHeight = sh; } + void SetStepHeight(float sh) { _stepHeight = sh; } - // Jumps: - bool IsOnGround() const; - bool TryJump(bool whileAirborne = false); - void Jump(); - void SetJumpSpeed(float v = 6); - float GetFallSpeed() const { return _fallSpeed; } - virtual void BaseCharacter_OnFallImpact(float speed) {} - virtual void BaseCharacter_OnWallImpact(float speed) {} - virtual void BaseCharacter_OnJump() {} + // Jumps: + bool IsOnGround() const; + bool TryJump(bool whileAirborne = false); + void Jump(); + void SetJumpSpeed(float v = 6); + float GetFallSpeed() const { return _fallSpeed; } + virtual void BaseCharacter_OnFallImpact(float speed) {} + virtual void BaseCharacter_OnWallImpact(float speed) {} + virtual void BaseCharacter_OnJump() {} - void AddExtraForce(RcVector3 v) { _extraForce += v; } + void AddExtraForce(RcVector3 v) { _extraForce += v; } - // For AI: - // Check if the speed is less than expected. - bool IsStuck(); - // Is typically called when AI gets a new task. - void StartUnstuckCooldown() { _unstuckCooldown.Start(); } + // For AI: + // Check if the speed is less than expected. + bool IsStuck(); + // Is typically called when AI gets a new task. + void StartUnstuckCooldown() { _unstuckCooldown.Start(); } - // Ragdoll: - bool IsRagdoll() const { return _ragdoll; } - void ToggleRagdoll(); - void BeginRagdoll(); - void EndRagdoll(); + // Ragdoll: + bool IsRagdoll() const { return _ragdoll; } + void ToggleRagdoll(); + void BeginRagdoll(); + void EndRagdoll(); - virtual void BaseCharacter_OnInitRagdoll(RcTransform3 matW) {} - virtual void BaseCharacter_OnDoneRagdoll() {} + virtual void BaseCharacter_OnInitRagdoll(RcTransform3 matW) {} + virtual void BaseCharacter_OnDoneRagdoll() {} - virtual void ComputeThirdPersonCameraArgs(RcVector3 offset, RPoint3 eye, RPoint3 at); - float ComputeThirdPersonCamera(World::RCamera camera, Anim::RcOrbit orbit, RcVector3 offset = Vector3(0)); - void ComputeThirdPersonAim(RPoint3 aimPos, RVector3 aimDir, RcVector3 offset = Vector3(0)); - float GetThirdPersonCameraBaseHeight() const; - void SetMaxCameraRadius(float r); - float GetCameraRadius() const { return _cameraRadius.GetValue(); } - }; - VERUS_TYPEDEFS(BaseCharacter); - } + virtual void ComputeThirdPersonCameraArgs(RcVector3 offset, RPoint3 eye, RPoint3 at); + float ComputeThirdPersonCamera(World::RCamera camera, Anim::RcOrbit orbit, RcVector3 offset = Vector3(0)); + void ComputeThirdPersonAim(RPoint3 aimPos, RVector3 aimDir, RcVector3 offset = Vector3(0)); + float GetThirdPersonCameraBaseHeight() const; + void SetMaxCameraRadius(float r); + float GetCameraRadius() const { return _cameraRadius.GetValue(); } + }; + VERUS_TYPEDEFS(BaseCharacter); } diff --git a/Verus/src/Game/BaseGame.h b/Verus/src/Game/BaseGame.h index 08db769..23ebeb4 100644 --- a/Verus/src/Game/BaseGame.h +++ b/Verus/src/Game/BaseGame.h @@ -1,74 +1,71 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class BaseGame : public Input::InputFocus { - class BaseGame : public Input::InputFocus - { - struct Pimpl; - Pimpl* _p = nullptr; - AlignedAllocator _alloc; - EngineInit _engineInit; - App::Window _window; - bool _restartApp = false; + struct Pimpl; + Pimpl* _p = nullptr; + AlignedAllocator _alloc; + EngineInit _engineInit; + App::Window _window; + bool _restartApp = false; - public: - BaseGame(); - ~BaseGame(); + public: + BaseGame(); + ~BaseGame(); - void Initialize(VERUS_MAIN_DEFAULT_ARGS, - App::RcInfo appInfo = App::Info(), - App::Window::RcDesc windowDesc = App::Window::Desc()); - void Loop(bool relativeMouseMode = true); - void Exit(); + void Initialize(VERUS_MAIN_DEFAULT_ARGS, + App::RcInfo appInfo = App::Info(), + App::Window::RcDesc windowDesc = App::Window::Desc()); + void Loop(bool relativeMouseMode = true); + void Exit(); - virtual void BaseGame_UpdateSettings(App::Window::RDesc windowDesc) {} - virtual void BaseGame_LoadContent() = 0; - virtual void BaseGame_UnloadContent() = 0; - virtual void BaseGame_EnterRequestedState() {} - virtual void BaseGame_Update() = 0; - virtual void BaseGame_Draw() = 0; - virtual void BaseGame_DrawView(CGI::RcViewDesc viewDesc) = 0; - virtual void BaseGame_OnWindowMoved() {} - virtual void BaseGame_OnWindowSizeChanged() {} - virtual void BaseGame_OnActivated() {} - virtual void BaseGame_OnDeactivated() {} - virtual bool BaseGame_CanQuitEventLoop() { return true; } + virtual void BaseGame_UpdateSettings(App::Window::RDesc windowDesc) {} + virtual void BaseGame_LoadContent() = 0; + virtual void BaseGame_UnloadContent() = 0; + virtual void BaseGame_EnterRequestedState() {} + virtual void BaseGame_Update() = 0; + virtual void BaseGame_Draw() = 0; + virtual void BaseGame_DrawView(CGI::RcViewDesc viewDesc) = 0; + virtual void BaseGame_OnWindowMoved() {} + virtual void BaseGame_OnWindowSizeChanged() {} + virtual void BaseGame_OnActivated() {} + virtual void BaseGame_OnDeactivated() {} + virtual bool BaseGame_CanQuitEventLoop() { return true; } - // Raw SDL events, for editor: - virtual void BaseGame_SDL_OnMouseMotion(int x, int y) {} - virtual void BaseGame_SDL_OnMouseButtonDown(int button) {} - virtual void BaseGame_SDL_OnMouseDoubleClick(int button) {} - virtual void BaseGame_SDL_OnMouseButtonUp(int button) {} - virtual void BaseGame_SDL_OnMouseWheel(int delta) {} - virtual bool BaseGame_SDL_OnKeyboardShortcut(int sym, int mod) { return false; } + // Raw SDL events, for editor: + virtual void BaseGame_SDL_OnMouseMotion(int x, int y) {} + virtual void BaseGame_SDL_OnMouseButtonDown(int button) {} + virtual void BaseGame_SDL_OnMouseDoubleClick(int button) {} + virtual void BaseGame_SDL_OnMouseButtonUp(int button) {} + virtual void BaseGame_SDL_OnMouseWheel(int delta) {} + virtual bool BaseGame_SDL_OnKeyboardShortcut(int sym, int mod) { return false; } - virtual void InputFocus_OnMouseMove(float dx, float dy) override; + virtual void InputFocus_OnMouseMove(float dx, float dy) override; - REngineInit GetEngineInit() { return _engineInit; } + REngineInit GetEngineInit() { return _engineInit; } - App::RcWindow GetWindow() const { return _window; } - bool IsFullscreen() const; - void ToggleFullscreen(); + App::RcWindow GetWindow() const { return _window; } + bool IsFullscreen() const; + void ToggleFullscreen(); - // Camera: - World::RCamera GetDefaultCamera(); - RSpirit GetCameraSpirit(); + // Camera: + World::RCamera GetDefaultCamera(); + RSpirit GetCameraSpirit(); - // Configuration: - void EnableDefaultCameraMovement(bool b = true); - void EnableEscapeKeyExitGame(bool b = true); - void EnableRawInputEvents(bool b = true); - void ShowFPS(bool b); + // Configuration: + void EnableDefaultCameraMovement(bool b = true); + void EnableEscapeKeyExitGame(bool b = true); + void EnableRawInputEvents(bool b = true); + void ShowFPS(bool b); - void BulletDebugDraw(); + void BulletDebugDraw(); - bool IsRestartAppRequested() const { return _restartApp; } - static void RestartApp(); - void RequestAppRestart(); - }; - VERUS_TYPEDEFS(BaseGame); - } + bool IsRestartAppRequested() const { return _restartApp; } + static void RestartApp(); + void RequestAppRestart(); + }; + VERUS_TYPEDEFS(BaseGame); } diff --git a/Verus/src/Game/ChainAward.h b/Verus/src/Game/ChainAward.h index c6fbead..e90626d 100644 --- a/Verus/src/Game/ChainAward.h +++ b/Verus/src/Game/ChainAward.h @@ -1,24 +1,21 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class ChainAward { - class ChainAward - { - float _lastTime = 0; - float _maxInterval = 0; - int _lastLevel = 0; - int _maxLevel = 0; + float _lastTime = 0; + float _maxInterval = 0; + int _lastLevel = 0; + int _maxLevel = 0; - public: - ChainAward(float maxInterval = 1, int maxLevel = 10); - ~ChainAward(); + public: + ChainAward(float maxInterval = 1, int maxLevel = 10); + ~ChainAward(); - int Score(); - void Reset(); - }; - VERUS_TYPEDEFS(ChainAward); - } + int Score(); + void Reset(); + }; + VERUS_TYPEDEFS(ChainAward); } diff --git a/Verus/src/Game/Mechanics/ActiveMechanics.h b/Verus/src/Game/Mechanics/ActiveMechanics.h index e99d5b6..2482b0a 100644 --- a/Verus/src/Game/Mechanics/ActiveMechanics.h +++ b/Verus/src/Game/Mechanics/ActiveMechanics.h @@ -1,45 +1,42 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class ActiveMechanics : public Object, public Input::InputFocus { - class ActiveMechanics : public Object, public Input::InputFocus - { - Vector _vStack; + Vector _vStack; - public: - ActiveMechanics(); - ~ActiveMechanics(); + public: + ActiveMechanics(); + ~ActiveMechanics(); - void Init(); - void Done(); + void Init(); + void Done(); - virtual bool InputFocus_Veto() override; - virtual void InputFocus_HandleInput() override; - bool Update(); - bool Draw(); - bool DrawOverlay(); + virtual bool InputFocus_Veto() override; + virtual void InputFocus_HandleInput() override; + bool Update(); + bool Draw(); + bool DrawOverlay(); - void ApplyReport(const void* pReport); - bool GetBotDomainCenter(int id, RPoint3 center); - bool GetSpawnPosition(int id, RPoint3 pos); - bool IsDefaultInputEnabled(); - bool OnDie(int id); - bool OnHeadCameraDefined(); - bool OnMouseMove(float x, float y); - bool OnTakeDamage(int id, float amount); - void OnViewChanged(CGI::RcViewDesc viewDesc); - bool UpdateMultiplayer(); - World::PMainCamera GetScreenCamera(); + void ApplyReport(const void* pReport); + bool GetBotDomainCenter(int id, RPoint3 center); + bool GetSpawnPosition(int id, RPoint3 pos); + bool IsDefaultInputEnabled(); + bool OnDie(int id); + bool OnHeadCameraDefined(); + bool OnMouseMove(float x, float y); + bool OnTakeDamage(int id, float amount); + void OnViewChanged(CGI::RcViewDesc viewDesc); + bool UpdateMultiplayer(); + World::PMainCamera GetScreenCamera(); - void Reset(); - bool Push(RMechanics mech); - bool Pop(RMechanics mech); - bool IsActive(RcMechanics mech) const; - virtual void ActiveMechanics_OnChanged() {} - }; - VERUS_TYPEDEFS(ActiveMechanics); - } + void Reset(); + bool Push(RMechanics mech); + bool Pop(RMechanics mech); + bool IsActive(RcMechanics mech) const; + virtual void ActiveMechanics_OnChanged() {} + }; + VERUS_TYPEDEFS(ActiveMechanics); } diff --git a/Verus/src/Game/Mechanics/Cutscene.h b/Verus/src/Game/Mechanics/Cutscene.h index 5d6823c..773be98 100644 --- a/Verus/src/Game/Mechanics/Cutscene.h +++ b/Verus/src/Game/Mechanics/Cutscene.h @@ -1,177 +1,174 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class Cutscene : public Object, public Mechanics { - class Cutscene : public Object, public Mechanics + public: + class Command + { + protected: + Cutscene* _pCutscene = nullptr; + String _url; + float _delay = 0; + float _prevDelay = FLT_MAX; + float _endDelay = FLT_MAX; + float _duration = 0; + bool _active = false; + + public: + virtual ~Command() {} + virtual void Parse(pugi::xml_node node); + virtual bool Update(); + virtual bool DrawOverlay() { return false; } + virtual void OnBegin() { _active = true; } + virtual void OnEnd() { _active = false; } + virtual bool IsBarrier() const { return false; } + virtual bool SkipHere() const { return false; } + + void SetCutscene(Cutscene* p) { _pCutscene = p; } + bool IsActive() const { return _active; } + bool IsDelayed() const { return _pCutscene->_timeSinceBarrier < _delay; } + float GetDelay() const { return _delay; } + void AdjustDelayBy(float amount) { _delay += amount; } + void UpdatePrevDelay(float newActiveDuration); + void UpdateEndDelay(float newActiveDuration); + float GetDuration() const { return _duration; } + void LimitActiveDuration(float limit); + float GetTime() const { return _pCutscene->_timeSinceBarrier - _delay; } + }; + VERUS_TYPEDEFS(Command); + + class BarrierCommand : public Command { public: - class Command - { - protected: - Cutscene* _pCutscene = nullptr; - String _url; - float _delay = 0; - float _prevDelay = FLT_MAX; - float _endDelay = FLT_MAX; - float _duration = 0; - bool _active = false; + static PCommand Make(); + virtual bool IsBarrier() const override { return true; } + }; + VERUS_TYPEDEFS(BarrierCommand); - public: - virtual ~Command() {} - virtual void Parse(pugi::xml_node node); - virtual bool Update(); - virtual bool DrawOverlay() { return false; } - virtual void OnBegin() { _active = true; } - virtual void OnEnd() { _active = false; } - virtual bool IsBarrier() const { return false; } - virtual bool SkipHere() const { return false; } - - void SetCutscene(Cutscene* p) { _pCutscene = p; } - bool IsActive() const { return _active; } - bool IsDelayed() const { return _pCutscene->_timeSinceBarrier < _delay; } - float GetDelay() const { return _delay; } - void AdjustDelayBy(float amount) { _delay += amount; } - void UpdatePrevDelay(float newActiveDuration); - void UpdateEndDelay(float newActiveDuration); - float GetDuration() const { return _duration; } - void LimitActiveDuration(float limit); - float GetTime() const { return _pCutscene->_timeSinceBarrier - _delay; } - }; - VERUS_TYPEDEFS(Command); - - class BarrierCommand : public Command - { - public: - static PCommand Make(); - virtual bool IsBarrier() const override { return true; } - }; - VERUS_TYPEDEFS(BarrierCommand); - - class CameraCommand : public Command, public IO::AsyncDelegate, public Anim::MotionDelegate - { - Anim::Motion _motion; - String _cameraName; - - public: - ~CameraCommand(); - static PCommand Make(); - virtual void Parse(pugi::xml_node node) override; - virtual bool Update() override; - virtual void OnBegin() override; - virtual void OnEnd() override; - virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; - virtual void Motion_OnTrigger(CSZ name, int state) override; - }; - VERUS_TYPEDEFS(CameraCommand); - - class ConfigCommand : public Command - { - int _tag = 1; - bool _callOnEnd = false; - bool _skipHere = false; - - public: - static PCommand Make(); - virtual void Parse(pugi::xml_node node) override; - virtual void OnBegin() override; - virtual bool SkipHere() const override { return _skipHere; } - }; - VERUS_TYPEDEFS(ConfigCommand); - - class FadeCommand : public Command - { - Vector4 _from = Vector4(0); - Vector4 _to = Vector4(0); - Easing _easing = Easing::none; - bool _skipHere = false; - - public: - static PCommand Make(); - virtual void Parse(pugi::xml_node node) override; - virtual bool DrawOverlay() override; - virtual bool SkipHere() const override { return _skipHere; } - }; - VERUS_TYPEDEFS(FadeCommand); - - class MotionCommand : public Command, public Anim::MotionDelegate - { - Anim::Motion _motion; - - public: - static PCommand Make(); - virtual bool Update() override; - virtual void Motion_OnTrigger(CSZ name, int state) override; - }; - VERUS_TYPEDEFS(MotionCommand); - - class SoundCommand : public Command - { - Audio::SoundPwn _sound; - Audio::SourcePtr _source; - float _gain = 1; - float _pitch = 1; - - public: - static PCommand Make(); - virtual void Parse(pugi::xml_node node) override; - virtual bool Update(); - virtual void OnEnd() override; - }; - VERUS_TYPEDEFS(SoundCommand); - - private: - typedef PCommand(*PFNCREATOR)(); - typedef Map TMapCreators; - - String _url; - TMapCreators _mapCreators; - Vector _vCommands; - std::function _fnOnEnd; - PCameraCommand _pCurrentCameraCommand = nullptr; - World::MainCamera _screenCamera; - int _beginIndex = 0; - int _endIndex = 0; - float _timeSinceBarrier = 0; - bool _interactive = false; + class CameraCommand : public Command, public IO::AsyncDelegate, public Anim::MotionDelegate + { + Anim::Motion _motion; + String _cameraName; public: - Cutscene(); - ~Cutscene(); - - void Init(); - void Done(); - - void Next(CSZ url, bool preload = false); - void Load(CSZ url); - + ~CameraCommand(); + static PCommand Make(); + virtual void Parse(pugi::xml_node node) override; + virtual bool Update() override; virtual void OnBegin() override; virtual void OnEnd() override; - virtual bool CanAutoPop() override; - - // Commands: - void RegisterCommand(CSZ type, PFNCREATOR pCreator); - PCommand CreateCommand(CSZ type); - void DeleteCommands(); - - // Run commands: - void Skip(); - bool SkipBarrier(); - bool RunParallelCommands(); - - virtual Continue Update() override; - virtual Continue DrawOverlay() override; - virtual bool IsDefaultInputEnabled() override; - virtual Continue OnMouseMove(float x, float y) override; - virtual void OnViewChanged(CGI::RcViewDesc viewDesc) override; - virtual World::PMainCamera GetScreenCamera() override; - - void SetOnEndCallback(std::function fn) { _fnOnEnd = fn; } - - void OnNewActiveDuration(float newActiveDuration); + virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; + virtual void Motion_OnTrigger(CSZ name, int state) override; }; - VERUS_TYPEDEFS(Cutscene); - } + VERUS_TYPEDEFS(CameraCommand); + + class ConfigCommand : public Command + { + int _tag = 1; + bool _callOnEnd = false; + bool _skipHere = false; + + public: + static PCommand Make(); + virtual void Parse(pugi::xml_node node) override; + virtual void OnBegin() override; + virtual bool SkipHere() const override { return _skipHere; } + }; + VERUS_TYPEDEFS(ConfigCommand); + + class FadeCommand : public Command + { + Vector4 _from = Vector4(0); + Vector4 _to = Vector4(0); + Easing _easing = Easing::none; + bool _skipHere = false; + + public: + static PCommand Make(); + virtual void Parse(pugi::xml_node node) override; + virtual bool DrawOverlay() override; + virtual bool SkipHere() const override { return _skipHere; } + }; + VERUS_TYPEDEFS(FadeCommand); + + class MotionCommand : public Command, public Anim::MotionDelegate + { + Anim::Motion _motion; + + public: + static PCommand Make(); + virtual bool Update() override; + virtual void Motion_OnTrigger(CSZ name, int state) override; + }; + VERUS_TYPEDEFS(MotionCommand); + + class SoundCommand : public Command + { + Audio::SoundPwn _sound; + Audio::SourcePtr _source; + float _gain = 1; + float _pitch = 1; + + public: + static PCommand Make(); + virtual void Parse(pugi::xml_node node) override; + virtual bool Update(); + virtual void OnEnd() override; + }; + VERUS_TYPEDEFS(SoundCommand); + + private: + typedef PCommand(*PFNCREATOR)(); + typedef Map TMapCreators; + + String _url; + TMapCreators _mapCreators; + Vector _vCommands; + std::function _fnOnEnd; + PCameraCommand _pCurrentCameraCommand = nullptr; + World::MainCamera _screenCamera; + int _beginIndex = 0; + int _endIndex = 0; + float _timeSinceBarrier = 0; + bool _interactive = false; + + public: + Cutscene(); + ~Cutscene(); + + void Init(); + void Done(); + + void Next(CSZ url, bool preload = false); + void Load(CSZ url); + + virtual void OnBegin() override; + virtual void OnEnd() override; + virtual bool CanAutoPop() override; + + // Commands: + void RegisterCommand(CSZ type, PFNCREATOR pCreator); + PCommand CreateCommand(CSZ type); + void DeleteCommands(); + + // Run commands: + void Skip(); + bool SkipBarrier(); + bool RunParallelCommands(); + + virtual Continue Update() override; + virtual Continue DrawOverlay() override; + virtual bool IsDefaultInputEnabled() override; + virtual Continue OnMouseMove(float x, float y) override; + virtual void OnViewChanged(CGI::RcViewDesc viewDesc) override; + virtual World::PMainCamera GetScreenCamera() override; + + void SetOnEndCallback(std::function fn) { _fnOnEnd = fn; } + + void OnNewActiveDuration(float newActiveDuration); + }; + VERUS_TYPEDEFS(Cutscene); } diff --git a/Verus/src/Game/Mechanics/Driving.h b/Verus/src/Game/Mechanics/Driving.h index 6086aa7..1420e2d 100644 --- a/Verus/src/Game/Mechanics/Driving.h +++ b/Verus/src/Game/Mechanics/Driving.h @@ -1,16 +1,13 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class Driving { - class Driving - { - public: - Driving(); - ~Driving(); - }; - VERUS_TYPEDEFS(Driving); - } + public: + Driving(); + ~Driving(); + }; + VERUS_TYPEDEFS(Driving); } diff --git a/Verus/src/Game/Mechanics/Mechanics.h b/Verus/src/Game/Mechanics/Mechanics.h index f00dfcd..c0a66f8 100644 --- a/Verus/src/Game/Mechanics/Mechanics.h +++ b/Verus/src/Game/Mechanics/Mechanics.h @@ -1,38 +1,35 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class Mechanics { - class Mechanics - { - public: - Mechanics(); - virtual ~Mechanics(); + public: + Mechanics(); + virtual ~Mechanics(); - virtual void OnBegin() {} - virtual void OnEnd() {} - virtual bool CanAutoPop() { return false; } + virtual void OnBegin() {} + virtual void OnEnd() {} + virtual bool CanAutoPop() { return false; } - virtual bool VetoInputFocus() { return false; } - virtual void HandleInput() {} - virtual Continue Update() { return Continue::yes; } - virtual Continue Draw() { return Continue::yes; } - virtual Continue DrawOverlay() { return Continue::yes; } + virtual bool VetoInputFocus() { return false; } + virtual void HandleInput() {} + virtual Continue Update() { return Continue::yes; } + virtual Continue Draw() { return Continue::yes; } + virtual Continue DrawOverlay() { return Continue::yes; } - virtual void ApplyReport(const void* pReport) {} - virtual Continue GetBotDomainCenter(int id, RPoint3 center) { return Continue::yes; } - virtual Continue GetSpawnPosition(int id, RPoint3 pos) { return Continue::yes; }; - virtual bool IsDefaultInputEnabled() { return true; } - virtual Continue OnDie(int id) { return Continue::yes; } - virtual Continue OnHeadCameraDefined() { return Continue::yes; } - virtual Continue OnMouseMove(float x, float y) { return Continue::yes; } - virtual Continue OnTakeDamage(int id, float amount) { return Continue::yes; } - virtual void OnViewChanged(CGI::RcViewDesc viewDesc) {} - virtual Continue UpdateMultiplayer() { return Continue::yes; } - virtual World::PMainCamera GetScreenCamera() { return nullptr; } - }; - VERUS_TYPEDEFS(Mechanics); - } + virtual void ApplyReport(const void* pReport) {} + virtual Continue GetBotDomainCenter(int id, RPoint3 center) { return Continue::yes; } + virtual Continue GetSpawnPosition(int id, RPoint3 pos) { return Continue::yes; }; + virtual bool IsDefaultInputEnabled() { return true; } + virtual Continue OnDie(int id) { return Continue::yes; } + virtual Continue OnHeadCameraDefined() { return Continue::yes; } + virtual Continue OnMouseMove(float x, float y) { return Continue::yes; } + virtual Continue OnTakeDamage(int id, float amount) { return Continue::yes; } + virtual void OnViewChanged(CGI::RcViewDesc viewDesc) {} + virtual Continue UpdateMultiplayer() { return Continue::yes; } + virtual World::PMainCamera GetScreenCamera() { return nullptr; } + }; + VERUS_TYPEDEFS(Mechanics); } diff --git a/Verus/src/Game/QuestSystem.h b/Verus/src/Game/QuestSystem.h index 940d512..48e4bb0 100644 --- a/Verus/src/Game/QuestSystem.h +++ b/Verus/src/Game/QuestSystem.h @@ -1,58 +1,41 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class QuestSystem : public Singleton, public Object { - class QuestSystem : public Singleton, public Object + public: + class Quest { public: - class Quest + class Req { public: - class Req + enum class Type : int { - public: - enum class Type : int - { - quest, - xp, - count - }; - - private: - String _id; - Type _type = Type::quest; + quest, + xp, + count }; - VERUS_TYPEDEFS(Req); - class Task + private: + String _id; + Type _type = Type::quest; + }; + VERUS_TYPEDEFS(Req); + + class Task + { + public: + enum class Type : int { - public: - enum class Type : int - { - destroy, - gather, - protect, - trigger, - count - }; - - class Reward - { - String _id; - int _count = 0; - }; - VERUS_TYPEDEFS(Reward); - - private: - Vector _vRewards; - String _desc; - Type _type = Type::destroy; - int _count = 0; + destroy, + gather, + protect, + trigger, + count }; - VERUS_TYPEDEFS(Task); class Reward { @@ -62,24 +45,38 @@ namespace verus VERUS_TYPEDEFS(Reward); private: - Vector _vReqs; - Vector _vTasks; Vector _vRewards; - String _id; String _desc; + Type _type = Type::destroy; + int _count = 0; }; - VERUS_TYPEDEFS(Quest); + VERUS_TYPEDEFS(Task); + + class Reward + { + String _id; + int _count = 0; + }; + VERUS_TYPEDEFS(Reward); private: - Vector _vQuests; - - public: - QuestSystem(); - ~QuestSystem(); - - void Init(); - void Done(); + Vector _vReqs; + Vector _vTasks; + Vector _vRewards; + String _id; + String _desc; }; - VERUS_TYPEDEFS(QuestSystem); - } + VERUS_TYPEDEFS(Quest); + + private: + Vector _vQuests; + + public: + QuestSystem(); + ~QuestSystem(); + + void Init(); + void Done(); + }; + VERUS_TYPEDEFS(QuestSystem); } diff --git a/Verus/src/Game/Spirit.h b/Verus/src/Game/Spirit.h index 39a53c1..1b55f25 100644 --- a/Verus/src/Game/Spirit.h +++ b/Verus/src/Game/Spirit.h @@ -1,108 +1,105 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class Spirit : public AllocatorAware { - class Spirit : public AllocatorAware + protected: + static const float s_defaultMaxPitch; + + struct DerivedVars { - protected: - static const float s_defaultMaxPitch; - - struct DerivedVars - { - Matrix3 _matPitch; - Matrix3 _matYaw; - Matrix3 _matLeanYaw; - Matrix3 _matRot; - Vector3 _frontDir = Vector3(0); - Vector3 _frontDir2D = Vector3(0); - Vector3 _sideDir = Vector3(0); - Vector3 _sideDir2D = Vector3(0); - Point3 _jerkyPosition = Point3(0); - }; - - DerivedVars _dv; - Point3 _position = Point3(0); - Point3 _prevPosition = Point3(0); - Point3 _remotePosition = Point3(0); - Vector3 _avgVelocity = Vector3(0); - Vector3 _endVelocity = Vector3(0); - Vector3 _move = Vector3(0); - Point3 _smoothPrevPosition = Point3(0); - Anim::Elastic _smoothPosition; - Anim::Elastic _pitch; - Anim::Elastic _yaw; - Anim::Elastic _smoothSpeed; - float _speed = 0; - float _maxSpeed = 10; - float _moveLen = 0; - float _maxPitch = s_defaultMaxPitch; - float _accel = 0; - float _decel = 0; - float _turnLeanStrength = 0; - float _jerkyPositionDelta = 10; - - public: - Spirit(); - virtual ~Spirit(); - - void ComputeDerivedVars(float smoothSpeed = 0); - - // Move: - void MoveFront(float x); - void MoveSide(float x); - void MoveFront2D(float x); - void MoveSide2D(float x); - void TurnPitch(float rad); - void TurnYaw(float rad); - void SetPitch(float rad); - void SetYaw(float rad); - - void SetMaxPitch(float value = s_defaultMaxPitch) { _maxPitch = value; } - float GetPitch() const { return _pitch; } - float GetYaw() const { return _yaw; } - - virtual void HandleActions(); - virtual void Update(); - - void SetAcceleration(float accel = 5, float decel = 5); - float GetSpeed() const { return _speed; } - float GetSmoothSpeed() const { return _smoothSpeed; } - float GetMaxSpeed() const { return _maxSpeed; } - void SetMaxSpeed(float v = 10) { _maxSpeed = v; } - - Point3 GetPosition(bool smooth = true); - RcPoint3 GetJerkyPosition() const { return _dv._jerkyPosition; } - virtual void MoveTo(RcPoint3 pos); - void SetRemotePosition(RcPoint3 pos); - virtual bool FitRemotePosition(); - - RcVector3 GetVelocity() const { return _avgVelocity; } - void SetVelocity(RcVector3 v) { _avgVelocity = _endVelocity = v; } - - RcVector3 GetFrontDirection() const { return _dv._frontDir; } - RcVector3 GetFrontDirection2D() const { return _dv._frontDir2D; } - RcVector3 GetSideDirection() const { return _dv._sideDir; } - RcVector3 GetSideDirection2D() const { return _dv._sideDir2D; } - - // Rotates smoothly across multiple frames. - void Rotate(RcVector3 front, float speed); - void LookAt(RcPoint3 point, bool forceTarget = false); - - // Matrices: - RcMatrix3 GetPitchMatrix() const; - RcMatrix3 GetYawMatrix() const; - RcMatrix3 GetRotationMatrix() const; - Transform3 GetMatrix() const; - Transform3 GetUprightMatrix() const; - Transform3 GetUprightWithLeanMatrix() const; - - float GetMotionBlur() const; - - void SetTurnLeanStrength(float x) { _turnLeanStrength = x; } + Matrix3 _matPitch; + Matrix3 _matYaw; + Matrix3 _matLeanYaw; + Matrix3 _matRot; + Vector3 _frontDir = Vector3(0); + Vector3 _frontDir2D = Vector3(0); + Vector3 _sideDir = Vector3(0); + Vector3 _sideDir2D = Vector3(0); + Point3 _jerkyPosition = Point3(0); }; - VERUS_TYPEDEFS(Spirit); - } + + DerivedVars _dv; + Point3 _position = Point3(0); + Point3 _prevPosition = Point3(0); + Point3 _remotePosition = Point3(0); + Vector3 _avgVelocity = Vector3(0); + Vector3 _endVelocity = Vector3(0); + Vector3 _move = Vector3(0); + Point3 _smoothPrevPosition = Point3(0); + Anim::Elastic _smoothPosition; + Anim::Elastic _pitch; + Anim::Elastic _yaw; + Anim::Elastic _smoothSpeed; + float _speed = 0; + float _maxSpeed = 10; + float _moveLen = 0; + float _maxPitch = s_defaultMaxPitch; + float _accel = 0; + float _decel = 0; + float _turnLeanStrength = 0; + float _jerkyPositionDelta = 10; + + public: + Spirit(); + virtual ~Spirit(); + + void ComputeDerivedVars(float smoothSpeed = 0); + + // Move: + void MoveFront(float x); + void MoveSide(float x); + void MoveFront2D(float x); + void MoveSide2D(float x); + void TurnPitch(float rad); + void TurnYaw(float rad); + void SetPitch(float rad); + void SetYaw(float rad); + + void SetMaxPitch(float value = s_defaultMaxPitch) { _maxPitch = value; } + float GetPitch() const { return _pitch; } + float GetYaw() const { return _yaw; } + + virtual void HandleActions(); + virtual void Update(); + + void SetAcceleration(float accel = 5, float decel = 5); + float GetSpeed() const { return _speed; } + float GetSmoothSpeed() const { return _smoothSpeed; } + float GetMaxSpeed() const { return _maxSpeed; } + void SetMaxSpeed(float v = 10) { _maxSpeed = v; } + + Point3 GetPosition(bool smooth = true); + RcPoint3 GetJerkyPosition() const { return _dv._jerkyPosition; } + virtual void MoveTo(RcPoint3 pos); + void SetRemotePosition(RcPoint3 pos); + virtual bool FitRemotePosition(); + + RcVector3 GetVelocity() const { return _avgVelocity; } + void SetVelocity(RcVector3 v) { _avgVelocity = _endVelocity = v; } + + RcVector3 GetFrontDirection() const { return _dv._frontDir; } + RcVector3 GetFrontDirection2D() const { return _dv._frontDir2D; } + RcVector3 GetSideDirection() const { return _dv._sideDir; } + RcVector3 GetSideDirection2D() const { return _dv._sideDir2D; } + + // Rotates smoothly across multiple frames. + void Rotate(RcVector3 front, float speed); + void LookAt(RcPoint3 point, bool forceTarget = false); + + // Matrices: + RcMatrix3 GetPitchMatrix() const; + RcMatrix3 GetYawMatrix() const; + RcMatrix3 GetRotationMatrix() const; + Transform3 GetMatrix() const; + Transform3 GetUprightMatrix() const; + Transform3 GetUprightWithLeanMatrix() const; + + float GetMotionBlur() const; + + void SetTurnLeanStrength(float x) { _turnLeanStrength = x; } + }; + VERUS_TYPEDEFS(Spirit); } diff --git a/Verus/src/Game/State.h b/Verus/src/Game/State.h index 7ccfbd8..01b6c68 100644 --- a/Verus/src/Game/State.h +++ b/Verus/src/Game/State.h @@ -1,29 +1,26 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class StateMachine; + + class State : public Input::InputFocus { - class StateMachine; + StateMachine* _pStateMachine = nullptr; - class State : public Input::InputFocus - { - StateMachine* _pStateMachine = nullptr; + public: + StateMachine* GetStateMachine() const { return _pStateMachine; } + StateMachine* SetStateMachine(StateMachine* p) { return Utils::Swap(_pStateMachine, p); } - public: - StateMachine* GetStateMachine() const { return _pStateMachine; } - StateMachine* SetStateMachine(StateMachine* p) { return Utils::Swap(_pStateMachine, p); } - - virtual bool IsValidNextState(State* p); - virtual void OnEnter(State* pPrev); - virtual void InputFocus_HandleInput() override; - virtual void HandleActions(); - virtual void Update(); - virtual void Draw(); - virtual void DrawView(CGI::RcViewDesc viewDesc); - virtual void OnExit(State* pNext); - }; - VERUS_TYPEDEFS(State); - } + virtual bool IsValidNextState(State* p); + virtual void OnEnter(State* pPrev); + virtual void InputFocus_HandleInput() override; + virtual void HandleActions(); + virtual void Update(); + virtual void Draw(); + virtual void DrawView(CGI::RcViewDesc viewDesc); + virtual void OnExit(State* pNext); + }; + VERUS_TYPEDEFS(State); } diff --git a/Verus/src/Game/StateMachine.h b/Verus/src/Game/StateMachine.h index 0230599..84fbe66 100644 --- a/Verus/src/Game/StateMachine.h +++ b/Verus/src/Game/StateMachine.h @@ -1,34 +1,31 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Game { - namespace Game + class StateMachine : public Object, public Input::InputFocus { - class StateMachine : public Object, public Input::InputFocus - { - PState _pCurrentState = nullptr; - PState _pRequestedState = nullptr; - UINT64 _prevFrame = UINT64_MAX; - bool _changed = false; + PState _pCurrentState = nullptr; + PState _pRequestedState = nullptr; + UINT64 _prevFrame = UINT64_MAX; + bool _changed = false; - public: - virtual void InputFocus_HandleInput() override; - void HandleActions(); - void Update(); - void Draw(); - void DrawView(CGI::RcViewDesc viewDesc); + public: + virtual void InputFocus_HandleInput() override; + void HandleActions(); + void Update(); + void Draw(); + void DrawView(CGI::RcViewDesc viewDesc); - PState GetCurrentState() const; - PState GetRequestedState() const; + PState GetCurrentState() const; + PState GetRequestedState() const; - bool CanEnterState(RState state, bool allowSameState = false); - bool EnterState(RState state, bool allowSameState = false); - bool EnterRequestedState(); - void ReenterState(); - void RequestState(RState state); - bool IsStateChanged() const { return _changed; } - }; - VERUS_TYPEDEFS(StateMachine); - } + bool CanEnterState(RState state, bool allowSameState = false); + bool EnterState(RState state, bool allowSameState = false); + bool EnterRequestedState(); + void ReenterState(); + void RequestState(RState state); + bool IsStateChanged() const { return _changed; } + }; + VERUS_TYPEDEFS(StateMachine); } diff --git a/Verus/src/Global/Basic.h b/Verus/src/Global/Basic.h index 68e78be..23b1acd 100644 --- a/Verus/src/Global/Basic.h +++ b/Verus/src/Global/Basic.h @@ -8,48 +8,41 @@ #include "Singleton.h" #include "QuickRefs.h" -namespace verus +namespace verus::Math { - namespace Math + // Minimum & maximum: + template + T Min(T a, T b) { - // Clamp: - template - T Clamp(T x, T mn, T mx) - { - if (x <= mn) - return mn; - else if (x >= mx) - return mx; - return x; - } + return std::min(a, b); + } + template + T Max(T a, T b) + { + return std::max(a, b); + } - // Minimum & maximum: - template - T Min(T a, T b) - { - return a < b ? a : b; - } - template - T Max(T a, T b) - { - return a > b ? a : b; - } + // Clamp: + template + T Clamp(T x, T min, T max) + { + return std::clamp(x, min, max); + } - // Memory alignment: - template - T AlignUp(T val, T align) - { - return (val + align - 1) / align * align; - } - template - T AlignDown(T val, T align) - { - return val / align * align; - } - template - T DivideByMultiple(T value, T alignment) - { - return (value + alignment - 1) / alignment; - } + // Memory alignment: + template + T AlignUp(T value, T alignment) + { + return (value + alignment - 1) / alignment * alignment; + } + template + T AlignDown(T value, T alignment) + { + return value / alignment * alignment; + } + template + T DivideByMultiple(T value, T alignment) + { + return (value + alignment - 1) / alignment; } } diff --git a/Verus/src/Global/EngineInit.h b/Verus/src/Global/EngineInit.h index 32b62c5..37c1d48 100644 --- a/Verus/src/Global/EngineInit.h +++ b/Verus/src/Global/EngineInit.h @@ -1,12 +1,9 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::CGI { - namespace CGI - { - struct RendererDelegate; - } + struct RendererDelegate; } namespace verus diff --git a/Verus/src/Global/STL.h b/Verus/src/Global/STL.h index f45cba5..4bf4b6b 100644 --- a/Verus/src/Global/STL.h +++ b/Verus/src/Global/STL.h @@ -94,7 +94,7 @@ namespace verus template using Set = std::set , AllocatorAwareSTL>; template using MultiSet = std::multiset , AllocatorAwareSTL>; template using HashSet = std::unordered_set , std::equal_to, AllocatorAwareSTL>; - template using Map = std::map , AllocatorAwareSTL>; - template using MultiMap = std::multimap , AllocatorAwareSTL>; - template using HashMap = std::unordered_map , std::equal_to, AllocatorAwareSTL>; + template using Map = std::map , AllocatorAwareSTL>>; + template using MultiMap = std::multimap , AllocatorAwareSTL>>; + template using HashMap = std::unordered_map , std::equal_to, AllocatorAwareSTL>>; } diff --git a/Verus/src/Global/Store.h b/Verus/src/Global/Store.h index ad61b8a..46bbda6 100644 --- a/Verus/src/Global/Store.h +++ b/Verus/src/Global/Store.h @@ -128,9 +128,9 @@ namespace verus void DeleteAll() { - for (auto& x : _map) + for (auto& [key, value] : _map) { - while (!x.second.Done()); + while (!value.Done()); } _map.clear(); } diff --git a/Verus/src/Global/SyntaxHighlight.h b/Verus/src/Global/SyntaxHighlight.h deleted file mode 100644 index bab0980..0000000 --- a/Verus/src/Global/SyntaxHighlight.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. -BOOL -BYTE -VERUS_INTERFACE -CSZ -FALSE -ID -INT16 -INT32 -INT64 -NULL -offsetof -PRIVATE -PROTECTED -PUBLIC -Rcfloat4 -Rcfloat4x4 -Rfloat4 -Rfloat4x4 -size_t -SZ -time_t -TRUE -UINT16 -UINT32 -UINT64 -VOID diff --git a/Verus/src/Global/Typedef.h b/Verus/src/Global/Typedef.h index 2bcccdb..7f0f073 100644 --- a/Verus/src/Global/Typedef.h +++ b/Verus/src/Global/Typedef.h @@ -33,6 +33,8 @@ namespace verus typedef std::string String; typedef std::wstring WideString; + typedef std::string_view StringView; + typedef std::wstring_view WideStringView; typedef std::stringstream StringStream; typedef glm::quat Quaternion; diff --git a/Verus/src/IO/Async.cpp b/Verus/src/IO/Async.cpp index 13f37d4..83eb6f2 100644 --- a/Verus/src/IO/Async.cpp +++ b/Verus/src/IO/Async.cpp @@ -47,13 +47,13 @@ void Async::Load(CSZ url, PAsyncDelegate pDelegate, RcTaskDesc desc) { VERUS_LOCK(*this); - for (auto& kv : _mapTasks) + for (auto& [key, value] : _mapTasks) { - if (!strcmp(url, _C(kv.first) + s_orderLength)) + if (!strcmp(url, _C(key) + s_orderLength)) { // This resource is already scheduled. // Just add a new owner, if it's not already there. - RTask task = kv.second; + RTask task = value; if (std::find(task._vOwners.begin(), task._vOwners.end(), pDelegate) == task._vOwners.end()) task._vOwners.push_back(pDelegate); return; @@ -92,9 +92,9 @@ void Async::_Cancel(PAsyncDelegate pDelegate) { VERUS_RT_ASSERT(IsInitialized()); VERUS_LOCK(*this); - for (auto& kv : _mapTasks) + for (auto& [key, value] : _mapTasks) { - RTask task = kv.second; + RTask task = value; VERUS_WHILE(Vector, task._vOwners, it) { if (*it == pDelegate) diff --git a/Verus/src/IO/Async.h b/Verus/src/IO/Async.h index bec9487..37b3b3d 100644 --- a/Verus/src/IO/Async.h +++ b/Verus/src/IO/Async.h @@ -1,83 +1,80 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + struct AsyncDelegate { - struct AsyncDelegate + virtual void Async_WhenLoaded(CSZ url, RcBlob blob) = 0; + }; + VERUS_TYPEDEFS(AsyncDelegate); + + // Load resources asynchronously. + // Load method just adds the url to a queue. + // Load and Cancel are virtual so that they can be safely called from another DLL. + // Internally they can allocate and free memory. + class Async : public Singleton, public Object, public Lockable + { + public: + struct TaskDesc { - virtual void Async_WhenLoaded(CSZ url, RcBlob blob) = 0; - }; - VERUS_TYPEDEFS(AsyncDelegate); + int _texturePart = 0; + bool _nullTerm = false; + bool _checkExist = false; + bool _runOnMainThread = true; - // Load resources asynchronously. - // Load method just adds the url to a queue. - // Load and Cancel are virtual so that they can be safely called from another DLL. - // Internally they can allocate and free memory. - class Async : public Singleton, public Object, public Lockable + TaskDesc(bool nullTerm = false, bool checkExist = false, int texturePart = 0, bool runOnMainThread = true) : + _nullTerm(nullTerm), + _checkExist(checkExist), + _texturePart(texturePart), + _runOnMainThread(runOnMainThread) {} + }; + VERUS_TYPEDEFS(TaskDesc); + + private: + struct Task { - public: - struct TaskDesc - { - int _texturePart = 0; - bool _nullTerm = false; - bool _checkExist = false; - bool _runOnMainThread = true; - - TaskDesc(bool nullTerm = false, bool checkExist = false, int texturePart = 0, bool runOnMainThread = true) : - _nullTerm(nullTerm), - _checkExist(checkExist), - _texturePart(texturePart), - _runOnMainThread(runOnMainThread) {} - }; - VERUS_TYPEDEFS(TaskDesc); - - private: - struct Task - { - Vector _vOwners; - Vector _v; - TaskDesc _desc; - bool _loaded = false; - }; - VERUS_TYPEDEFS(Task); - - static const int s_orderLength = 8; - - typedef Map TMapTasks; - - TMapTasks _mapTasks; - std::thread _thread; - std::condition_variable _cv; - D::RuntimeError _ex; - CSZ _queue[256]; - int _cursorRead = 0; - int _cursorWrite = 0; - UINT32 _order = 0; - std::atomic_bool _stopThread; - bool _inUpdate = false; - bool _flush = false; - bool _onePerUpdateMode = false; - - public: - Async(); - ~Async(); - - void Init(); - void Done(); - - virtual void Load(CSZ url, PAsyncDelegate pDelegate, RcTaskDesc desc = TaskDesc()); - VERUS_P(virtual void _Cancel(PAsyncDelegate pDelegate)); - static void Cancel(PAsyncDelegate pDelegate); - - virtual void Update(); - - void Flush(); - void SetOnePerUpdateMode(bool b) { _onePerUpdateMode = b; } - - VERUS_P(void ThreadProc()); + Vector _vOwners; + Vector _v; + TaskDesc _desc; + bool _loaded = false; }; - VERUS_TYPEDEFS(Async); - } + VERUS_TYPEDEFS(Task); + + static const int s_orderLength = 8; + + typedef Map TMapTasks; + + TMapTasks _mapTasks; + std::thread _thread; + std::condition_variable _cv; + D::RuntimeError _ex; + CSZ _queue[256]; + int _cursorRead = 0; + int _cursorWrite = 0; + UINT32 _order = 0; + std::atomic_bool _stopThread; + bool _inUpdate = false; + bool _flush = false; + bool _onePerUpdateMode = false; + + public: + Async(); + ~Async(); + + void Init(); + void Done(); + + virtual void Load(CSZ url, PAsyncDelegate pDelegate, RcTaskDesc desc = TaskDesc()); + VERUS_P(virtual void _Cancel(PAsyncDelegate pDelegate)); + static void Cancel(PAsyncDelegate pDelegate); + + virtual void Update(); + + void Flush(); + void SetOnePerUpdateMode(bool b) { _onePerUpdateMode = b; } + + VERUS_P(void ThreadProc()); + }; + VERUS_TYPEDEFS(Async); } diff --git a/Verus/src/IO/DDSHeader.h b/Verus/src/IO/DDSHeader.h index b32708c..84c1c24 100644 --- a/Verus/src/IO/DDSHeader.h +++ b/Verus/src/IO/DDSHeader.h @@ -1,145 +1,142 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + struct DDSHeader { - struct DDSHeader + enum class Flags : UINT32 { - enum class Flags : UINT32 - { - caps /**/ = 0x00000001, - height /**/ = 0x00000002, - width /**/ = 0x00000004, - pitch /**/ = 0x00000008, - pixelFormat /**/ = 0x00001000, - mipMapCount /**/ = 0x00020000, - linearSize /**/ = 0x00080000, - depth /**/ = 0x00800000 - }; - - enum class PixelFormatFlags : UINT32 - { - alphaPixels /**/ = 0x00000001, - alpha /**/ = 0x00000002, - fourCC /**/ = 0x00000004, - indexed /**/ = 0x00000020, - rgb /**/ = 0x00000040, - compressed /**/ = 0x00000080, - luminance /**/ = 0x00020000 - }; - - enum class Caps1 : UINT32 - { - complex /**/ = 0x00000008, - texture /**/ = 0x00001000, - mipMap /**/ = 0x00400000 - }; - - enum class Caps2 : UINT32 - { - cubemap /**/ = 0x00000200, - cubemapPositiveX /**/ = 0x00000400, - cubemapNegativeX /**/ = 0x00000800, - cubemapPositiveY /**/ = 0x00001000, - cubemapNegativeY /**/ = 0x00002000, - cubemapPositiveZ /**/ = 0x00004000, - cubemapNegativeZ /**/ = 0x00008000, - volume /**/ = 0x00200000 - }; - - enum class FourCC : UINT32 - { - dxt1 = '1TXD', - dxt3 = '3TXD', - dxt5 = '5TXD', - bc4u = 'U4CB', - bc4s = 'S4CB', - bc5u = '2ITA', - bc5s = 'S5CB', - dx10 = '01XD' - }; - - struct PixelFormat - { - UINT32 _size; - PixelFormatFlags _flags; - FourCC _fourCC; - UINT32 _rgbBitCount; - UINT32 _rBitMask; - UINT32 _gBitMask; - UINT32 _bBitMask; - UINT32 _rgbAlphaBitMask; - }; - - struct Caps - { - Caps1 _caps1; - Caps2 _caps2; - UINT32 _reserved[2]; - }; - - char _magic[4]; - UINT32 _size; - Flags _flags; - UINT32 _height; - UINT32 _width; - UINT32 _pitchOrLinearSize; - UINT32 _depth; - UINT32 _mipMapCount; - UINT32 _reserved1[11]; - PixelFormat _pixelFormat; - Caps _caps; - UINT32 _reserved2; - - DDSHeader(); - bool Validate() const; - bool IsDXT10() const; - bool Is4BitsBC() const; - bool IsBC1() const; - bool IsBC2() const; - bool IsBC3() const; - bool IsBC4U() const; - bool IsBC4S() const; - bool IsBC5U() const; - bool IsBC5S() const; - bool IsBC() const; - bool IsBGRA8() const; - bool IsBGR8() const; - static int ComputeBcLevelSize(int w, int h, bool is4Bits); - static int ComputeBcPitch(int w, int h, bool is4Bits); - int GetPartCount() const; - int SkipParts(int skipCount); + caps /**/ = 0x00000001, + height /**/ = 0x00000002, + width /**/ = 0x00000004, + pitch /**/ = 0x00000008, + pixelFormat /**/ = 0x00001000, + mipMapCount /**/ = 0x00020000, + linearSize /**/ = 0x00080000, + depth /**/ = 0x00800000 }; - VERUS_TYPEDEFS(DDSHeader); - struct DDSHeaderDXT10 + enum class PixelFormatFlags : UINT32 { - enum class Format : UINT32 - { - bc4 = 80, - bc5 = 83, - bc7 = 98 - }; - - enum class Dimension : UINT32 - { - unknown = 0, - buffer = 1, - texture1D = 2, - texture2D = 3, - texture3D = 4 - }; - - Format _dxgiFormat; - Dimension _resourceDimension; - UINT32 _miscFlag; - UINT32 _arraySize; - UINT32 _miscFlags2; - - bool IsBC7() const; + alphaPixels /**/ = 0x00000001, + alpha /**/ = 0x00000002, + fourCC /**/ = 0x00000004, + indexed /**/ = 0x00000020, + rgb /**/ = 0x00000040, + compressed /**/ = 0x00000080, + luminance /**/ = 0x00020000 }; - VERUS_TYPEDEFS(DDSHeaderDXT10); - } + + enum class Caps1 : UINT32 + { + complex /**/ = 0x00000008, + texture /**/ = 0x00001000, + mipMap /**/ = 0x00400000 + }; + + enum class Caps2 : UINT32 + { + cubemap /**/ = 0x00000200, + cubemapPositiveX /**/ = 0x00000400, + cubemapNegativeX /**/ = 0x00000800, + cubemapPositiveY /**/ = 0x00001000, + cubemapNegativeY /**/ = 0x00002000, + cubemapPositiveZ /**/ = 0x00004000, + cubemapNegativeZ /**/ = 0x00008000, + volume /**/ = 0x00200000 + }; + + enum class FourCC : UINT32 + { + dxt1 = '1TXD', + dxt3 = '3TXD', + dxt5 = '5TXD', + bc4u = 'U4CB', + bc4s = 'S4CB', + bc5u = '2ITA', + bc5s = 'S5CB', + dx10 = '01XD' + }; + + struct PixelFormat + { + UINT32 _size; + PixelFormatFlags _flags; + FourCC _fourCC; + UINT32 _rgbBitCount; + UINT32 _rBitMask; + UINT32 _gBitMask; + UINT32 _bBitMask; + UINT32 _rgbAlphaBitMask; + }; + + struct Caps + { + Caps1 _caps1; + Caps2 _caps2; + UINT32 _reserved[2]; + }; + + char _magic[4]; + UINT32 _size; + Flags _flags; + UINT32 _height; + UINT32 _width; + UINT32 _pitchOrLinearSize; + UINT32 _depth; + UINT32 _mipMapCount; + UINT32 _reserved1[11]; + PixelFormat _pixelFormat; + Caps _caps; + UINT32 _reserved2; + + DDSHeader(); + bool Validate() const; + bool IsDXT10() const; + bool Is4BitsBC() const; + bool IsBC1() const; + bool IsBC2() const; + bool IsBC3() const; + bool IsBC4U() const; + bool IsBC4S() const; + bool IsBC5U() const; + bool IsBC5S() const; + bool IsBC() const; + bool IsBGRA8() const; + bool IsBGR8() const; + static int ComputeBcLevelSize(int w, int h, bool is4Bits); + static int ComputeBcPitch(int w, int h, bool is4Bits); + int GetPartCount() const; + int SkipParts(int skipCount); + }; + VERUS_TYPEDEFS(DDSHeader); + + struct DDSHeaderDXT10 + { + enum class Format : UINT32 + { + bc4 = 80, + bc5 = 83, + bc7 = 98 + }; + + enum class Dimension : UINT32 + { + unknown = 0, + buffer = 1, + texture1D = 2, + texture2D = 3, + texture3D = 4 + }; + + Format _dxgiFormat; + Dimension _resourceDimension; + UINT32 _miscFlag; + UINT32 _arraySize; + UINT32 _miscFlags2; + + bool IsBC7() const; + }; + VERUS_TYPEDEFS(DDSHeaderDXT10); } diff --git a/Verus/src/IO/Dictionary.cpp b/Verus/src/IO/Dictionary.cpp index e58b856..8013dc5 100644 --- a/Verus/src/IO/Dictionary.cpp +++ b/Verus/src/IO/Dictionary.cpp @@ -138,8 +138,8 @@ void Dictionary::Deserialize(RStream stream) String Dictionary::ToString() const { StringStream ss; - for (const auto& x : TStoreValues::_map) - ss << x.first << ": " << x.second._s << VERUS_CRNL; + for (const auto& [key, value] : TStoreValues::_map) + ss << key << ": " << value._s << VERUS_CRNL; return ss.str(); } diff --git a/Verus/src/IO/Dictionary.h b/Verus/src/IO/Dictionary.h index d646114..d99693e 100644 --- a/Verus/src/IO/Dictionary.h +++ b/Verus/src/IO/Dictionary.h @@ -1,66 +1,63 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + class DictionaryValue { - class DictionaryValue + public: + String _s; + int _i = 0; + float _f = 0; + + DictionaryValue(); + DictionaryValue(CSZ value); + void Set(CSZ value); + + void AddRef() {} + bool Done() { return true; } + }; + VERUS_TYPEDEFS(DictionaryValue); + + typedef StoreUnique TStoreValues; + class Dictionary : private TStoreValues + { + Dictionary* _pParent = nullptr; + + public: + Dictionary(); + ~Dictionary(); + + void LinkParent(Dictionary* p); + + void Insert(CSZ key, CSZ value); + void Delete(CSZ key); + void DeleteAll(); + + CSZ Find(CSZ key, CSZ def = nullptr) const; + RcString FindSafe(CSZ key) const; + int FindInt(CSZ key, int def = 0) const; + float FindFloat(CSZ key, float def = 0) const; + + int GetCount() const; + + void ExportAsStrings(Vector& v) const; + + void Serialize(RStream stream); + void Deserialize(RStream stream); + + String ToString() const; + void FromString(CSZ text); + + template + void ForEach(const T& fn) { - public: - String _s; - int _i = 0; - float _f = 0; - - DictionaryValue(); - DictionaryValue(CSZ value); - void Set(CSZ value); - - void AddRef() {} - bool Done() { return true; } - }; - VERUS_TYPEDEFS(DictionaryValue); - - typedef StoreUnique TStoreValues; - class Dictionary : private TStoreValues - { - Dictionary* _pParent = nullptr; - - public: - Dictionary(); - ~Dictionary(); - - void LinkParent(Dictionary* p); - - void Insert(CSZ key, CSZ value); - void Delete(CSZ key); - void DeleteAll(); - - CSZ Find(CSZ key, CSZ def = nullptr) const; - RcString FindSafe(CSZ key) const; - int FindInt(CSZ key, int def = 0) const; - float FindFloat(CSZ key, float def = 0) const; - - int GetCount() const; - - void ExportAsStrings(Vector& v) const; - - void Serialize(RStream stream); - void Deserialize(RStream stream); - - String ToString() const; - void FromString(CSZ text); - - template - void ForEach(const T& fn) + for (const auto& [key, value] : TStoreValues::_map) { - for (const auto& x : TStoreValues::_map) - { - if (Continue::no == fn(_C(x.first), _C(x.second._s))) - return; - } + if (Continue::no == fn(_C(key), _C(value._s))) + return; } - }; - VERUS_TYPEDEFS(Dictionary); - } + } + }; + VERUS_TYPEDEFS(Dictionary); } diff --git a/Verus/src/IO/File.h b/Verus/src/IO/File.h index 8b7b85d..5dc87bf 100644 --- a/Verus/src/IO/File.h +++ b/Verus/src/IO/File.h @@ -1,30 +1,27 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + // Treat a file as a stream. + class File : public SeekableStream { - // Treat a file as a stream. - class File : public SeekableStream - { - FILE* _pFile = nullptr; + FILE* _pFile = nullptr; - public: - File(); - ~File(); + public: + File(); + ~File(); - bool Open(CSZ pathname, CSZ mode = "rb"); - void Close(); + bool Open(CSZ pathname, CSZ mode = "rb"); + void Close(); - virtual INT64 Read(void* p, INT64 size) override; - virtual INT64 Write(const void* p, INT64 size) override; + virtual INT64 Read(void* p, INT64 size) override; + virtual INT64 Write(const void* p, INT64 size) override; - virtual void Seek(INT64 offset, int origin) override; - virtual INT64 GetPosition() override; + virtual void Seek(INT64 offset, int origin) override; + virtual INT64 GetPosition() override; - FILE* GetFile() { return _pFile; } - }; - VERUS_TYPEDEFS(File); - } + FILE* GetFile() { return _pFile; } + }; + VERUS_TYPEDEFS(File); } diff --git a/Verus/src/IO/FileSystem.h b/Verus/src/IO/FileSystem.h index d3caeeb..0a543c4 100644 --- a/Verus/src/IO/FileSystem.h +++ b/Verus/src/IO/FileSystem.h @@ -1,92 +1,89 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + enum class ImageFormat : int { - enum class ImageFormat : int + extension, + png, + tga, + jpg + }; + + class FileSystem : public Singleton + { + typedef Map> TMapCache; + + static CSZ s_dataFolder; + static CSZ s_shaderPAK; + + TMapCache _mapCache; + INT64 _cacheSize = 0; + + public: + struct LoadDesc { - extension, - png, - tga, - jpg + int _texturePart = 0; + bool _nullTerm = false; + bool _mandatory = true; + + LoadDesc(bool nullTerm = false, int texturePart = 0, bool mandatory = true) : + _nullTerm(nullTerm), _texturePart(texturePart), _mandatory(mandatory) {} }; + VERUS_TYPEDEFS(LoadDesc); - class FileSystem : public Singleton - { - typedef Map> TMapCache; + static const int s_querySize = 240; + static const int s_entrySize = 256; - static CSZ s_dataFolder; - static CSZ s_shaderPAK; + FileSystem(); + ~FileSystem(); - TMapCache _mapCache; - INT64 _cacheSize = 0; + static size_t FindPosForPAK(CSZ url); + static void ReadPakHeader(RFile file, UINT32& magic, INT64& entriesOffset, INT64& entriesSize); - public: - struct LoadDesc - { - int _texturePart = 0; - bool _nullTerm = false; - bool _mandatory = true; + void PreloadCache(CSZ pak, CSZ types[]); + void PreloadDefaultCache(); - LoadDesc(bool nullTerm = false, int texturePart = 0, bool mandatory = true) : - _nullTerm(nullTerm), _texturePart(texturePart), _mandatory(mandatory) {} - }; - VERUS_TYPEDEFS(LoadDesc); + static void LoadResource /**/(CSZ url, Vector& vData, RcLoadDesc desc = LoadDesc()); + static void LoadResourceFromFile /**/(CSZ url, Vector& vData, RcLoadDesc desc = LoadDesc()); - static const int s_querySize = 240; - static const int s_entrySize = 256; + void LoadResourceFromCache(CSZ url, Vector& vData, bool mandatory = true); - FileSystem(); - ~FileSystem(); + VERUS_P(static void LoadResourceFromPAK(CSZ url, Vector& vData, RcLoadDesc desc, RFile file, CSZ pakEntry)); - static size_t FindPosForPAK(CSZ url); - static void ReadPakHeader(RFile file, UINT32& magic, INT64& entriesOffset, INT64& entriesSize); + static void LoadTextureParts(RFile file, CSZ url, int texturePart, Vector& vData); + static String ConvertFilenameToPassword(CSZ fileEntry); - void PreloadCache(CSZ pak, CSZ types[]); - void PreloadDefaultCache(); + static bool FileExist(CSZ url); + static bool Delete(CSZ pathname); - static void LoadResource /**/(CSZ url, Vector& vData, RcLoadDesc desc = LoadDesc()); - static void LoadResourceFromFile /**/(CSZ url, Vector& vData, RcLoadDesc desc = LoadDesc()); + // Path & filename: + static String ConvertAbsolutePathToRelative(RcString path); + static String ConvertRelativePathToAbsolute(RcString path, bool useProjectDir); + static String ReplaceFilename(CSZ pathname, CSZ filename); - void LoadResourceFromCache(CSZ url, Vector& vData, bool mandatory = true); + // Save data: + static void SaveImage /**/(CSZ pathname, const void* p, int w, int h, ImageFormat format = ImageFormat::tga, int pixelStride = sizeof(UINT32), int param = 0); + static void SaveDDS /**/(CSZ pathname, const void* p, int w, int h, int d = 0); + static void SaveString/**/(CSZ pathname, CSZ s); + }; + VERUS_TYPEDEFS(FileSystem); - VERUS_P(static void LoadResourceFromPAK(CSZ url, Vector& vData, RcLoadDesc desc, RFile file, CSZ pakEntry)); + class Image : public Object + { + public: + Vector _vData; + BYTE* _p = nullptr; + int _width = 0; + int _height = 0; + int _pixelStride = 0; - static void LoadTextureParts(RFile file, CSZ url, int texturePart, Vector& vData); - static String ConvertFilenameToPassword(CSZ fileEntry); + Image(); + ~Image(); - static bool FileExist(CSZ url); - static bool Delete(CSZ pathname); - - // Path & filename: - static String ConvertAbsolutePathToRelative(RcString path); - static String ConvertRelativePathToAbsolute(RcString path, bool useProjectDir); - static String ReplaceFilename(CSZ pathname, CSZ filename); - - // Save data: - static void SaveImage /**/(CSZ pathname, const void* p, int w, int h, ImageFormat format = ImageFormat::tga, int pixelStride = sizeof(UINT32), int param = 0); - static void SaveDDS /**/(CSZ pathname, const void* p, int w, int h, int d = 0); - static void SaveString/**/(CSZ pathname, CSZ s); - }; - VERUS_TYPEDEFS(FileSystem); - - class Image : public Object - { - public: - Vector _vData; - BYTE* _p = nullptr; - int _width = 0; - int _height = 0; - int _pixelStride = 0; - - Image(); - ~Image(); - - void Init(CSZ url); - void Done(); - }; - VERUS_TYPEDEFS(Image); - } + void Init(CSZ url); + void Done(); + }; + VERUS_TYPEDEFS(Image); } diff --git a/Verus/src/IO/Json.h b/Verus/src/IO/Json.h index 279624d..97d2215 100644 --- a/Verus/src/IO/Json.h +++ b/Verus/src/IO/Json.h @@ -1,36 +1,33 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + class Json { - class Json - { - nlohmann::json _json; - String _pathname; + nlohmann::json _json; + String _pathname; - public: - Json(); - Json(CSZ pathname); - ~Json(); + public: + Json(); + Json(CSZ pathname); + ~Json(); - Str GetFilename() const { return _C(_pathname); } - void SetFilename(CSZ name); - void Load(bool fromCache = false); - void Save(); - void Clear(); + Str GetFilename() const { return _C(_pathname); } + void SetFilename(CSZ name); + void Load(bool fromCache = false); + void Save(); + void Clear(); - void Set(CSZ name, CSZ v, bool ifNull = false); - void Set(CSZ name, int v, bool ifNull = false); - void Set(CSZ name, float v, bool ifNull = false); - void Set(CSZ name, bool v, bool ifNull = false); + void Set(CSZ name, CSZ v, bool ifNull = false); + void Set(CSZ name, int v, bool ifNull = false); + void Set(CSZ name, float v, bool ifNull = false); + void Set(CSZ name, bool v, bool ifNull = false); - CSZ GetS(CSZ name, CSZ def = nullptr); - int GetI(CSZ name, int def = 0); - float GetF(CSZ name, float def = 0); - bool GetB(CSZ name, bool def = false); - }; - VERUS_TYPEDEFS(Json); - } + CSZ GetS(CSZ name, CSZ def = nullptr); + int GetI(CSZ name, int def = 0); + float GetF(CSZ name, float def = 0); + bool GetB(CSZ name, bool def = false); + }; + VERUS_TYPEDEFS(Json); } diff --git a/Verus/src/IO/Stream.h b/Verus/src/IO/Stream.h index 39ee4b3..aeb6fb5 100644 --- a/Verus/src/IO/Stream.h +++ b/Verus/src/IO/Stream.h @@ -1,120 +1,117 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + class Stream { - class Stream + UINT32 _version = 0; + + public: + static const int s_bufferSize = UCHAR_MAX + 1; + + Stream() {} + virtual ~Stream() {} + + virtual BYTE* GetPointer() { return nullptr; } + + virtual INT64 Read(void* p, INT64 size) = 0; + virtual INT64 Write(const void* p, INT64 size) = 0; + + INT64 ReadString(SZ sz) { - UINT32 _version = 0; + BYTE len; + (*this) >> len; + const INT64 ret = Read(sz, len); + sz[len] = 0; + return ret + 1; + } - public: - static const int s_bufferSize = UCHAR_MAX + 1; - - Stream() {} - virtual ~Stream() {} - - virtual BYTE* GetPointer() { return nullptr; } - - virtual INT64 Read(void* p, INT64 size) = 0; - virtual INT64 Write(const void* p, INT64 size) = 0; - - INT64 ReadString(SZ sz) - { - BYTE len; - (*this) >> len; - const INT64 ret = Read(sz, len); - sz[len] = 0; - return ret + 1; - } - - INT64 WriteString(CSZ sz) - { - const size_t len = strlen(sz); - if (len > UCHAR_MAX) - throw verus::D::RuntimeError(std::this_thread::get_id(), "Stream.h", __LINE__) << "WriteString(); Invalid string length"; - (*this) << static_cast(len); - const INT64 ret = Write(sz, len); - return ret + 1; - } - - void WriteText(CSZ sz) - { - Write(sz, strlen(sz)); - } - - Stream& operator<<(CSZ txt) - { - WriteText(txt); - return *this; - } - - template Stream& operator<<(const T& x) - { - Write(&x, sizeof(T)); - return *this; - } - - template Stream& operator>>(T& x) - { - Read(&x, sizeof(T)); - return *this; - } - - UINT32 GetVersion() const { return _version; } - void SetVersion(UINT32 version) { _version = version; } - }; - VERUS_TYPEDEFS(Stream); - - class SeekableStream : public Stream + INT64 WriteString(CSZ sz) { - INT64 _blockOffset = 0; + const size_t len = strlen(sz); + if (len > UCHAR_MAX) + throw verus::D::RuntimeError(std::this_thread::get_id(), "Stream.h", __LINE__) << "WriteString(); Invalid string length"; + (*this) << static_cast(len); + const INT64 ret = Write(sz, len); + return ret + 1; + } - public: - SeekableStream() {} - virtual ~SeekableStream() {} + void WriteText(CSZ sz) + { + Write(sz, strlen(sz)); + } - virtual void Seek(INT64 offset, int origin) = 0; - virtual INT64 GetPosition() = 0; + Stream& operator<<(CSZ txt) + { + WriteText(txt); + return *this; + } - // Adds a placeholder for block size and begins a block: - void BeginBlock() - { - VERUS_RT_ASSERT(!_blockOffset); - _blockOffset = GetPosition(); - const INT64 zero = 0; - Write(&zero, sizeof(zero)); - } + template Stream& operator<<(const T& x) + { + Write(&x, sizeof(T)); + return *this; + } - // Ends a block by placing it's size into placeholder: - void EndBlock() - { - VERUS_RT_ASSERT(_blockOffset); - const INT64 offset = GetPosition(); - const INT64 delta = offset - _blockOffset - sizeof(INT64); - Seek(_blockOffset, SEEK_SET); - Write(&delta, sizeof(delta)); - Seek(0, SEEK_END); - _blockOffset = 0; - } + template Stream& operator>>(T& x) + { + Read(&x, sizeof(T)); + return *this; + } - INT64 GetSize() - { - const INT64 was = GetPosition(); - Seek(0, SEEK_END); - const INT64 size = GetPosition(); - Seek(was, SEEK_SET); - return size; - } + UINT32 GetVersion() const { return _version; } + void SetVersion(UINT32 version) { _version = version; } + }; + VERUS_TYPEDEFS(Stream); - void ReadAll(Vector& vData, bool nullTerm = false) - { - const INT64 size = GetSize(); - vData.resize(nullTerm ? size + 1 : size); - Read(vData.data(), size); - } - }; - VERUS_TYPEDEFS(SeekableStream); - } + class SeekableStream : public Stream + { + INT64 _blockOffset = 0; + + public: + SeekableStream() {} + virtual ~SeekableStream() {} + + virtual void Seek(INT64 offset, int origin) = 0; + virtual INT64 GetPosition() = 0; + + // Adds a placeholder for block size and begins a block: + void BeginBlock() + { + VERUS_RT_ASSERT(!_blockOffset); + _blockOffset = GetPosition(); + const INT64 zero = 0; + Write(&zero, sizeof(zero)); + } + + // Ends a block by placing it's size into placeholder: + void EndBlock() + { + VERUS_RT_ASSERT(_blockOffset); + const INT64 offset = GetPosition(); + const INT64 delta = offset - _blockOffset - sizeof(INT64); + Seek(_blockOffset, SEEK_SET); + Write(&delta, sizeof(delta)); + Seek(0, SEEK_END); + _blockOffset = 0; + } + + INT64 GetSize() + { + const INT64 was = GetPosition(); + Seek(0, SEEK_END); + const INT64 size = GetPosition(); + Seek(was, SEEK_SET); + return size; + } + + void ReadAll(Vector& vData, bool nullTerm = false) + { + const INT64 size = GetSize(); + vData.resize(nullTerm ? size + 1 : size); + Read(vData.data(), size); + } + }; + VERUS_TYPEDEFS(SeekableStream); } diff --git a/Verus/src/IO/StreamPtr.h b/Verus/src/IO/StreamPtr.h index 4f7fa6e..af498f8 100644 --- a/Verus/src/IO/StreamPtr.h +++ b/Verus/src/IO/StreamPtr.h @@ -1,40 +1,37 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + class StreamPtr : public Stream { - class StreamPtr : public Stream + const BYTE* _p; + INT64 _size; + INT64 _offset; + + public: + StreamPtr(RcBlob blob) : _p(blob._p), _size(blob._size), _offset(0) {} + ~StreamPtr() {} + + INT64 GetOffset() const { return _offset; } + INT64 GetSize() const { return _size; } + bool IsEnd() const { return _offset >= _size; } + + void Advance(INT64 a) { _offset += a; } + + virtual INT64 Read(void* p, INT64 size) override { - const BYTE* _p; - INT64 _size; - INT64 _offset; + VERUS_RT_ASSERT(_offset + size <= _size); + memcpy(p, _p + _offset, size); + _offset += size; + return size; + } - public: - StreamPtr(RcBlob blob) : _p(blob._p), _size(blob._size), _offset(0) {} - ~StreamPtr() {} - - INT64 GetOffset() const { return _offset; } - INT64 GetSize() const { return _size; } - bool IsEnd() const { return _offset >= _size; } - - void Advance(INT64 a) { _offset += a; } - - virtual INT64 Read(void* p, INT64 size) override - { - VERUS_RT_ASSERT(_offset + size <= _size); - memcpy(p, _p + _offset, size); - _offset += size; - return size; - } - - virtual INT64 Write(const void* p, INT64 size) override - { - VERUS_RT_FAIL("Write()"); - return 0; - } - }; - VERUS_TYPEDEFS(StreamPtr); - } + virtual INT64 Write(const void* p, INT64 size) override + { + VERUS_RT_FAIL("Write()"); + return 0; + } + }; + VERUS_TYPEDEFS(StreamPtr); } diff --git a/Verus/src/IO/Vwx.h b/Verus/src/IO/Vwx.h index 56d77d1..92e4531 100644 --- a/Verus/src/IO/Vwx.h +++ b/Verus/src/IO/Vwx.h @@ -1,22 +1,19 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + class Vwx : public AsyncDelegate { - class Vwx : public AsyncDelegate - { - public: - Vwx(); - ~Vwx(); + public: + Vwx(); + ~Vwx(); - virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; + virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; - void Serialize(CSZ url); - void Deserialize(CSZ url, bool sync); + void Serialize(CSZ url); + void Deserialize(CSZ url, bool sync); - void Deserialize_LegacyXXX(CSZ url, RcBlob blob); - }; - } + void Deserialize_LegacyXXX(CSZ url, RcBlob blob); + }; } diff --git a/Verus/src/IO/Xml.h b/Verus/src/IO/Xml.h index 9decf44..ec5b22b 100644 --- a/Verus/src/IO/Xml.h +++ b/Verus/src/IO/Xml.h @@ -1,39 +1,36 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::IO { - namespace IO + class Xml { - class Xml - { - pugi::xml_document _doc; - String _pathname; - Vector _vData; + pugi::xml_document _doc; + String _pathname; + Vector _vData; - public: - Xml(); - Xml(CSZ pathname); - ~Xml(); + public: + Xml(); + Xml(CSZ pathname); + ~Xml(); - Str GetFilename() const { return _C(_pathname); } - void SetFilename(CSZ name); - void Load(bool fromCache = false); - void Save(); + Str GetFilename() const { return _C(_pathname); } + void SetFilename(CSZ name); + void Load(bool fromCache = false); + void Save(); - pugi::xml_node GetRoot(); - pugi::xml_node AddElement(CSZ name); + pugi::xml_node GetRoot(); + pugi::xml_node AddElement(CSZ name); - void Set(CSZ name, CSZ v, bool ifNull = false); - void Set(CSZ name, int v, bool ifNull = false); - void Set(CSZ name, float v, bool ifNull = false); - void Set(CSZ name, bool v, bool ifNull = false); + void Set(CSZ name, CSZ v, bool ifNull = false); + void Set(CSZ name, int v, bool ifNull = false); + void Set(CSZ name, float v, bool ifNull = false); + void Set(CSZ name, bool v, bool ifNull = false); - CSZ GetS(CSZ name, CSZ def = nullptr); - int GetI(CSZ name, int def = 0); - float GetF(CSZ name, float def = 0); - bool GetB(CSZ name, bool def = false); - }; - VERUS_TYPEDEFS(Xml); - } + CSZ GetS(CSZ name, CSZ def = nullptr); + int GetI(CSZ name, int def = 0); + float GetF(CSZ name, float def = 0); + bool GetB(CSZ name, bool def = false); + }; + VERUS_TYPEDEFS(Xml); } diff --git a/Verus/src/Input/DragController.h b/Verus/src/Input/DragController.h index f65b41a..e8e4cc9 100644 --- a/Verus/src/Input/DragController.h +++ b/Verus/src/Input/DragController.h @@ -1,44 +1,41 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Input { - namespace Input + struct DragControllerDelegate { - struct DragControllerDelegate - { - virtual void DragController_GetParams(float& x, float& y) = 0; - virtual void DragController_SetParams(float x, float y) = 0; - virtual void DragController_GetRatio(float& x, float& y) = 0; - virtual void DragController_Begin() {} - virtual void DragController_End() {} - virtual void DragController_SetScale(float s) {} - }; - VERUS_TYPEDEFS(DragControllerDelegate); + virtual void DragController_GetParams(float& x, float& y) = 0; + virtual void DragController_SetParams(float x, float y) = 0; + virtual void DragController_GetRatio(float& x, float& y) = 0; + virtual void DragController_Begin() {} + virtual void DragController_End() {} + virtual void DragController_SetScale(float s) {} + }; + VERUS_TYPEDEFS(DragControllerDelegate); - class DragController - { - PDragControllerDelegate _pDelegate = nullptr; - float _originX = 0; - float _originY = 0; - int _originCoordX = 0; - int _originCoordY = 0; - float _ratioX = 1; - float _ratioY = 1; - bool _holding = false; + class DragController + { + PDragControllerDelegate _pDelegate = nullptr; + float _originX = 0; + float _originY = 0; + int _originCoordX = 0; + int _originCoordY = 0; + float _ratioX = 1; + float _ratioY = 1; + bool _holding = false; - public: - void SetDelegate(PDragControllerDelegate p); + public: + void SetDelegate(PDragControllerDelegate p); - void Begin(int x, int y); - bool DragTo(int x, int y); - bool DragBy(int x, int y); - void End(); + void Begin(int x, int y); + bool DragTo(int x, int y); + bool DragBy(int x, int y); + void End(); - bool IsHolding() const { return _holding; } + bool IsHolding() const { return _holding; } - void SetScale(float s); - }; - VERUS_TYPEDEFS(DragController); - } + void SetScale(float s); + }; + VERUS_TYPEDEFS(DragController); } diff --git a/Verus/src/Input/Gamepad.h b/Verus/src/Input/Gamepad.h index 49b9f6c..af96366 100644 --- a/Verus/src/Input/Gamepad.h +++ b/Verus/src/Input/Gamepad.h @@ -1,27 +1,24 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Input { - namespace Input + class Gamepad { - class Gamepad - { - SDL_GameController* _pGameController = nullptr; - SDL_Haptic* _pHaptic = nullptr; - SDL_JoystickID _joystickID = -1; - bool _connected = false; + SDL_GameController* _pGameController = nullptr; + SDL_Haptic* _pHaptic = nullptr; + SDL_JoystickID _joystickID = -1; + bool _connected = false; - public: - Gamepad(); - ~Gamepad(); + public: + Gamepad(); + ~Gamepad(); - void Open(int joystickIndex); - void Close(); + void Open(int joystickIndex); + void Close(); - SDL_JoystickID GetJoystickID() const { return _joystickID; } - bool IsConnected() const { return _connected; } - }; - VERUS_TYPEDEFS(Gamepad); - } + SDL_JoystickID GetJoystickID() const { return _joystickID; } + bool IsConnected() const { return _connected; } + }; + VERUS_TYPEDEFS(Gamepad); } diff --git a/Verus/src/Input/InputManager.h b/Verus/src/Input/InputManager.h index 834c860..1dc37e8 100644 --- a/Verus/src/Input/InputManager.h +++ b/Verus/src/Input/InputManager.h @@ -6,234 +6,231 @@ #define VERUS_BUTTON_WHEELUP 6 #define VERUS_BUTTON_WHEELDOWN 7 -namespace verus +namespace verus::Input { - namespace Input + struct InputFocus { - struct InputFocus - { - virtual bool InputFocus_Veto() { return false; } - virtual void InputFocus_HandleInput() {} - virtual void InputFocus_OnKeyDown(int scancode) {} - virtual void InputFocus_OnKeyUp(int scancode) {} - virtual void InputFocus_OnTextInput(wchar_t c) {} - virtual void InputFocus_OnMouseMove(int dx, int dy, int x, int y) {} - virtual void InputFocus_OnMouseMove(float dx, float dy) {} - }; - VERUS_TYPEDEFS(InputFocus); + virtual bool InputFocus_Veto() { return false; } + virtual void InputFocus_HandleInput() {} + virtual void InputFocus_OnKeyDown(int scancode) {} + virtual void InputFocus_OnKeyUp(int scancode) {} + virtual void InputFocus_OnTextInput(wchar_t c) {} + virtual void InputFocus_OnMouseMove(int dx, int dy, int x, int y) {} + virtual void InputFocus_OnMouseMove(float dx, float dy) {} + }; + VERUS_TYPEDEFS(InputFocus); - enum class ActionType : int + enum class ActionType : int + { + inBoolean, + inFloat, + inVector2, + inPose, + outVibration + }; + + class InputManager : public Singleton, public Object + { + public: + struct ActionSet { - inBoolean, - inFloat, - inVector2, - inPose, - outVibration + String _name; // Must be lowercase. + String _localizedName; + UINT32 _priority = 0; + bool _xrCompatible = false; + }; + VERUS_TYPEDEFS(ActionSet); + + struct Action + { + Vector _vSubactionPaths; + Vector _vBindingPaths; + String _name; // Must be lowercase. + String _localizedName; + ActionType _type = ActionType::inBoolean; + int _setIndex = 0; + + bool _changedState = false; + bool _booleanValue = false; + float _floatValue = 0; + }; + VERUS_TYPEDEFS(Action); + + struct ActionIndex + { + UINT32 _atom = 0; + int _actionIndex = 0; + + bool _changedState = false; + bool _booleanValue = false; + bool _negativeBoolean = false; + float _floatValue = 0; + }; + VERUS_TYPEDEFS(ActionIndex); + + private: + enum class PathEntity : int + { + undefined, + gamepad, + handLeft, + handRight, + head, + keyboard, + mouse, + treadmill }; - class InputManager : public Singleton, public Object + enum class PathIdentifier : int { - public: - struct ActionSet - { - String _name; // Must be lowercase. - String _localizedName; - UINT32 _priority = 0; - bool _xrCompatible = false; - }; - VERUS_TYPEDEFS(ActionSet); - - struct Action - { - Vector _vSubactionPaths; - Vector _vBindingPaths; - String _name; // Must be lowercase. - String _localizedName; - ActionType _type = ActionType::inBoolean; - int _setIndex = 0; - - bool _changedState = false; - bool _booleanValue = false; - float _floatValue = 0; - }; - VERUS_TYPEDEFS(Action); - - struct ActionIndex - { - UINT32 _atom = 0; - int _actionIndex = 0; - - bool _changedState = false; - bool _booleanValue = false; - bool _negativeBoolean = false; - float _floatValue = 0; - }; - VERUS_TYPEDEFS(ActionIndex); - - private: - enum class PathEntity : int - { - undefined, - gamepad, - handLeft, - handRight, - head, - keyboard, - mouse, - treadmill - }; - - enum class PathIdentifier : int - { - undefined, - aim, - buttonA, - buttonB, - buttonEnd, - buttonHome, - buttonSelect, - buttonStart, - buttonX, - buttonY, - diamondDown, - diamondLeft, - diamondRight, - diamondUp, - dpadDown, - dpadLeft, - dpadRight, - dpadUp, - grip, - haptic, - joystick, - miscBack, - miscMenu, - miscMuteMic, - miscPlayPause, - miscView, - miscVolumeDown, - miscVolumeUp, - pedal, - shoulder, - squeeze, - system, - throttle, - thumbrest, - thumbstick, - trackball, - trackpad, - trigger, - wheel - }; - - enum class PathLocation : int - { - undefined, - left, - leftLower, - leftUpper, - lower, - right, - rightLower, - rightUpper, - upper - }; - - enum class PathComponent : int - { - undefined, - click, - force, - pose, - scalarX, - scalarY, - touch, - twist, - value - }; - - static const int s_maxGamepads = 4; - - Vector _vInputFocusStack; - Vector _vActionSets; - Vector _vActions; - Vector _vActionIndex; - Gamepad _gamepads[s_maxGamepads]; - int _axisThreshold = 8192; - bool _kbStatePressed[VERUS_INPUT_MAX_KB]; - bool _kbStateDownEvent[VERUS_INPUT_MAX_KB]; - bool _kbStateUpEvent[VERUS_INPUT_MAX_KB]; - bool _mouseStatePressed[VERUS_INPUT_MAX_MOUSE]; - bool _mouseStateDownEvent[VERUS_INPUT_MAX_MOUSE]; - bool _mouseStateUpEvent[VERUS_INPUT_MAX_MOUSE]; - bool _mouseStateDoubleClick[VERUS_INPUT_MAX_MOUSE]; - - public: - InputManager(); - ~InputManager(); - - void Init(); - void Done(); - - bool HandleEvent(SDL_Event& event); - void HandleInput(); - - int GainFocus(PInputFocus p); - int LoseFocus(PInputFocus p); - - void ResetInputState(); - - bool IsKeyPressed(int scancode) const; - bool IsKeyDownEvent(int scancode) const; - bool IsKeyUpEvent(int scancode) const; - - bool IsMousePressed(int button) const; - bool IsMouseDownEvent(int button) const; - bool IsMouseUpEvent(int button) const; - bool IsMouseDoubleClick(int button) const; - - static float GetMouseScale(); - - int GetGamepadIndex(SDL_JoystickID joystickID) const; - - int CreateActionSet(CSZ name, CSZ localizedName, bool xrCompatible = false, int priority = 0); - int CreateAction(int setIndex, CSZ name, CSZ localizedName, ActionType type, - std::initializer_list ilSubactionPaths, std::initializer_list ilBindingPaths); - - int GetActionSetCount() const { return static_cast(_vActionSets.size()); } - int GetActionCount() const { return static_cast(_vActions.size()); } - - RcActionSet GetActionSet(int index) { return _vActionSets[index]; } - RcAction GetAction(int index) { return _vActions[index]; } - - static UINT32 ToAtom(CSZ path); - static UINT32 ToAtom(int player, PathEntity entity, int inOut, - PathIdentifier identifier, PathLocation location, PathComponent component); - static UINT32 ToAtom(int player, PathEntity entity, int inOut, int scancode); - static bool IsKeyboardAtom(UINT32 atom); - static bool IsMouseAtom(UINT32 atom); - - bool GetActionStateBoolean(int actionIndex, bool* pChangedState = nullptr, int subaction = -1) const; - float GetActionStateFloat(int actionIndex, bool* pChangedState = nullptr, int subaction = -1) const; - bool GetActionStatePose(int actionIndex, Math::RPose pose, int subaction = -1) const; - - static CSZ GetSingletonFailMessage() { return "Make_Input(); // FAIL.\r\n"; } - - private: - void SwitchRelativeMouseMode(int scancode); - - void OnKeyDown(int scancode); - void OnKeyUp(int scancode); - void OnTextInput(wchar_t c); - - void OnMouseMove(int dx, int dy, int x, int y); - void OnMouseDown(int button); - void OnMouseUp(int button); - void OnMouseDoubleClick(int button); - - void UpdateActionStateBoolean(UINT32 atom, bool value); - void UpdateActionStateFloat(UINT32 atom, float value); + undefined, + aim, + buttonA, + buttonB, + buttonEnd, + buttonHome, + buttonSelect, + buttonStart, + buttonX, + buttonY, + diamondDown, + diamondLeft, + diamondRight, + diamondUp, + dpadDown, + dpadLeft, + dpadRight, + dpadUp, + grip, + haptic, + joystick, + miscBack, + miscMenu, + miscMuteMic, + miscPlayPause, + miscView, + miscVolumeDown, + miscVolumeUp, + pedal, + shoulder, + squeeze, + system, + throttle, + thumbrest, + thumbstick, + trackball, + trackpad, + trigger, + wheel }; - VERUS_TYPEDEFS(InputManager); - } + + enum class PathLocation : int + { + undefined, + left, + leftLower, + leftUpper, + lower, + right, + rightLower, + rightUpper, + upper + }; + + enum class PathComponent : int + { + undefined, + click, + force, + pose, + scalarX, + scalarY, + touch, + twist, + value + }; + + static const int s_maxGamepads = 4; + + Vector _vInputFocusStack; + Vector _vActionSets; + Vector _vActions; + Vector _vActionIndex; + Gamepad _gamepads[s_maxGamepads]; + int _axisThreshold = 8192; + bool _kbStatePressed[VERUS_INPUT_MAX_KB]; + bool _kbStateDownEvent[VERUS_INPUT_MAX_KB]; + bool _kbStateUpEvent[VERUS_INPUT_MAX_KB]; + bool _mouseStatePressed[VERUS_INPUT_MAX_MOUSE]; + bool _mouseStateDownEvent[VERUS_INPUT_MAX_MOUSE]; + bool _mouseStateUpEvent[VERUS_INPUT_MAX_MOUSE]; + bool _mouseStateDoubleClick[VERUS_INPUT_MAX_MOUSE]; + + public: + InputManager(); + ~InputManager(); + + void Init(); + void Done(); + + bool HandleEvent(SDL_Event& event); + void HandleInput(); + + int GainFocus(PInputFocus p); + int LoseFocus(PInputFocus p); + + void ResetInputState(); + + bool IsKeyPressed(int scancode) const; + bool IsKeyDownEvent(int scancode) const; + bool IsKeyUpEvent(int scancode) const; + + bool IsMousePressed(int button) const; + bool IsMouseDownEvent(int button) const; + bool IsMouseUpEvent(int button) const; + bool IsMouseDoubleClick(int button) const; + + static float GetMouseScale(); + + int GetGamepadIndex(SDL_JoystickID joystickID) const; + + int CreateActionSet(CSZ name, CSZ localizedName, bool xrCompatible = false, int priority = 0); + int CreateAction(int setIndex, CSZ name, CSZ localizedName, ActionType type, + std::initializer_list ilSubactionPaths, std::initializer_list ilBindingPaths); + + int GetActionSetCount() const { return static_cast(_vActionSets.size()); } + int GetActionCount() const { return static_cast(_vActions.size()); } + + RcActionSet GetActionSet(int index) { return _vActionSets[index]; } + RcAction GetAction(int index) { return _vActions[index]; } + + static UINT32 ToAtom(CSZ path); + static UINT32 ToAtom(int player, PathEntity entity, int inOut, + PathIdentifier identifier, PathLocation location, PathComponent component); + static UINT32 ToAtom(int player, PathEntity entity, int inOut, int scancode); + static bool IsKeyboardAtom(UINT32 atom); + static bool IsMouseAtom(UINT32 atom); + + bool GetActionStateBoolean(int actionIndex, bool* pChangedState = nullptr, int subaction = -1) const; + float GetActionStateFloat(int actionIndex, bool* pChangedState = nullptr, int subaction = -1) const; + bool GetActionStatePose(int actionIndex, Math::RPose pose, int subaction = -1) const; + + static CSZ GetSingletonFailMessage() { return "Make_Input(); // FAIL.\r\n"; } + + private: + void SwitchRelativeMouseMode(int scancode); + + void OnKeyDown(int scancode); + void OnKeyUp(int scancode); + void OnTextInput(wchar_t c); + + void OnMouseMove(int dx, int dy, int x, int y); + void OnMouseDown(int button); + void OnMouseUp(int button); + void OnMouseDoubleClick(int button); + + void UpdateActionStateBoolean(UINT32 atom, bool value); + void UpdateActionStateFloat(UINT32 atom, float value); + }; + VERUS_TYPEDEFS(InputManager); } diff --git a/Verus/src/Math/Bounds.h b/Verus/src/Math/Bounds.h index 82d5758..82ea3fc 100644 --- a/Verus/src/Math/Bounds.h +++ b/Verus/src/Math/Bounds.h @@ -1,69 +1,66 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Math { - namespace Math + class Bounds { - class Bounds - { - Point3 _min; - Point3 _max; + Point3 _min; + Point3 _max; - public: - Bounds(); - Bounds(RcPoint3 mn, RcPoint3 mx); - ~Bounds(); + public: + Bounds(); + Bounds(RcPoint3 mn, RcPoint3 mx); + ~Bounds(); - RcPoint3 GetMin() const { return _min; } - RcPoint3 GetMax() const { return _max; } - bool IsNull() const; + RcPoint3 GetMin() const { return _min; } + RcPoint3 GetMax() const { return _max; } + bool IsNull() const; - Point3 GetCenter() const { return VMath::lerp(0.5f, _min, _max); } - Vector3 GetDimensions() const { return (_max - _min); } - Vector3 GetExtents() const { return (_max - _min) * 0.5f; } + Point3 GetCenter() const { return VMath::lerp(0.5f, _min, _max); } + Vector3 GetDimensions() const { return (_max - _min); } + Vector3 GetExtents() const { return (_max - _min) * 0.5f; } - Bounds& Set(RcPoint3 mn, RcPoint3 mx); - Bounds& Set(float mn, float mx, int axis); - Bounds& Set(const Bounds& that, int axis); + Bounds& Set(RcPoint3 mn, RcPoint3 mx); + Bounds& Set(float mn, float mx, int axis); + Bounds& Set(const Bounds& that, int axis); - Bounds& Reset(); - Bounds& Include(RcPoint3 point); - Bounds& CombineWith(const Bounds& that); - Bounds& MoveBy(RcVector3 offset); + Bounds& Reset(); + Bounds& Include(RcPoint3 point); + Bounds& CombineWith(const Bounds& that); + Bounds& MoveBy(RcVector3 offset); - static Bounds MakeFromCenterExtents(RcPoint3 center, RcVector3 extents); - static Bounds MakeFromOrientedBox(const Bounds& that, RcTransform3 tr); + static Bounds MakeFromCenterExtents(RcPoint3 center, RcVector3 extents); + static Bounds MakeFromOrientedBox(const Bounds& that, RcTransform3 tr); - Bounds& ScaleBy(float scale); - Bounds& FattenBy(float d); + Bounds& ScaleBy(float scale); + Bounds& FattenBy(float d); - bool IsInside(RcPoint3 point) const; - bool IsInside2D(RcPoint3 point) const; - bool IsOverlappingWith(const Bounds& that) const; - bool IsOverlappingWith2D(const Bounds& that, int axis) const; + bool IsInside(RcPoint3 point) const; + bool IsInside2D(RcPoint3 point) const; + bool IsOverlappingWith(const Bounds& that) const; + bool IsOverlappingWith2D(const Bounds& that, int axis) const; - void GetCorners(PPoint3 points) const; - void GetCorners(PMatrix4 m) const; - Sphere GetSphere() const; - Matrix4 GetMatrix() const; - Transform3 GetDrawTransform() const; - Transform3 GetBoxTransform() const; + void GetCorners(PPoint3 points) const; + void GetCorners(PMatrix4 m) const; + Sphere GetSphere() const; + Matrix4 GetMatrix() const; + Transform3 GetDrawTransform() const; + Transform3 GetBoxTransform() const; - Bounds& MirrorY(); - Bounds& Wrap(); + Bounds& MirrorY(); + Bounds& Wrap(); - void GetQuadrant2D(int id, Bounds& that) const; - void GetQuadrant3D(int id, Bounds& that) const; + void GetQuadrant2D(int id, Bounds& that) const; + void GetQuadrant3D(int id, Bounds& that) const; - float GetDiagonal() const; - float GetAverageSize() const; - float GetMaxSide() const; - Vector3 GetExtentsFromOrigin(RcVector3 scale = Vector3::Replicate(1)) const; - float GetMaxExtentFromOrigin(RcVector3 scale = Vector3::Replicate(1)) const; + float GetDiagonal() const; + float GetAverageSize() const; + float GetMaxSide() const; + Vector3 GetExtentsFromOrigin(RcVector3 scale = Vector3::Replicate(1)) const; + float GetMaxExtentFromOrigin(RcVector3 scale = Vector3::Replicate(1)) const; - Bounds& ToUnitBounds(); - }; - VERUS_TYPEDEFS(Bounds); - } + Bounds& ToUnitBounds(); + }; + VERUS_TYPEDEFS(Bounds); } diff --git a/Verus/src/Math/Frustum.h b/Verus/src/Math/Frustum.h index f96df0c..f9129f1 100644 --- a/Verus/src/Math/Frustum.h +++ b/Verus/src/Math/Frustum.h @@ -1,46 +1,43 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Math { - namespace Math + class Frustum { - class Frustum + enum class Name : int { - enum class Name : int - { - left, - right, - bottom, - top, - nearest, - furthest, - count - }; - - Matrix4 _matInvVP = Matrix4::identity(); - Plane _planes[static_cast(Name::count)]; - Point3 _corners[10]; - - public: - Frustum(); - ~Frustum(); - - static Frustum MakeFromMatrix(RcMatrix4 matVP); - Frustum& FromMatrix(RcMatrix4 matVP); - Relation ContainsSphere(RcSphere sphere) const; - Relation ContainsAabb(RcBounds bounds) const; - void Draw(); - - RcPoint3 GetCorner(int index) const { return _corners[index]; } - RcPoint3 GetZNearPosition() const { return _corners[8]; } - RcPoint3 GetZFarPosition() const { return _corners[9]; } - - Bounds GetBounds(RcTransform3 tr, PPoint3 pFocusedCenterPos = nullptr) const; - - Frustum& SetNearPlane(RcPoint3 eye, RcVector3 front, float zNear); - Frustum& SetFarPlane(RcPoint3 eye, RcVector3 front, float zFar); + left, + right, + bottom, + top, + nearest, + furthest, + count }; - VERUS_TYPEDEFS(Frustum); - } + + Matrix4 _matInvVP = Matrix4::identity(); + Plane _planes[static_cast(Name::count)]; + Point3 _corners[10]; + + public: + Frustum(); + ~Frustum(); + + static Frustum MakeFromMatrix(RcMatrix4 matVP); + Frustum& FromMatrix(RcMatrix4 matVP); + Relation ContainsSphere(RcSphere sphere) const; + Relation ContainsAabb(RcBounds bounds) const; + void Draw(); + + RcPoint3 GetCorner(int index) const { return _corners[index]; } + RcPoint3 GetZNearPosition() const { return _corners[8]; } + RcPoint3 GetZFarPosition() const { return _corners[9]; } + + Bounds GetBounds(RcTransform3 tr, PPoint3 pFocusedCenterPos = nullptr) const; + + Frustum& SetNearPlane(RcPoint3 eye, RcVector3 front, float zNear); + Frustum& SetFarPlane(RcPoint3 eye, RcVector3 front, float zFar); + }; + VERUS_TYPEDEFS(Frustum); } diff --git a/Verus/src/Math/Math.cpp b/Verus/src/Math/Math.cpp index 791d9a8..70b707c 100644 --- a/Verus/src/Math/Math.cpp +++ b/Verus/src/Math/Math.cpp @@ -95,9 +95,7 @@ int Math::LowestBit(int x) bool Math::IsNaN(float x) { - // 'isnan' : is not a member of 'std' :( - volatile float y = x; - return y != y; + return std::isnan(x); } float Math::ToRadians(float deg) @@ -144,47 +142,49 @@ float Math::ApplyEasing(Easing easing, float x) { switch (easing) { - case Easing::none: return x; + using enum Easing; - case Easing::sineIn: return glm::sineEaseIn(x); - case Easing::sineOut: return glm::sineEaseOut(x); - case Easing::sineInOut: return glm::sineEaseInOut(x); + case none: return x; - case Easing::quadIn: return glm::quadraticEaseIn(x); - case Easing::quadOut: return glm::quadraticEaseOut(x); - case Easing::quadInOut: return glm::quadraticEaseInOut(x); + case sineIn: return glm::sineEaseIn(x); + case sineOut: return glm::sineEaseOut(x); + case sineInOut: return glm::sineEaseInOut(x); - case Easing::cubicIn: return glm::cubicEaseIn(x); - case Easing::cubicOut: return glm::cubicEaseOut(x); - case Easing::cubicInOut: return glm::cubicEaseInOut(x); + case quadIn: return glm::quadraticEaseIn(x); + case quadOut: return glm::quadraticEaseOut(x); + case quadInOut: return glm::quadraticEaseInOut(x); - case Easing::quartIn: return glm::quarticEaseIn(x); - case Easing::quartOut: return glm::quarticEaseOut(x); - case Easing::quartInOut: return glm::quarticEaseInOut(x); + case cubicIn: return glm::cubicEaseIn(x); + case cubicOut: return glm::cubicEaseOut(x); + case cubicInOut: return glm::cubicEaseInOut(x); - case Easing::quintIn: return glm::quinticEaseIn(x); - case Easing::quintOut: return glm::quinticEaseOut(x); - case Easing::quintInOut: return glm::quinticEaseInOut(x); + case quartIn: return glm::quarticEaseIn(x); + case quartOut: return glm::quarticEaseOut(x); + case quartInOut: return glm::quarticEaseInOut(x); - case Easing::expoIn: return glm::exponentialEaseIn(x); - case Easing::expoOut: return glm::exponentialEaseOut(x); - case Easing::expoInOut: return glm::exponentialEaseInOut(x); + case quintIn: return glm::quinticEaseIn(x); + case quintOut: return glm::quinticEaseOut(x); + case quintInOut: return glm::quinticEaseInOut(x); - case Easing::circIn: return glm::circularEaseIn(x); - case Easing::circOut: return glm::circularEaseOut(x); - case Easing::circInOut: return glm::circularEaseInOut(x); + case expoIn: return glm::exponentialEaseIn(x); + case expoOut: return glm::exponentialEaseOut(x); + case expoInOut: return glm::exponentialEaseInOut(x); - case Easing::backIn: return glm::backEaseIn(x); - case Easing::backOut: return glm::backEaseOut(x); - case Easing::backInOut: return glm::backEaseInOut(x); + case circIn: return glm::circularEaseIn(x); + case circOut: return glm::circularEaseOut(x); + case circInOut: return glm::circularEaseInOut(x); - case Easing::elasticIn: return glm::elasticEaseIn(x); - case Easing::elasticOut: return glm::elasticEaseOut(x); - case Easing::elasticInOut: return glm::elasticEaseInOut(x); + case backIn: return glm::backEaseIn(x); + case backOut: return glm::backEaseOut(x); + case backInOut: return glm::backEaseInOut(x); - case Easing::bounceIn: return glm::bounceEaseIn(x); - case Easing::bounceOut: return glm::bounceEaseOut(x); - case Easing::bounceInOut: return glm::bounceEaseInOut(x); + case elasticIn: return glm::elasticEaseIn(x); + case elasticOut: return glm::elasticEaseOut(x); + case elasticInOut: return glm::elasticEaseInOut(x); + + case bounceIn: return glm::bounceEaseIn(x); + case bounceOut: return glm::bounceEaseOut(x); + case bounceInOut: return glm::bounceEaseInOut(x); } VERUS_RT_FAIL("Unknown easing."); return x; diff --git a/Verus/src/Math/Math.h b/Verus/src/Math/Math.h index f86d83a..0f4ec02 100644 --- a/Verus/src/Math/Math.h +++ b/Verus/src/Math/Math.h @@ -87,90 +87,87 @@ namespace verus #include "Quadtree.h" #include "Octree.h" -namespace verus +namespace verus::Math { - namespace Math + struct Pose { - struct Pose - { - Quat _orientation = Quat(0); - Point3 _position = Point3(0); + Quat _orientation = Quat(0); + Point3 _position = Point3(0); - Pose() {} - Pose(const XrPosef& that) : _orientation(that.orientation), _position(that.position) {} - }; - VERUS_TYPEDEFS(Pose); - - // Bits: - bool IsPowerOfTwo(int x); - UINT32 NextPowerOfTwo(UINT32 x); - int HighestBit(int x); - int LowestBit(int x); - bool IsNaN(float x); - - // Angles: - float ToRadians(float deg); - float ToDegrees(float rad); - float WrapAngle(float rad); - - // Interpolation, splines: - float Lerp(float a, float b, float t); - float LerpAngles(float a, float b, float t); - float SmoothStep(float a, float b, float t); - float ApplyEasing(Easing easing, float x); - Easing EasingFromString(CSZ s); - CSZ EasingToString(Easing easing); - Quat NLerp(float t, RcQuat qA, RcQuat qB); - - // Barycentric: - Vector3 Barycentric(RcPoint3 a, RcPoint3 b, RcPoint3 c, RcPoint3 p); - bool IsPointInsideBarycentric(RcVector3 bc); - template - T BarycentricInterpolation(const T& a, const T& b, const T& c, RcVector3 bc) - { - const T ab = b - a; - const T ac = c - a; - return a + ab * static_cast(bc.getX()) + ac * static_cast(bc.getY()); - } - - // Shapes: - Vector3 TriangleNormal(RcPoint3 a, RcPoint3 b, RcPoint3 c); - float TriangleArea( - const glm::vec3& a, - const glm::vec3& b, - const glm::vec3& c); - bool IsPointInsideTriangle( - const glm::vec2& a, - const glm::vec2& b, - const glm::vec2& c, - const glm::vec2& p); - - // Geometry: - int StripGridIndexCount(int polyCountWidth, int polyCountHeight); - void CreateStripGrid(int polyCountWidth, int polyCountHeight, Vector& vIndices); - void CreateListGrid(int polyCountWidth, int polyCountHeight, Vector& vIndices); - bool CheckIndexBuffer(Vector& vIndices, int maxIndex); - - // Scene: - Transform3 BoundsDrawMatrix(RcPoint3 mn, RcPoint3 mx); - Transform3 BoundsBoxMatrix(RcPoint3 mn, RcPoint3 mx); - float ComputeOnePixelDistance(float objectSize, float viewportHeightInPixels = 135, float fovY = VERUS_PI / 4); - float ComputeDistToMipScale(float texHeight, float viewportHeightInPixels, float objectSize, float fovY); - void Quadrant(const int** ppSrcMinMax, int** ppDestMinMax, int half, int id); - - int ComputeMipLevels(int w, int h, int d = 1); - - BYTE CombineOcclusion(BYTE a, BYTE b); - - // Matrices: - Transform3 QuadMatrix(float x = 0, float y = 0, float w = 1, float h = 1); - Transform3 ToUVMatrix(float zOffset = 0, RcVector4 texSize = Vector4(0), PcVector4 pTileSize = nullptr, float uOffset = 0, float vOffset = 0); - - float Reduce(float val, float reduction); - - Point3 ClosestPointOnSegment(RcPoint3 segA, RcPoint3 segB, RcPoint3 point); - float SegmentToPointDistance(RcPoint3 segA, RcPoint3 segB, RcPoint3 point); - - void Test(); + Pose() {} + Pose(const XrPosef& that) : _orientation(that.orientation), _position(that.position) {} }; + VERUS_TYPEDEFS(Pose); + + // Bits: + bool IsPowerOfTwo(int x); + UINT32 NextPowerOfTwo(UINT32 x); + int HighestBit(int x); + int LowestBit(int x); + bool IsNaN(float x); + + // Angles: + float ToRadians(float deg); + float ToDegrees(float rad); + float WrapAngle(float rad); + + // Interpolation, splines: + float Lerp(float a, float b, float t); + float LerpAngles(float a, float b, float t); + float SmoothStep(float a, float b, float t); + float ApplyEasing(Easing easing, float x); + Easing EasingFromString(CSZ s); + CSZ EasingToString(Easing easing); + Quat NLerp(float t, RcQuat qA, RcQuat qB); + + // Barycentric: + Vector3 Barycentric(RcPoint3 a, RcPoint3 b, RcPoint3 c, RcPoint3 p); + bool IsPointInsideBarycentric(RcVector3 bc); + template + T BarycentricInterpolation(const T& a, const T& b, const T& c, RcVector3 bc) + { + const T ab = b - a; + const T ac = c - a; + return a + ab * static_cast(bc.getX()) + ac * static_cast(bc.getY()); + } + + // Shapes: + Vector3 TriangleNormal(RcPoint3 a, RcPoint3 b, RcPoint3 c); + float TriangleArea( + const glm::vec3& a, + const glm::vec3& b, + const glm::vec3& c); + bool IsPointInsideTriangle( + const glm::vec2& a, + const glm::vec2& b, + const glm::vec2& c, + const glm::vec2& p); + + // Geometry: + int StripGridIndexCount(int polyCountWidth, int polyCountHeight); + void CreateStripGrid(int polyCountWidth, int polyCountHeight, Vector& vIndices); + void CreateListGrid(int polyCountWidth, int polyCountHeight, Vector& vIndices); + bool CheckIndexBuffer(Vector& vIndices, int maxIndex); + + // Scene: + Transform3 BoundsDrawMatrix(RcPoint3 mn, RcPoint3 mx); + Transform3 BoundsBoxMatrix(RcPoint3 mn, RcPoint3 mx); + float ComputeOnePixelDistance(float objectSize, float viewportHeightInPixels = 135, float fovY = VERUS_PI / 4); + float ComputeDistToMipScale(float texHeight, float viewportHeightInPixels, float objectSize, float fovY); + void Quadrant(const int** ppSrcMinMax, int** ppDestMinMax, int half, int id); + + int ComputeMipLevels(int w, int h, int d = 1); + + BYTE CombineOcclusion(BYTE a, BYTE b); + + // Matrices: + Transform3 QuadMatrix(float x = 0, float y = 0, float w = 1, float h = 1); + Transform3 ToUVMatrix(float zOffset = 0, RcVector4 texSize = Vector4(0), PcVector4 pTileSize = nullptr, float uOffset = 0, float vOffset = 0); + + float Reduce(float val, float reduction); + + Point3 ClosestPointOnSegment(RcPoint3 segA, RcPoint3 segB, RcPoint3 point); + float SegmentToPointDistance(RcPoint3 segA, RcPoint3 segB, RcPoint3 point); + + void Test(); } diff --git a/Verus/src/Math/Octree.h b/Verus/src/Math/Octree.h index ceab1e5..4e47980 100644 --- a/Verus/src/Math/Octree.h +++ b/Verus/src/Math/Octree.h @@ -1,104 +1,101 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Math { - namespace Math + class OctreeDelegate { - class OctreeDelegate + public: + virtual Continue Octree_OnElementDetected(void* pToken, void* pUser) = 0; + }; + VERUS_TYPEDEFS(OctreeDelegate); + + class Octree : public Object + { + public: + class Element { public: - virtual Continue Octree_OnElementDetected(void* pToken, void* pUser) = 0; + Bounds _bounds; + Sphere _sphere; + void* _pToken = nullptr; + + Element() {} + Element(RcBounds bounds, void* pToken) : + _bounds(bounds), _pToken(pToken) + { + _sphere = _bounds.GetSphere(); + } }; - VERUS_TYPEDEFS(OctreeDelegate); + VERUS_TYPEDEFS(Element); - class Octree : public Object + class Result { public: - class Element - { - public: - Bounds _bounds; - Sphere _sphere; - void* _pToken = nullptr; - - Element() {} - Element(RcBounds bounds, void* pToken) : - _bounds(bounds), _pToken(pToken) - { - _sphere = _bounds.GetSphere(); - } - }; - VERUS_TYPEDEFS(Element); - - class Result - { - public: - void* _pLastFoundToken = nullptr; - int _testCount = 0; - int _passedTestCount = 0; - bool _depth = false; - }; - VERUS_TYPEDEFS(Result); - - private: - class Node : public AllocatorAware - { - Bounds _bounds; - Sphere _sphere; - Vector _vElements; - - public: - Node(); - ~Node(); - - static int GetChildIndex(int currentNode, int child); - static bool HasChildren(int currentNode, int nodeCount); - - RcSphere GetSphere() const { return _sphere; } - RcBounds GetBounds() const { return _bounds; } - void SetBounds(RcBounds b) { _bounds = b; _sphere = b.GetSphere(); } - - void BindElement(RcElement element); - void UnbindElement(void* pToken); - void UpdateDynamicElement(RcElement element); - - int GetElementCount() const { return Utils::Cast32(_vElements.size()); } - RcElement GetElementAt(int i) const { return _vElements[i]; } - }; - VERUS_TYPEDEFS(Node); + void* _pLastFoundToken = nullptr; + int _testCount = 0; + int _passedTestCount = 0; + bool _depth = false; + }; + VERUS_TYPEDEFS(Result); + private: + class Node : public AllocatorAware + { Bounds _bounds; - Vector3 _limit = Vector3(0); - Vector _vNodes; - POctreeDelegate _pDelegate = nullptr; - Result _defaultResult; - int _skipTestNode = -1; + Sphere _sphere; + Vector _vElements; public: - Octree(); - ~Octree(); + Node(); + ~Node(); - void Init(RcBounds bounds, RcVector3 limit); - void Done(); - - POctreeDelegate SetDelegate(POctreeDelegate p) { return Utils::Swap(_pDelegate, p); } - - VERUS_P(void Build(int currentNode = 0, int depth = 0)); - - bool BindElement(RcElement element, bool forceRoot = false, int currentNode = 0); - void UnbindElement(void* pToken); - void UpdateDynamicBounds(RcElement element); - VERUS_P(bool MustBind(int currentNode, RcBounds bounds) const); - - Continue DetectElements(RcFrustum frustum, PResult pResult = nullptr, int currentNode = 0, void* pUser = nullptr); - Continue DetectElements(Math::RcSphere sphere, PResult pResult = nullptr, int currentNode = 0, void* pUser = nullptr); - Continue DetectElements(RcPoint3 point, PResult pResult = nullptr, int currentNode = 0, void* pUser = nullptr); - - VERUS_P(static void RemapChildIndices(RcPoint3 point, RcPoint3 center, BYTE childIndices[8])); + static int GetChildIndex(int currentNode, int child); + static bool HasChildren(int currentNode, int nodeCount); + RcSphere GetSphere() const { return _sphere; } RcBounds GetBounds() const { return _bounds; } + void SetBounds(RcBounds b) { _bounds = b; _sphere = b.GetSphere(); } + + void BindElement(RcElement element); + void UnbindElement(void* pToken); + void UpdateDynamicElement(RcElement element); + + int GetElementCount() const { return Utils::Cast32(_vElements.size()); } + RcElement GetElementAt(int i) const { return _vElements[i]; } }; - VERUS_TYPEDEFS(Octree); - } + VERUS_TYPEDEFS(Node); + + Bounds _bounds; + Vector3 _limit = Vector3(0); + Vector _vNodes; + POctreeDelegate _pDelegate = nullptr; + Result _defaultResult; + int _skipTestNode = -1; + + public: + Octree(); + ~Octree(); + + void Init(RcBounds bounds, RcVector3 limit); + void Done(); + + POctreeDelegate SetDelegate(POctreeDelegate p) { return Utils::Swap(_pDelegate, p); } + + VERUS_P(void Build(int currentNode = 0, int depth = 0)); + + bool BindElement(RcElement element, bool forceRoot = false, int currentNode = 0); + void UnbindElement(void* pToken); + void UpdateDynamicBounds(RcElement element); + VERUS_P(bool MustBind(int currentNode, RcBounds bounds) const); + + Continue DetectElements(RcFrustum frustum, PResult pResult = nullptr, int currentNode = 0, void* pUser = nullptr); + Continue DetectElements(Math::RcSphere sphere, PResult pResult = nullptr, int currentNode = 0, void* pUser = nullptr); + Continue DetectElements(RcPoint3 point, PResult pResult = nullptr, int currentNode = 0, void* pUser = nullptr); + + VERUS_P(static void RemapChildIndices(RcPoint3 point, RcPoint3 center, BYTE childIndices[8])); + + RcBounds GetBounds() const { return _bounds; } + }; + VERUS_TYPEDEFS(Octree); } diff --git a/Verus/src/Math/Plane.h b/Verus/src/Math/Plane.h index 155cb07..cf053ac 100644 --- a/Verus/src/Math/Plane.h +++ b/Verus/src/Math/Plane.h @@ -1,27 +1,24 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Math { - namespace Math + class Plane : public Vector4 { - class Plane : public Vector4 - { - public: - Plane(); - Plane(RcVector4 that); - Plane(RcVector3 normal, float d); - Plane(RcVector3 normal, RcPoint3 point); - Plane(RcPoint3 pointA, RcPoint3 pointB, RcPoint3 pointC); - Plane& operator=(RcVector4 that) { Vector4::operator=(that); return *this; } - ~Plane(); + public: + Plane(); + Plane(RcVector4 that); + Plane(RcVector3 normal, float d); + Plane(RcVector3 normal, RcPoint3 point); + Plane(RcPoint3 pointA, RcPoint3 pointB, RcPoint3 pointC); + Plane& operator=(RcVector4 that) { Vector4::operator=(that); return *this; } + ~Plane(); - float DistanceTo(RcPoint3 point) const; + float DistanceTo(RcPoint3 point) const; - Plane& Normalize(); + Plane& Normalize(); - bool IntersectSegment(RcPoint3 pointA, RcPoint3 pointB, RPoint3 point, float* t = nullptr); - }; - VERUS_TYPEDEFS(Plane); - } + bool IntersectSegment(RcPoint3 pointA, RcPoint3 pointB, RPoint3 point, float* t = nullptr); + }; + VERUS_TYPEDEFS(Plane); } diff --git a/Verus/src/Math/Quadtree.h b/Verus/src/Math/Quadtree.h index 4309ce1..a45c8a2 100644 --- a/Verus/src/Math/Quadtree.h +++ b/Verus/src/Math/Quadtree.h @@ -1,94 +1,91 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Math { - namespace Math + class QuadtreeDelegate { - class QuadtreeDelegate + public: + virtual Continue Quadtree_OnElementDetected(void* pToken, void* pUser) = 0; + }; + VERUS_TYPEDEFS(QuadtreeDelegate); + + class Quadtree : public Object + { + public: + class Element { public: - virtual Continue Quadtree_OnElementDetected(void* pToken, void* pUser) = 0; + Bounds _bounds; + void* _pToken = nullptr; + + Element() {} + Element(RcBounds bounds, void* pToken) : + _bounds(bounds), _pToken(pToken) {} }; - VERUS_TYPEDEFS(QuadtreeDelegate); + VERUS_TYPEDEFS(Element); - class Quadtree : public Object + class Result { public: - class Element - { - public: - Bounds _bounds; - void* _pToken = nullptr; + void* _pLastFoundToken = nullptr; + int _testCount = 0; + int _passedTestCount = 0; + }; + VERUS_TYPEDEFS(Result); - Element() {} - Element(RcBounds bounds, void* pToken) : - _bounds(bounds), _pToken(pToken) {} - }; - VERUS_TYPEDEFS(Element); - - class Result - { - public: - void* _pLastFoundToken = nullptr; - int _testCount = 0; - int _passedTestCount = 0; - }; - VERUS_TYPEDEFS(Result); - - private: - class Node : public AllocatorAware - { - Bounds _bounds; - Vector _vElements; - - public: - Node(); - ~Node(); - - static int GetChildIndex(int currentNode, int child); - static bool HasChildren(int currentNode, int nodeCount); - - RcBounds GetBounds() const { return _bounds; } - void SetBounds(RcBounds b) { _bounds = b; } - - void BindElement(RcElement element); - void UnbindElement(void* pToken); - void UpdateDynamicElement(RcElement element); - - int GetElementCount() const { return Utils::Cast32(_vElements.size()); } - RcElement GetElementAt(int i) const { return _vElements[i]; } - }; - VERUS_TYPEDEFS(Node); - - Bounds _bounds; - Vector3 _limit = Vector3(0); - Vector _vNodes; - PQuadtreeDelegate _pDelegate = nullptr; - Result _defaultResult; + private: + class Node : public AllocatorAware + { + Bounds _bounds; + Vector _vElements; public: - Quadtree(); - ~Quadtree(); + Node(); + ~Node(); - void Init(RcBounds bounds, RcVector3 limit); - void Done(); - - PQuadtreeDelegate SetDelegate(PQuadtreeDelegate p) { return Utils::Swap(_pDelegate, p); } - - VERUS_P(void Build(int currentNode = 0, int depth = 0)); - - bool BindElement(RcElement element, bool forceRoot = false, int currentNode = 0); - void UnbindElement(void* pToken); - void UpdateDynamicBounds(RcElement element); - VERUS_P(bool MustBind(int currentNode, RcBounds bounds) const); - - Continue DetectElements(RcPoint3 point, PResult pResult = nullptr, int currentNode = 0, void* pUser = nullptr); - - VERUS_P(static void RemapChildIndices(RcPoint3 point, RcPoint3 center, BYTE childIndices[4])); + static int GetChildIndex(int currentNode, int child); + static bool HasChildren(int currentNode, int nodeCount); RcBounds GetBounds() const { return _bounds; } + void SetBounds(RcBounds b) { _bounds = b; } + + void BindElement(RcElement element); + void UnbindElement(void* pToken); + void UpdateDynamicElement(RcElement element); + + int GetElementCount() const { return Utils::Cast32(_vElements.size()); } + RcElement GetElementAt(int i) const { return _vElements[i]; } }; - VERUS_TYPEDEFS(Quadtree); - } + VERUS_TYPEDEFS(Node); + + Bounds _bounds; + Vector3 _limit = Vector3(0); + Vector _vNodes; + PQuadtreeDelegate _pDelegate = nullptr; + Result _defaultResult; + + public: + Quadtree(); + ~Quadtree(); + + void Init(RcBounds bounds, RcVector3 limit); + void Done(); + + PQuadtreeDelegate SetDelegate(PQuadtreeDelegate p) { return Utils::Swap(_pDelegate, p); } + + VERUS_P(void Build(int currentNode = 0, int depth = 0)); + + bool BindElement(RcElement element, bool forceRoot = false, int currentNode = 0); + void UnbindElement(void* pToken); + void UpdateDynamicBounds(RcElement element); + VERUS_P(bool MustBind(int currentNode, RcBounds bounds) const); + + Continue DetectElements(RcPoint3 point, PResult pResult = nullptr, int currentNode = 0, void* pUser = nullptr); + + VERUS_P(static void RemapChildIndices(RcPoint3 point, RcPoint3 center, BYTE childIndices[4])); + + RcBounds GetBounds() const { return _bounds; } + }; + VERUS_TYPEDEFS(Quadtree); } diff --git a/Verus/src/Math/QuadtreeIntegral.h b/Verus/src/Math/QuadtreeIntegral.h index e3d2548..8280ffe 100644 --- a/Verus/src/Math/QuadtreeIntegral.h +++ b/Verus/src/Math/QuadtreeIntegral.h @@ -1,82 +1,79 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Math { - namespace Math + class QuadtreeIntegralDelegate { - class QuadtreeIntegralDelegate + public: + virtual void QuadtreeIntegral_OnElementDetected(const short ij[2], RcPoint3 center) = 0; + virtual void QuadtreeIntegral_GetHeights(const short ij[2], float height[2]) = 0; + }; + VERUS_TYPEDEFS(QuadtreeIntegralDelegate); + + class QuadtreeIntegral : public Object + { + class Node { - public: - virtual void QuadtreeIntegral_OnElementDetected(const short ij[2], RcPoint3 center) = 0; - virtual void QuadtreeIntegral_GetHeights(const short ij[2], float height[2]) = 0; - }; - VERUS_TYPEDEFS(QuadtreeIntegralDelegate); - - class QuadtreeIntegral : public Object - { - class Node - { - Bounds _bounds; - Sphere _sphere; - short _ijOffset[2]; - short _xzMin[2]; - short _xzMax[2]; - - public: - Node(); - ~Node(); - - static int GetChildIndex(int currentNode, int child); - static bool HasChildren(int currentNode, int nodeCount); - - const short* GetOffsetIJ() const { return _ijOffset; } - int GetWidth() const { return _xzMax[0] - _xzMin[0]; } - short* GetSetMin() { return _xzMin; } - short* GetSetMax() { return _xzMax; } - - RcBounds GetBounds() const { return _bounds; } - Node& SetBounds(RcBounds bounds) { _bounds = bounds; return *this; } - RcSphere GetSphere() const { return _sphere; } - Node& SetSphere(RcSphere sphere) { _sphere = sphere; return *this; } - - void PrepareBounds2D(); - void PrepareMinMax(int mapHalf); - void PrepareOffsetIJ(int mapHalf); - }; - VERUS_TYPEDEFS(Node); - - Vector _vNodes; - PQuadtreeIntegralDelegate _pDelegate = nullptr; - float _fattenBy = 0.5f; - int _nodeCount = 0; - int _testCount = 0; - int _passedTestCount = 0; - int _skipTestNode = -1; - int _mapSide = 0; - int _limit = 0; - int _maxDepth = 0; - bool _distCoarseMode = false; + Bounds _bounds; + Sphere _sphere; + short _ijOffset[2]; + short _xzMin[2]; + short _xzMax[2]; public: - QuadtreeIntegral(); - ~QuadtreeIntegral(); + Node(); + ~Node(); - void Init(int mapSide, int limit, PQuadtreeIntegralDelegate p, float fattenBy = 0.5f); - void Done(); + static int GetChildIndex(int currentNode, int child); + static bool HasChildren(int currentNode, int nodeCount); - PQuadtreeIntegralDelegate SetDelegate(PQuadtreeIntegralDelegate p) { return Utils::Swap(_pDelegate, p); } + const short* GetOffsetIJ() const { return _ijOffset; } + int GetWidth() const { return _xzMax[0] - _xzMin[0]; } + short* GetSetMin() { return _xzMin; } + short* GetSetMax() { return _xzMax; } - VERUS_P(void AllocNodes()); - VERUS_P(void InitNodes(int currentNode = 0, int depth = 0)); + RcBounds GetBounds() const { return _bounds; } + Node& SetBounds(RcBounds bounds) { _bounds = bounds; return *this; } + RcSphere GetSphere() const { return _sphere; } + Node& SetSphere(RcSphere sphere) { _sphere = sphere; return *this; } - void DetectElements(int currentNode = 0, int depth = 0); - - int GetTestCount() const { return _testCount; } - int GetPassedTestCount() const { return _passedTestCount; } - - void SetDistCoarseMode(bool b) { _distCoarseMode = b; } + void PrepareBounds2D(); + void PrepareMinMax(int mapHalf); + void PrepareOffsetIJ(int mapHalf); }; - VERUS_TYPEDEFS(QuadtreeIntegral); - } + VERUS_TYPEDEFS(Node); + + Vector _vNodes; + PQuadtreeIntegralDelegate _pDelegate = nullptr; + float _fattenBy = 0.5f; + int _nodeCount = 0; + int _testCount = 0; + int _passedTestCount = 0; + int _skipTestNode = -1; + int _mapSide = 0; + int _limit = 0; + int _maxDepth = 0; + bool _distCoarseMode = false; + + public: + QuadtreeIntegral(); + ~QuadtreeIntegral(); + + void Init(int mapSide, int limit, PQuadtreeIntegralDelegate p, float fattenBy = 0.5f); + void Done(); + + PQuadtreeIntegralDelegate SetDelegate(PQuadtreeIntegralDelegate p) { return Utils::Swap(_pDelegate, p); } + + VERUS_P(void AllocNodes()); + VERUS_P(void InitNodes(int currentNode = 0, int depth = 0)); + + void DetectElements(int currentNode = 0, int depth = 0); + + int GetTestCount() const { return _testCount; } + int GetPassedTestCount() const { return _passedTestCount; } + + void SetDistCoarseMode(bool b) { _distCoarseMode = b; } + }; + VERUS_TYPEDEFS(QuadtreeIntegral); } diff --git a/Verus/src/Math/Sphere.h b/Verus/src/Math/Sphere.h index 0c85147..4ac2641 100644 --- a/Verus/src/Math/Sphere.h +++ b/Verus/src/Math/Sphere.h @@ -1,30 +1,27 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Math { - namespace Math + class Sphere { - class Sphere - { - Vector4 _center_radius; + Vector4 _center_radius; - public: - Sphere() {} - Sphere(RcPoint3 center, float r) : _center_radius(Vector3(center), r) {} + public: + Sphere() {} + Sphere(RcPoint3 center, float r) : _center_radius(Vector3(center), r) {} - Point3 GetCenter() const { return _center_radius.getXYZ(); } - float GetRadius() const { return _center_radius.getW(); } - float GetRadiusSq() const { return _center_radius.getW() * _center_radius.getW(); } + Point3 GetCenter() const { return _center_radius.getXYZ(); } + float GetRadius() const { return _center_radius.getW(); } + float GetRadiusSq() const { return _center_radius.getW() * _center_radius.getW(); } - Sphere& SetCenter(RcPoint3 center) { _center_radius.setXYZ(Vector3(center)); return *this; } - Sphere& SetRadius(float r) { _center_radius.setW(r); return *this; } + Sphere& SetCenter(RcPoint3 center) { _center_radius.setXYZ(Vector3(center)); return *this; } + Sphere& SetRadius(float r) { _center_radius.setW(r); return *this; } - bool IsInside(RcPoint3 point) const; - bool IsOverlappingWith(const Sphere& that) const; + bool IsInside(RcPoint3 point) const; + bool IsOverlappingWith(const Sphere& that) const; - static void EvenlyDistPoints(int count, Vector& vPoints); - }; - VERUS_TYPEDEFS(Sphere); - } + static void EvenlyDistPoints(int count, Vector& vPoints); + }; + VERUS_TYPEDEFS(Sphere); } diff --git a/Verus/src/Math/TangentSpaceTools.h b/Verus/src/Math/TangentSpaceTools.h index 2c9758f..e3aebc5 100644 --- a/Verus/src/Math/TangentSpaceTools.h +++ b/Verus/src/Math/TangentSpaceTools.h @@ -1,28 +1,25 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Math { - namespace Math + class TangentSpaceTools { - class TangentSpaceTools - { - public: - static void RecalculateNormals( - const Vector& vIndices, - const Vector& vPositions, - Vector& vNormals, - float areaBasedNormals); + public: + static void RecalculateNormals( + const Vector& vIndices, + const Vector& vPositions, + Vector& vNormals, + float areaBasedNormals); - static void RecalculateTangentSpace( - const Vector& vIndices, - const Vector& vPositions, - const Vector& vNormals, - const Vector& vTexCoords, - Vector& vTan, - Vector& vBin, - bool useMikkTSpace = true); - }; - VERUS_TYPEDEFS(TangentSpaceTools); - } + static void RecalculateTangentSpace( + const Vector& vIndices, + const Vector& vPositions, + const Vector& vNormals, + const Vector& vTexCoords, + Vector& vTan, + Vector& vBin, + bool useMikkTSpace = true); + }; + VERUS_TYPEDEFS(TangentSpaceTools); } diff --git a/Verus/src/Net/Addr.h b/Verus/src/Net/Addr.h index 3624d80..bbd4652 100644 --- a/Verus/src/Net/Addr.h +++ b/Verus/src/Net/Addr.h @@ -1,39 +1,36 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Net { - namespace Net + // Holds IP address and port. + class Addr { - // Holds IP address and port. - class Addr + public: + union { - public: - union - { - UINT32 _addr = 0; - BYTE _a[4]; - }; - UINT16 _port = 0; - - Addr() = default; - Addr(const sockaddr_in& sa); - Addr(CSZ addr, int port); - - bool operator==(const Addr& that) const; - - // Returns localhost address 127.0.0.1. - static Addr Localhost(int port = 0); - - bool IsNull() const { return !_addr || !_port; } - bool IsLocalhost() const; - - // Accepts IP:Port or URL, which is resolved using getaddrinfo(). - void FromString(CSZ addr); - String ToString(bool addPort = false) const; - - sockaddr_in ToSockAddr() const; + UINT32 _addr = 0; + BYTE _a[4]; }; - VERUS_TYPEDEFS(Addr); - } + UINT16 _port = 0; + + Addr() = default; + Addr(const sockaddr_in& sa); + Addr(CSZ addr, int port); + + bool operator==(const Addr& that) const; + + // Returns localhost address 127.0.0.1. + static Addr Localhost(int port = 0); + + bool IsNull() const { return !_addr || !_port; } + bool IsLocalhost() const; + + // Accepts IP:Port or URL, which is resolved using getaddrinfo(). + void FromString(CSZ addr); + String ToString(bool addPort = false) const; + + sockaddr_in ToSockAddr() const; + }; + VERUS_TYPEDEFS(Addr); } diff --git a/Verus/src/Net/HttpFile.h b/Verus/src/Net/HttpFile.h index 7c5f2b4..9b47645 100644 --- a/Verus/src/Net/HttpFile.h +++ b/Verus/src/Net/HttpFile.h @@ -1,48 +1,45 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Net { - namespace Net + // Provides ability to read files from the internet using HTTP. + class HttpFile : public IO::Stream { - // Provides ability to read files from the internet using HTTP. - class HttpFile : public IO::Stream - { - static const int s_httpPort = 80; - static const int s_schemeLength = 7; - static const int s_maxContentLength = 1024 * 1024; + static const int s_httpPort = 80; + static const int s_schemeLength = 7; + static const int s_maxContentLength = 1024 * 1024; - typedef Map TMapHeader; + typedef Map TMapHeader; - String _url; - Vector _vData; - Socket _socket; - std::thread _thread; - TMapHeader _mapHeader; - BYTE _buffer[200]; - INT64 _offset = 0; - INT64 _size = 0; - int _contentPart = 0; - std::atomic_bool _ready; - bool _nullTerm = false; + String _url; + Vector _vData; + Socket _socket; + std::thread _thread; + TMapHeader _mapHeader; + BYTE _buffer[200]; + INT64 _offset = 0; + INT64 _size = 0; + int _contentPart = 0; + std::atomic_bool _ready; + bool _nullTerm = false; - public: - HttpFile(); - ~HttpFile(); + public: + HttpFile(); + ~HttpFile(); - bool Open(CSZ url); - void Close(); + bool Open(CSZ url); + void Close(); - virtual INT64 Read(void* p, INT64 size) override; - virtual INT64 Write(const void* p, INT64 size) override; + virtual INT64 Read(void* p, INT64 size) override; + virtual INT64 Write(const void* p, INT64 size) override; - INT64 GetSize(); + INT64 GetSize(); - bool IsReady() const { return _ready; } - void DownloadAsync(CSZ url, bool nullTerm = false); - VERUS_P(void ThreadProc()); - const BYTE* GetData() const { return _vData.data(); } - }; - VERUS_TYPEDEFS(HttpFile); - } + bool IsReady() const { return _ready; } + void DownloadAsync(CSZ url, bool nullTerm = false); + VERUS_P(void ThreadProc()); + const BYTE* GetData() const { return _vData.data(); } + }; + VERUS_TYPEDEFS(HttpFile); } diff --git a/Verus/src/Net/Multiplayer.h b/Verus/src/Net/Multiplayer.h index cf582e3..f03f8cf 100644 --- a/Verus/src/Net/Multiplayer.h +++ b/Verus/src/Net/Multiplayer.h @@ -1,156 +1,153 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Net { - namespace Net + struct GameDesc { - struct GameDesc + String _name; + String _map; + Addr _addr; + UINT16 _version = 0; + UINT16 _count = 0; + }; + VERUS_TYPEDEFS(GameDesc); + + enum { REPORT_ID_SIZE = 1 }; + + enum REPORT_ID + { + REPORT_NOOP, + REPORT_RNAT, + REPORT_RACK, + REPORT_PADD, + REPORT_PREM, + REPORT_KICK, + REPORT_USER + }; + + struct MultiplayerDelegate + { + virtual void Multiplayer_OnReportFrom/**/(int id, const BYTE* p) = 0; + virtual bool Multiplayer_IsReliable /**/(const BYTE* p) = 0; + virtual bool Multiplayer_OnConnect /**/(int id, const BYTE* p, RcAddr addr) = 0; + virtual void Multiplayer_OnDisconnect/**/(int id) = 0; + }; + VERUS_TYPEDEFS(MultiplayerDelegate); + + struct MultiplayerFlags + { + enum { - String _name; - String _map; - Addr _addr; - UINT16 _version = 0; - UINT16 _count = 0; + sendReports = (ObjectFlags::user << 0), + activeGamesReady = (ObjectFlags::user << 1), + noLock = (ObjectFlags::user << 2), + running = (ObjectFlags::user << 3) }; - VERUS_TYPEDEFS(GameDesc); + }; - enum { REPORT_ID_SIZE = 1 }; - - enum REPORT_ID + class Multiplayer : public Singleton, public Object, public Lockable + { + enum class Seq : UINT16 { - REPORT_NOOP, - REPORT_RNAT, - REPORT_RACK, - REPORT_PADD, - REPORT_PREM, - REPORT_KICK, - REPORT_USER + skip, + unreliable, + reliableBase }; - struct MultiplayerDelegate + class Player { - virtual void Multiplayer_OnReportFrom/**/(int id, const BYTE* p) = 0; - virtual bool Multiplayer_IsReliable /**/(const BYTE* p) = 0; - virtual bool Multiplayer_OnConnect /**/(int id, const BYTE* p, RcAddr addr) = 0; - virtual void Multiplayer_OnDisconnect/**/(int id) = 0; - }; - VERUS_TYPEDEFS(MultiplayerDelegate); + friend class Multiplayer; - struct MultiplayerFlags - { - enum - { - sendReports = (ObjectFlags::user << 0), - activeGamesReady = (ObjectFlags::user << 1), - noLock = (ObjectFlags::user << 2), - running = (ObjectFlags::user << 3) - }; - }; - - class Multiplayer : public Singleton, public Object, public Lockable - { - enum class Seq : UINT16 - { - skip, - unreliable, - reliableBase - }; - - class Player - { - friend class Multiplayer; - - std::chrono::steady_clock::time_point _tpLast; - String _log; - BaseCircularBuffer _sendBuffer; - BaseCircularBuffer _recvBuffer; - Addr _addr; // Not null means active player. - UINT32 _statSendBufferFullCount = 0; - UINT32 _statRecvBufferFullCount = 0; - UINT16 _sendSeq = +Seq::reliableBase; - UINT16 _sendSeqResend = +Seq::reliableBase; - UINT16 _recvSeq = +Seq::reliableBase; - bool _reserved = false; // Taken by app for bot, etc. - - public: - Player(); - - void Reset(); - void Log(CSZ msg); - void SaveLog(int id, bool server); - }; - VERUS_TYPEDEFS(Player); - - static const int s_bufferSize = 256; - static const int s_logSize = 20 * 1024; - - PMultiplayerDelegate _pDelegate = nullptr; - Vector _vPlayers; - Vector _vMasterBuffer; - Vector _vReportBuffer; - Vector _vGameDesc; - Vector _vNat; - String _lobbyWebsite; - String _lobbyGameID; - GameDesc _lobbyGameDesc; - Socket _socket; - std::thread _thread; - std::thread _threadWeb; - std::condition_variable _cv; - int _maxPlayers = 0; - int _maxReportSize = 0; - int _maxReports = 0; - int _myPlayer = -1; - Addr _serverAddr; // Localhost means that this machine is the server. - - static bool IsLessThan(UINT16 a, UINT16 b); - static bool IsGreaterThan(UINT16 a, UINT16 b); - static void NextSeq(UINT16& seq); + std::chrono::steady_clock::time_point _tpLast; + String _log; + BaseCircularBuffer _sendBuffer; + BaseCircularBuffer _recvBuffer; + Addr _addr; // Not null means active player. + UINT32 _statSendBufferFullCount = 0; + UINT32 _statRecvBufferFullCount = 0; + UINT16 _sendSeq = +Seq::reliableBase; + UINT16 _sendSeqResend = +Seq::reliableBase; + UINT16 _recvSeq = +Seq::reliableBase; + bool _reserved = false; // Taken by app for bot, etc. public: - Multiplayer(); - ~Multiplayer(); + Player(); - void Init(RcAddr addr, int maxPlayers, int maxReportSize, int maxReports = 32); - void Done(); - - PMultiplayerDelegate SetDelegate(PMultiplayerDelegate p) { return Utils::Swap(_pDelegate, p); } - - bool IsServer() const { return _serverAddr.IsLocalhost(); } - RcAddr GetServerAddr() const { return _serverAddr; } - int GetMyPlayer() const { return _myPlayer; } - void SetMyPlayer(int id) { _myPlayer = id; } - int GetPlayerCount(); - int GetMaxPlayers() const { return _maxPlayers; } - bool IsActivePlayer(int id); - - int ReservePlayer(); - void CancelReservation(int id); - - // Writes the report into the send buffer for some or all players. This will eventually send this report. - // id = Player's ID. Use -1 to send the report to all players. Server cannot send the report to itself. - // p = Pointer to report's data. Must not be less than the size of the report. - // deferred = Will send it as soon as possible if false. - void SendReportAsync(int id, BYTE* p, bool deferred = false); - // Reads reports from recv buffers, cleans them, calls MultiplayerDelegate's callbacks. - void ProcessRecvBuffers(); - // Writes the KICK report to the player's send buffer. This will eventually kick the specified player. - void Kick(int id); - - VERUS_P(int GetIdByAddr(RcAddr addr) const); - VERUS_P(int FindFreeID() const); - VERUS_P(void ThreadProc()); - - String GetDebug(); - - void UploadActiveGameAsync(RcGameDesc gd, CSZ gameID, CSZ website = "swiborg.com"); - void DownloadActiveGamesAsync(CSZ gameID, int version, CSZ website = "swiborg.com"); - bool AreActiveGamesReady(); - void UploadNatRequest(CSZ gameID, CSZ website = "swiborg.com"); - Vector GetActiveGames(); - VERUS_P(void ThreadProcWeb()); + void Reset(); + void Log(CSZ msg); + void SaveLog(int id, bool server); }; - VERUS_TYPEDEFS(Multiplayer); - } + VERUS_TYPEDEFS(Player); + + static const int s_bufferSize = 256; + static const int s_logSize = 20 * 1024; + + PMultiplayerDelegate _pDelegate = nullptr; + Vector _vPlayers; + Vector _vMasterBuffer; + Vector _vReportBuffer; + Vector _vGameDesc; + Vector _vNat; + String _lobbyWebsite; + String _lobbyGameID; + GameDesc _lobbyGameDesc; + Socket _socket; + std::thread _thread; + std::thread _threadWeb; + std::condition_variable _cv; + int _maxPlayers = 0; + int _maxReportSize = 0; + int _maxReports = 0; + int _myPlayer = -1; + Addr _serverAddr; // Localhost means that this machine is the server. + + static bool IsLessThan(UINT16 a, UINT16 b); + static bool IsGreaterThan(UINT16 a, UINT16 b); + static void NextSeq(UINT16& seq); + + public: + Multiplayer(); + ~Multiplayer(); + + void Init(RcAddr addr, int maxPlayers, int maxReportSize, int maxReports = 32); + void Done(); + + PMultiplayerDelegate SetDelegate(PMultiplayerDelegate p) { return Utils::Swap(_pDelegate, p); } + + bool IsServer() const { return _serverAddr.IsLocalhost(); } + RcAddr GetServerAddr() const { return _serverAddr; } + int GetMyPlayer() const { return _myPlayer; } + void SetMyPlayer(int id) { _myPlayer = id; } + int GetPlayerCount(); + int GetMaxPlayers() const { return _maxPlayers; } + bool IsActivePlayer(int id); + + int ReservePlayer(); + void CancelReservation(int id); + + // Writes the report into the send buffer for some or all players. This will eventually send this report. + // id = Player's ID. Use -1 to send the report to all players. Server cannot send the report to itself. + // p = Pointer to report's data. Must not be less than the size of the report. + // deferred = Will send it as soon as possible if false. + void SendReportAsync(int id, BYTE* p, bool deferred = false); + // Reads reports from recv buffers, cleans them, calls MultiplayerDelegate's callbacks. + void ProcessRecvBuffers(); + // Writes the KICK report to the player's send buffer. This will eventually kick the specified player. + void Kick(int id); + + VERUS_P(int GetIdByAddr(RcAddr addr) const); + VERUS_P(int FindFreeID() const); + VERUS_P(void ThreadProc()); + + String GetDebug(); + + void UploadActiveGameAsync(RcGameDesc gd, CSZ gameID, CSZ website = "swiborg.com"); + void DownloadActiveGamesAsync(CSZ gameID, int version, CSZ website = "swiborg.com"); + bool AreActiveGamesReady(); + void UploadNatRequest(CSZ gameID, CSZ website = "swiborg.com"); + Vector GetActiveGames(); + VERUS_P(void ThreadProcWeb()); + }; + VERUS_TYPEDEFS(Multiplayer); } diff --git a/Verus/src/Net/Socket.h b/Verus/src/Net/Socket.h index 0c52d9e..a5f576b 100644 --- a/Verus/src/Net/Socket.h +++ b/Verus/src/Net/Socket.h @@ -1,60 +1,57 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Net { - namespace Net + class Socket : public Lockable { - class Socket : public Lockable + class Client { - class Client - { - friend class Socket; + friend class Socket; - Socket* _pListener = nullptr; - SOCKET _socket = INVALID_SOCKET; - std::thread _thread; - Vector _vBuffer; + Socket* _pListener = nullptr; + SOCKET _socket = INVALID_SOCKET; + std::thread _thread; + Vector _vBuffer; - void ThreadProc(); - }; - VERUS_TYPEDEFS(Client); - - static WSADATA s_wsaData; - SOCKET _socket = INVALID_SOCKET; - std::thread _thread; - Vector _vClients; - int _maxClients = 1; - int _clientBufferSize = 0; - - public: - Socket(); - ~Socket(); - - static void Startup(); - static void Cleanup(); - - void Listen(int port); - void Connect(RcAddr addr); - void Udp(int port); - void Close(); - - int Send(const void* p, int size) const; - int SendTo(const void* p, int size, RcAddr addr) const; - int Recv(void* p, int size) const; - int RecvFrom(void* p, int size, RAddr addr) const; - - void SetMaxClients(int count) { _maxClients = count; } - void SetClientBufferSize(int size) { _clientBufferSize = size; } - - VERUS_P(void ThreadProc()); - - void GetLatestClientBuffer(int id, BYTE* p); - - VERUS_P(int GetFreeClientSlot() const); - - VERUS_P(void CloseAllClients()); + void ThreadProc(); }; - VERUS_TYPEDEFS(Socket); - } + VERUS_TYPEDEFS(Client); + + static WSADATA s_wsaData; + SOCKET _socket = INVALID_SOCKET; + std::thread _thread; + Vector _vClients; + int _maxClients = 1; + int _clientBufferSize = 0; + + public: + Socket(); + ~Socket(); + + static void Startup(); + static void Cleanup(); + + void Listen(int port); + void Connect(RcAddr addr); + void Udp(int port); + void Close(); + + int Send(const void* p, int size) const; + int SendTo(const void* p, int size, RcAddr addr) const; + int Recv(void* p, int size) const; + int RecvFrom(void* p, int size, RAddr addr) const; + + void SetMaxClients(int count) { _maxClients = count; } + void SetClientBufferSize(int size) { _clientBufferSize = size; } + + VERUS_P(void ThreadProc()); + + void GetLatestClientBuffer(int id, BYTE* p); + + VERUS_P(int GetFreeClientSlot() const); + + VERUS_P(void CloseAllClients()); + }; + VERUS_TYPEDEFS(Socket); } diff --git a/Verus/src/Physics/Bullet.h b/Verus/src/Physics/Bullet.h index 67de23a..4a75592 100644 --- a/Verus/src/Physics/Bullet.h +++ b/Verus/src/Physics/Bullet.h @@ -1,137 +1,134 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Physics { - namespace Physics + class alignas(btDefaultMotionState) alignas(btRigidBody) LocalRigidBody { - class alignas(btDefaultMotionState) alignas(btRigidBody) LocalRigidBody + BYTE _data[sizeof(btDefaultMotionState) + sizeof(btRigidBody)] = {}; + btRigidBody* _p = nullptr; + + public: + void operator=(btRigidBody* p) { - BYTE _data[sizeof(btDefaultMotionState) + sizeof(btRigidBody)] = {}; - btRigidBody* _p = nullptr; + _p = p; + } - public: - void operator=(btRigidBody* p) - { - _p = p; - } - - btRigidBody* operator->() const - { - return _p; - } - btRigidBody* Get() - { - return _p; - } - - BYTE* GetDefaultMotionStateData() - { - return &_data[0]; - } - BYTE* GetRigidBodyData() - { - return &_data[sizeof(btDefaultMotionState)]; - } - - void Delete() - { - if (_p) - { - _p->getMotionState()->~btMotionState(); - _p->~btRigidBody(); - _p = nullptr; - } - } - }; - VERUS_TYPEDEFS(LocalRigidBody); - - enum class Material : int + btRigidBody* operator->() const { - brick, - glass, - leather, - metal, - plastic, - rubber, - sand, - stone, - wood, - count - }; - - enum class DebugDrawMode : int + return _p; + } + btRigidBody* Get() { - none, - basic - }; + return _p; + } - class Bullet : public Singleton, public Object + BYTE* GetDefaultMotionStateData() { - static const int s_defaultMaxSubSteps = 8; + return &_data[0]; + } + BYTE* GetRigidBodyData() + { + return &_data[sizeof(btDefaultMotionState)]; + } - LocalPtr _pCollisionConfiguration; - LocalPtr _pDispatcher; - LocalPtr _pBroadphaseInterface; - LocalPtr _pConstraintSolver; - LocalPtr _pDiscreteDynamicsWorld; - LocalPtr _pStaticPlaneShape; - LocalRigidBody _pStaticPlaneRigidBody; - btGhostPairCallback _ghostPairCallback; - BulletDebugDraw _debugDraw; - Group _staticMask = Group::immovable | Group::terrain | Group::forest; - bool _pauseSimulation = false; + void Delete() + { + if (_p) + { + _p->getMotionState()->~btMotionState(); + _p->~btRigidBody(); + _p = nullptr; + } + } + }; + VERUS_TYPEDEFS(LocalRigidBody); - public: - Bullet(); - ~Bullet(); + enum class Material : int + { + brick, + glass, + leather, + metal, + plastic, + rubber, + sand, + stone, + wood, + count + }; - void Init(); - void Done(); + enum class DebugDrawMode : int + { + none, + basic + }; - btDefaultCollisionConfiguration* GetCollisionConfiguration() { return _pCollisionConfiguration.Get(); } - btCollisionDispatcher* GetDispatcher() { return _pDispatcher.Get(); } - btAxisSweep3* GetBroadphaseInterface() { return _pBroadphaseInterface.Get(); } - btSequentialImpulseConstraintSolver* GetConstraintSolver() { return _pConstraintSolver.Get(); } - btDiscreteDynamicsWorld* GetWorld() { return _pDiscreteDynamicsWorld.Get(); } + class Bullet : public Singleton, public Object + { + static const int s_defaultMaxSubSteps = 8; - btRigidBody* AddNewRigidBody( - float mass, - const btTransform& startTransform, - btCollisionShape* pShape, - int group = +Group::general, - int mask = +Group::all, - const btTransform* pCenterOfMassOffset = nullptr, - void* pPlacementMotionState = nullptr, - void* pPlacementRigidBody = nullptr); - btRigidBody* AddNewRigidBody( - RLocalRigidBody localRigidBody, - float mass, - const btTransform& startTransform, - btCollisionShape* pShape, - int group = +Group::general, - int mask = +Group::all, - const btTransform* pCenterOfMassOffset = nullptr); + LocalPtr _pCollisionConfiguration; + LocalPtr _pDispatcher; + LocalPtr _pBroadphaseInterface; + LocalPtr _pConstraintSolver; + LocalPtr _pDiscreteDynamicsWorld; + LocalPtr _pStaticPlaneShape; + LocalRigidBody _pStaticPlaneRigidBody; + btGhostPairCallback _ghostPairCallback; + BulletDebugDraw _debugDraw; + Group _staticMask = Group::immovable | Group::terrain | Group::forest; + bool _pauseSimulation = false; - void DeleteAllCollisionObjects(); + public: + Bullet(); + ~Bullet(); - void Simulate(); - void PauseSimualtion(bool b) { _pauseSimulation = b; } - bool IsSimulationPaused() const { return _pauseSimulation; } + void Init(); + void Done(); - void DebugDraw(); - void SetDebugDrawMode(DebugDrawMode mode); - void EnableDebugPlane(bool b); + btDefaultCollisionConfiguration* GetCollisionConfiguration() { return _pCollisionConfiguration.Get(); } + btCollisionDispatcher* GetDispatcher() { return _pDispatcher.Get(); } + btAxisSweep3* GetBroadphaseInterface() { return _pBroadphaseInterface.Get(); } + btSequentialImpulseConstraintSolver* GetConstraintSolver() { return _pConstraintSolver.Get(); } + btDiscreteDynamicsWorld* GetWorld() { return _pDiscreteDynamicsWorld.Get(); } - static float GetFriction(Material m); - static float GetRestitution(Material m); + btRigidBody* AddNewRigidBody( + float mass, + const btTransform& startTransform, + btCollisionShape* pShape, + int group = +Group::general, + int mask = +Group::all, + const btTransform* pCenterOfMassOffset = nullptr, + void* pPlacementMotionState = nullptr, + void* pPlacementRigidBody = nullptr); + btRigidBody* AddNewRigidBody( + RLocalRigidBody localRigidBody, + float mass, + const btTransform& startTransform, + btCollisionShape* pShape, + int group = +Group::general, + int mask = +Group::all, + const btTransform* pCenterOfMassOffset = nullptr); - static CSZ GroupToString(int index); + void DeleteAllCollisionObjects(); - Group GetStaticMask() const { return _staticMask; } - Group GetNonStaticMask() const { return ~_staticMask; } - void SetStaticMask(Group mask) { _staticMask = mask; } - }; - VERUS_TYPEDEFS(Bullet); - } + void Simulate(); + void PauseSimualtion(bool b) { _pauseSimulation = b; } + bool IsSimulationPaused() const { return _pauseSimulation; } + + void DebugDraw(); + void SetDebugDrawMode(DebugDrawMode mode); + void EnableDebugPlane(bool b); + + static float GetFriction(Material m); + static float GetRestitution(Material m); + + static CSZ GroupToString(int index); + + Group GetStaticMask() const { return _staticMask; } + Group GetNonStaticMask() const { return ~_staticMask; } + void SetStaticMask(Group mask) { _staticMask = mask; } + }; + VERUS_TYPEDEFS(Bullet); } diff --git a/Verus/src/Physics/BulletDebugDraw.h b/Verus/src/Physics/BulletDebugDraw.h index 19a7d2a..494c2aa 100644 --- a/Verus/src/Physics/BulletDebugDraw.h +++ b/Verus/src/Physics/BulletDebugDraw.h @@ -1,39 +1,36 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Physics { - namespace Physics + class BulletDebugDraw : public btIDebugDraw { - class BulletDebugDraw : public btIDebugDraw - { - static const int s_maxDrawDist = 25; + static const int s_maxDrawDist = 25; - int _debugMode = 0; + int _debugMode = 0; - public: - BulletDebugDraw() : _debugMode(btIDebugDraw::DBG_DrawWireframe) {} - ~BulletDebugDraw() {} + public: + BulletDebugDraw() : _debugMode(btIDebugDraw::DBG_DrawWireframe) {} + ~BulletDebugDraw() {} - virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& color) override; - virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& fromColor, const btVector3& toColor) override; + virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& color) override; + virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& fromColor, const btVector3& toColor) override; - virtual void drawSphere(const btVector3& p, btScalar radius, const btVector3& color) override; - virtual void drawBox(const btVector3& boxMin, const btVector3& boxMax, const btVector3& color) override; + virtual void drawSphere(const btVector3& p, btScalar radius, const btVector3& color) override; + virtual void drawBox(const btVector3& boxMin, const btVector3& boxMax, const btVector3& color) override; - virtual void drawTriangle(const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& color, btScalar alpha) override; + virtual void drawTriangle(const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& color, btScalar alpha) override; - virtual void drawContactPoint(const btVector3& pointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color) override; + virtual void drawContactPoint(const btVector3& pointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color) override; - virtual void reportErrorWarning(const char* warningString) override; + virtual void reportErrorWarning(const char* warningString) override; - virtual void draw3dText(const btVector3& location, const char* textString) override; + virtual void draw3dText(const btVector3& location, const char* textString) override; - virtual void drawTransform(const btTransform& transform, btScalar orthoLen) override; + virtual void drawTransform(const btTransform& transform, btScalar orthoLen) override; - virtual void setDebugMode(int debugMode) override { _debugMode = debugMode; } - virtual int getDebugMode() const override { return _debugMode; } - }; - VERUS_TYPEDEFS(BulletDebugDraw); - } + virtual void setDebugMode(int debugMode) override { _debugMode = debugMode; } + virtual int getDebugMode() const override { return _debugMode; } + }; + VERUS_TYPEDEFS(BulletDebugDraw); } diff --git a/Verus/src/Physics/CharacterController.h b/Verus/src/Physics/CharacterController.h index 17d87f4..f7ab8ed 100644 --- a/Verus/src/Physics/CharacterController.h +++ b/Verus/src/Physics/CharacterController.h @@ -1,56 +1,53 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Physics { - namespace Physics + class CharacterController : public Object, public UserPtr { - class CharacterController : public Object, public UserPtr + LocalPtr _pCapsule; + LocalPtr _pKCC; // Action. + LocalPtr _pGhostObject; // CollisionObject. + float _radius = 1; + float _height = 1; + float _offset = 0; + + public: + class Desc { - LocalPtr _pCapsule; - LocalPtr _pKCC; // Action. - LocalPtr _pGhostObject; // CollisionObject. - float _radius = 1; - float _height = 1; - float _offset = 0; - public: - class Desc - { - public: - float _radius = -1; - float _height = -1; - float _stepHeight = -1; - }; - VERUS_TYPEDEFS(Desc); - - CharacterController(); - ~CharacterController(); - - void Init(RcPoint3 pos, RcDesc desc); - void Done(); - - virtual int UserPtr_GetType() override; - - float GetRadius() const { return _radius; } - float GetHeight() const { return _height; } - float GetOffset() const { return _offset; } - void SetRadius(float r); - void SetHeight(float h); - VERUS_P(void UpdateScaling()); - - KinematicCharacterController* GetKCC() { return _pKCC.Get(); } - const KinematicCharacterController* GetKCC() const { return _pKCC.Get(); } - - void Move(RcVector3 velocity); - - Point3 GetPosition(); - void MoveTo(RcPoint3 pos); - - void Visualize(bool b); - - bool Is(const void* p) const { return p == this; } + float _radius = -1; + float _height = -1; + float _stepHeight = -1; }; - VERUS_TYPEDEFS(CharacterController); - } + VERUS_TYPEDEFS(Desc); + + CharacterController(); + ~CharacterController(); + + void Init(RcPoint3 pos, RcDesc desc); + void Done(); + + virtual int UserPtr_GetType() override; + + float GetRadius() const { return _radius; } + float GetHeight() const { return _height; } + float GetOffset() const { return _offset; } + void SetRadius(float r); + void SetHeight(float h); + VERUS_P(void UpdateScaling()); + + KinematicCharacterController* GetKCC() { return _pKCC.Get(); } + const KinematicCharacterController* GetKCC() const { return _pKCC.Get(); } + + void Move(RcVector3 velocity); + + Point3 GetPosition(); + void MoveTo(RcPoint3 pos); + + void Visualize(bool b); + + bool Is(const void* p) const { return p == this; } + }; + VERUS_TYPEDEFS(CharacterController); } diff --git a/Verus/src/Physics/Groups.h b/Verus/src/Physics/Groups.h index 34f3edd..269f2b8 100644 --- a/Verus/src/Physics/Groups.h +++ b/Verus/src/Physics/Groups.h @@ -1,30 +1,27 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Physics { - namespace Physics + enum class Group : UINT32 { - enum class Group : UINT32 - { - none = 0, - general = (1 << 0), - immovable = (1 << 1), - kinematic = (1 << 2), - debris = (1 << 3), - sensor = (1 << 4), - character = (1 << 5), - ragdoll = (1 << 6), - ray = (1 << 7), // rayTest - node = (1 << 8), // World::PBaseNode - dynamic = (1 << 9), - gizmo = (1 << 10), // Editor::PGizmoTool - particle = (1 << 11), - terrain = (1 << 12), - forest = (1 << 13), - transport = (1 << 14), - wall = (1 << 15), - all = UINT32_MAX - }; - } + none = 0, + general = (1 << 0), + immovable = (1 << 1), + kinematic = (1 << 2), + debris = (1 << 3), + sensor = (1 << 4), + character = (1 << 5), + ragdoll = (1 << 6), + ray = (1 << 7), // rayTest + node = (1 << 8), // World::PBaseNode + dynamic = (1 << 9), + gizmo = (1 << 10), // Editor::PGizmoTool + particle = (1 << 11), + terrain = (1 << 12), + forest = (1 << 13), + transport = (1 << 14), + wall = (1 << 15), + all = UINT32_MAX + }; } diff --git a/Verus/src/Physics/Spring.h b/Verus/src/Physics/Spring.h index 2c2f27d..92bc635 100644 --- a/Verus/src/Physics/Spring.h +++ b/Verus/src/Physics/Spring.h @@ -1,24 +1,21 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Physics { - namespace Physics + class Spring { - class Spring - { - Vector3 _offset = Vector3(0); - Vector3 _velocity = Vector3(0); - float _stiffness = 50; - float _damping = 2; + Vector3 _offset = Vector3(0); + Vector3 _velocity = Vector3(0); + float _stiffness = 50; + float _damping = 2; - public: - Spring(float stiffness = 50, float damping = 2); + public: + Spring(float stiffness = 50, float damping = 2); - void Update(RcVector3 appliedForce); + void Update(RcVector3 appliedForce); - RcVector3 GetOffset() const { return _offset; } - }; - VERUS_TYPEDEFS(Spring); - } + RcVector3 GetOffset() const { return _offset; } + }; + VERUS_TYPEDEFS(Spring); } diff --git a/Verus/src/Physics/UserPtr.h b/Verus/src/Physics/UserPtr.h index 3111a5e..442f651 100644 --- a/Verus/src/Physics/UserPtr.h +++ b/Verus/src/Physics/UserPtr.h @@ -1,15 +1,12 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Physics { - namespace Physics + class UserPtr { - class UserPtr - { - public: - virtual int UserPtr_GetType() = 0; - }; - VERUS_TYPEDEFS(UserPtr); - } + public: + virtual int UserPtr_GetType() = 0; + }; + VERUS_TYPEDEFS(UserPtr); } diff --git a/Verus/src/Physics/Vehicle.h b/Verus/src/Physics/Vehicle.h index 708d79f..971f3e4 100644 --- a/Verus/src/Physics/Vehicle.h +++ b/Verus/src/Physics/Vehicle.h @@ -1,95 +1,92 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Physics { - namespace Physics + class Vehicle : public Object, public UserPtr { - class Vehicle : public Object, public UserPtr + LocalPtr _pChassisShape; + LocalPtr _pBumperShape; + LocalPtr _pCompoundShape; + LocalRigidBody _pChassis; + LocalPtr _pVehicleRaycaster; + LocalPtr _pRaycastVehicle; + btRaycastVehicle::btVehicleTuning _vehicleTuning; + int _frontRightWheelIndex = -1; + int _wheelCount = 0; + float _invWheelCount = 0; + float _invHandBrakeWheelCount = 0; + + public: + struct Steering { - LocalPtr _pChassisShape; - LocalPtr _pBumperShape; - LocalPtr _pCompoundShape; - LocalRigidBody _pChassis; - LocalPtr _pVehicleRaycaster; - LocalPtr _pRaycastVehicle; - btRaycastVehicle::btVehicleTuning _vehicleTuning; - int _frontRightWheelIndex = -1; - int _wheelCount = 0; - float _invWheelCount = 0; - float _invHandBrakeWheelCount = 0; + float _angle = 0; + float _speed = 1; + float _maxAngle = Math::ToRadians(40); - public: - struct Steering + void Update(float stiffness) { - float _angle = 0; - float _speed = 1; - float _maxAngle = Math::ToRadians(40); - - void Update(float stiffness) - { - VERUS_QREF_TIMER; - // Steering torque: - const float deviation = abs(_angle / _maxAngle); - _angle = Math::Reduce(_angle, (_speed * dt) * deviation * stiffness); - } - - void SteerLeft() - { - VERUS_QREF_TIMER; - _angle = Math::Clamp(_angle + _speed * dt, -_maxAngle, _maxAngle); - } - - void SteerRight() - { - VERUS_QREF_TIMER; - _angle = Math::Clamp(_angle - _speed * dt, -_maxAngle, _maxAngle); - } - }; - VERUS_TYPEDEFS(Steering); - - struct Desc - { - Transform3 _tr = Transform3::identity(); - Math::Bounds _chassis; - Vector _vLeftWheels; - Vector _vRightWheels; - float _mass = 1200; - float _suspensionRestLength = 0.15f; // 0.25 for buggy, 0.05 for sports car. - }; - VERUS_TYPEDEFS(Desc); - - Vehicle(); - ~Vehicle(); - - void Init(RcDesc desc); - void Done(); - - void Update(); - - template - void ForEachWheel(const T& fn) const - { - VERUS_FOR(i, _wheelCount) - { - if (Continue::no == fn(_pRaycastVehicle->getWheelInfo(i))) - return; - } + VERUS_QREF_TIMER; + // Steering torque: + const float deviation = abs(_angle / _maxAngle); + _angle = Math::Reduce(_angle, (_speed * dt) * deviation * stiffness); } - Transform3 GetTransform() const; + void SteerLeft() + { + VERUS_QREF_TIMER; + _angle = Math::Clamp(_angle + _speed * dt, -_maxAngle, _maxAngle); + } - btRaycastVehicle* GetRaycastVehicle() { return _pRaycastVehicle.Get(); } - - void ApplyAirForce(float scale = 1); - void SetBrake(float brake, float handBrake = 0, int index = -1); - void SetEngineForce(float force, int index = -1); - void SetSteeringAngle(float angle); - - virtual int UserPtr_GetType() override; - - float ComputeEnginePitch() const; + void SteerRight() + { + VERUS_QREF_TIMER; + _angle = Math::Clamp(_angle - _speed * dt, -_maxAngle, _maxAngle); + } }; - VERUS_TYPEDEFS(Vehicle); - } + VERUS_TYPEDEFS(Steering); + + struct Desc + { + Transform3 _tr = Transform3::identity(); + Math::Bounds _chassis; + Vector _vLeftWheels; + Vector _vRightWheels; + float _mass = 1200; + float _suspensionRestLength = 0.15f; // 0.25 for buggy, 0.05 for sports car. + }; + VERUS_TYPEDEFS(Desc); + + Vehicle(); + ~Vehicle(); + + void Init(RcDesc desc); + void Done(); + + void Update(); + + template + void ForEachWheel(const T& fn) const + { + VERUS_FOR(i, _wheelCount) + { + if (Continue::no == fn(_pRaycastVehicle->getWheelInfo(i))) + return; + } + } + + Transform3 GetTransform() const; + + btRaycastVehicle* GetRaycastVehicle() { return _pRaycastVehicle.Get(); } + + void ApplyAirForce(float scale = 1); + void SetBrake(float brake, float handBrake = 0, int index = -1); + void SetEngineForce(float force, int index = -1); + void SetSteeringAngle(float angle); + + virtual int UserPtr_GetType() override; + + float ComputeEnginePitch() const; + }; + VERUS_TYPEDEFS(Vehicle); } diff --git a/Verus/src/Security/CipherRC4.h b/Verus/src/Security/CipherRC4.h index 5d127f6..3a53b72 100644 --- a/Verus/src/Security/CipherRC4.h +++ b/Verus/src/Security/CipherRC4.h @@ -1,79 +1,76 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::Security { - namespace Security + class CipherRC4 { - class CipherRC4 + public: + static inline void Encrypt( + RcString password, + const Vector& vData, + Vector& vCipher, + size_t skip = 787) { - public: - static inline void Encrypt( - RcString password, - const Vector& vData, - Vector& vCipher, - size_t skip = 787) + vCipher.resize(vData.size()); + size_t i, j, a; + BYTE key[256]; + BYTE box[256]; + for (i = 0; i < 256; ++i) { - vCipher.resize(vData.size()); - size_t i, j, a; - BYTE key[256]; - BYTE box[256]; - for (i = 0; i < 256; ++i) - { - key[i] = password[i % password.length()]; - box[i] = static_cast(i); - } - for (j = i = 0; i < 256; ++i) - { - j = (j + box[i] + key[i]) & 0xFF; - std::swap(box[i], box[j]); - } - const size_t count = vData.size() + skip; - for (a = j = i = 0; i < count; ++i) - { - a = (a + 1) & 0xFF; - j = (j + box[a]) & 0xFF; - std::swap(box[a], box[j]); - const BYTE k = box[(box[a] + box[j]) & 0xFF]; - if (i >= skip) - vCipher[i - skip] = vData[i - skip] ^ k; - } + key[i] = password[i % password.length()]; + box[i] = static_cast(i); } - - static inline void Decrypt( - RcString password, - const Vector& vCipher, - Vector& vData, - size_t skip = 787) + for (j = i = 0; i < 256; ++i) { - Encrypt(password, vCipher, vData, skip); + j = (j + box[i] + key[i]) & 0xFF; + std::swap(box[i], box[j]); } - - static inline void Test() + const size_t count = vData.size() + skip; + for (a = j = i = 0; i < count; ++i) { - // See: https://tools.ietf.org/html/rfc6229 - - const BYTE offset0000_256[] = { 0xEA, 0xA6, 0xBD, 0x25, 0x88, 0x0B, 0xF9, 0x3D, 0x3F, 0x5D, 0x1E, 0x4C, 0xA2, 0x61, 0x1D, 0x91 }; - const BYTE offset1536_256[] = { 0x3E, 0x34, 0x13, 0x5C, 0x79, 0xDB, 0x01, 0x02, 0x00, 0x76, 0x76, 0x51, 0xCF, 0x26, 0x30, 0x73 }; - String password; - password.resize(32); - VERUS_FOR(i, 32) - password[i] = i + 1; - Vector v, vCip; - v.resize(16); - Encrypt(password, v, vCip, 0); - VERUS_RT_ASSERT(!memcmp(offset0000_256, vCip.data(), vCip.size())); - Encrypt(password, v, vCip, 1536); - VERUS_RT_ASSERT(!memcmp(offset1536_256, vCip.data(), vCip.size())); - - password.resize(5); - const BYTE offset0768_40[] = { 0xEB, 0x62, 0x63, 0x8D, 0x4F, 0x0B, 0xA1, 0xFE, 0x9F, 0xCA, 0x20, 0xE0, 0x5B, 0xF8, 0xFF, 0x2B }; - const BYTE offset3072_40[] = { 0xEC, 0x0E, 0x11, 0xC4, 0x79, 0xDC, 0x32, 0x9D, 0xC8, 0xDA, 0x79, 0x68, 0xFE, 0x96, 0x56, 0x81 }; - Encrypt(password, v, vCip, 768); - VERUS_RT_ASSERT(!memcmp(offset0768_40, vCip.data(), vCip.size())); - Encrypt(password, v, vCip, 3072); - VERUS_RT_ASSERT(!memcmp(offset3072_40, vCip.data(), vCip.size())); + a = (a + 1) & 0xFF; + j = (j + box[a]) & 0xFF; + std::swap(box[a], box[j]); + const BYTE k = box[(box[a] + box[j]) & 0xFF]; + if (i >= skip) + vCipher[i - skip] = vData[i - skip] ^ k; } - }; - } + } + + static inline void Decrypt( + RcString password, + const Vector& vCipher, + Vector& vData, + size_t skip = 787) + { + Encrypt(password, vCipher, vData, skip); + } + + static inline void Test() + { + // See: https://tools.ietf.org/html/rfc6229 + + const BYTE offset0000_256[] = { 0xEA, 0xA6, 0xBD, 0x25, 0x88, 0x0B, 0xF9, 0x3D, 0x3F, 0x5D, 0x1E, 0x4C, 0xA2, 0x61, 0x1D, 0x91 }; + const BYTE offset1536_256[] = { 0x3E, 0x34, 0x13, 0x5C, 0x79, 0xDB, 0x01, 0x02, 0x00, 0x76, 0x76, 0x51, 0xCF, 0x26, 0x30, 0x73 }; + String password; + password.resize(32); + VERUS_FOR(i, 32) + password[i] = i + 1; + Vector v, vCip; + v.resize(16); + Encrypt(password, v, vCip, 0); + VERUS_RT_ASSERT(!memcmp(offset0000_256, vCip.data(), vCip.size())); + Encrypt(password, v, vCip, 1536); + VERUS_RT_ASSERT(!memcmp(offset1536_256, vCip.data(), vCip.size())); + + password.resize(5); + const BYTE offset0768_40[] = { 0xEB, 0x62, 0x63, 0x8D, 0x4F, 0x0B, 0xA1, 0xFE, 0x9F, 0xCA, 0x20, 0xE0, 0x5B, 0xF8, 0xFF, 0x2B }; + const BYTE offset3072_40[] = { 0xEC, 0x0E, 0x11, 0xC4, 0x79, 0xDC, 0x32, 0x9D, 0xC8, 0xDA, 0x79, 0x68, 0xFE, 0x96, 0x56, 0x81 }; + Encrypt(password, v, vCip, 768); + VERUS_RT_ASSERT(!memcmp(offset0768_40, vCip.data(), vCip.size())); + Encrypt(password, v, vCip, 3072); + VERUS_RT_ASSERT(!memcmp(offset3072_40, vCip.data(), vCip.size())); + } + }; } diff --git a/Verus/src/World/Atmosphere.h b/Verus/src/World/Atmosphere.h index 8e6bf7e..8d9722a 100644 --- a/Verus/src/World/Atmosphere.h +++ b/Verus/src/World/Atmosphere.h @@ -1,177 +1,174 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class Atmosphere : public Singleton, public Object { - class Atmosphere : public Singleton, public Object - { - public: + public: #include "../Shaders/Sky.inc.hlsl" - enum PIPE - { - PIPE_SKY, - PIPE_SKY_REFLECTION, - PIPE_CLOUDS, - PIPE_CLOUDS_REFLECTION, - PIPE_SUN, - PIPE_MOON, - PIPE_COUNT - }; - - enum TEX - { - TEX_SKY, - TEX_STARS, - TEX_SUN, - TEX_MOON, - TEX_CLOUDS, - TEX_CLOUDS_NM, - TEX_COUNT - }; - - struct Vertex - { - float _pos[3]; - short _tc[2]; - }; - - private: - struct Clouds - { - Vector4 _phaseA = Vector4(0); - Vector4 _phaseB = Vector4(0); - float _speedPhaseA = 0.017f; - float _speedPhaseB = 0.003f; - Anim::Elastic _cloudiness = 0.25f; - }; - - struct Fog - { - Vector3 _color = Vector3(0); - float _density[2] = {}; // Actual and base. - }; - - struct Sun - { - Matrix3 _matTilt; - Vector3 _dirTo = Vector3(0, 1, 0); - Vector3 _color = Vector3(0); - LightNodePwn _lightNode; - float _alpha = 1; - float _latitude = VERUS_PI * 0.25f; - }; - - struct Wind - { - Matrix3 _matPlantBending = Matrix3::identity(); - Vector3 _baseVelocity = Vector3(4, 0, 0); - Vector3 _velocity = Vector3(4, 0, 0); - Vector3 _accel = Vector3(0); - Vector3 _jerk = Vector3(0); - Vector3 _direction = Vector3(0); - float _speed = 0; - }; - - static UB_View s_ubView; - static UB_MaterialFS s_ubMaterialFS; - static UB_MeshVS s_ubMeshVS; - static UB_Object s_ubObject; - - CGI::GeometryPwn _geo; - CGI::ShaderPwn _shader; - CGI::PipelinePwns _pipe; - CGI::TexturePwns _tex; - Clouds _clouds; - Fog _fog; - Sun _sun; - Wind _wind; - Vector3 _ambientColor = Vector3(0); - Vector3 _ambientColorY0 = Vector3(0); - Vector3 _ambientColorY1 = Vector3(0); - CubeMapBaker _cubeMapBaker; - Mesh _skyDome; - CGI::TextureRAM _texSky; - float _time = 0.5f; - float _timeSpeed = 1 / 300.f; - float _ambientMagnitude = 1; - CGI::CSHandle _cshSkyFS; - CGI::CSHandle _cshSunFS; - CGI::CSHandle _cshMoonFS; - bool _night = false; - bool _async_loaded = false; - - public: - struct Report - { - float _time; - float _speed; - float _cloudiness; - }; - VERUS_TYPEDEFS(Report); - - Atmosphere(); - virtual ~Atmosphere(); - - void Init(); - void Done(); - - void UpdateSun(float time); - void UpdateWind(); - void Update(); - void DrawSky(bool reflection = false); - - void SampleSkyColor(float time, int level, float* pOut); - static float GetMagnitude(float time, float noon, float dusk, float midnight); - - // Time: - float GetTime() const { return _time; } - void SetTime(float x) { _time = x; } - float GetTimeSpeed() const { return _timeSpeed; } - void SetTimeSpeed(float x) { _timeSpeed = x; } - - float GetAmbientMagnitude() const { return _ambientMagnitude; } - RcVector3 GetAmbientColor() const { return _ambientColor; } - RcVector3 GetAmbientColorY0() const { return _ambientColorY0; } - RcVector3 GetAmbientColorY1() const { return _ambientColorY1; } - - // Clouds: - Anim::Elastic& GetCloudiness() { return _clouds._cloudiness; } - void SetCloudiness(float x) { _clouds._cloudiness = x; _clouds._cloudiness.ForceTarget(); } - - // Fog: - RcVector3 GetFogColor() const { return _fog._color; } - float GetFogDensity() const { return _fog._density[0]; } - float GetBaseFogDensity() const { return _fog._density[1]; } - void SetBaseFogDensity(float d) { _fog._density[1] = d; } - - // Sun: - RcVector3 GetDirToSun() const; - Vector3 GetSunShadowMapUpDir() const; - RcVector3 GetSunColor() const; - float GetSunAlpha() const; - void OnWorldResetInitSunLight(); - void SetLatitude(float lat); - - // Wind: - RcMatrix3 GetPlantBendingMatrix() const; - RcVector3 GetBaseWindVelocity() const; - void SetBaseWindVelocity(RcVector3 v); - RcVector3 GetWindVelocity() const; - RcVector3 GetWindDirection() const; - float GetWindSpeed() const; - - // CubeMap: - RCubeMapBaker GetCubeMapBaker() { return _cubeMapBaker; } - - void CreateCelestialBodyMesh(); - - // Net: - void GetReport(RReport report); - void SetReport(RcReport report); + enum PIPE + { + PIPE_SKY, + PIPE_SKY_REFLECTION, + PIPE_CLOUDS, + PIPE_CLOUDS_REFLECTION, + PIPE_SUN, + PIPE_MOON, + PIPE_COUNT }; - VERUS_TYPEDEFS(Atmosphere); - } + + enum TEX + { + TEX_SKY, + TEX_STARS, + TEX_SUN, + TEX_MOON, + TEX_CLOUDS, + TEX_CLOUDS_NM, + TEX_COUNT + }; + + struct Vertex + { + float _pos[3]; + short _tc[2]; + }; + + private: + struct Clouds + { + Vector4 _phaseA = Vector4(0); + Vector4 _phaseB = Vector4(0); + float _speedPhaseA = 0.017f; + float _speedPhaseB = 0.003f; + Anim::Elastic _cloudiness = 0.25f; + }; + + struct Fog + { + Vector3 _color = Vector3(0); + float _density[2] = {}; // Actual and base. + }; + + struct Sun + { + Matrix3 _matTilt; + Vector3 _dirTo = Vector3(0, 1, 0); + Vector3 _color = Vector3(0); + LightNodePwn _lightNode; + float _alpha = 1; + float _latitude = VERUS_PI * 0.25f; + }; + + struct Wind + { + Matrix3 _matPlantBending = Matrix3::identity(); + Vector3 _baseVelocity = Vector3(4, 0, 0); + Vector3 _velocity = Vector3(4, 0, 0); + Vector3 _accel = Vector3(0); + Vector3 _jerk = Vector3(0); + Vector3 _direction = Vector3(0); + float _speed = 0; + }; + + static UB_View s_ubView; + static UB_MaterialFS s_ubMaterialFS; + static UB_MeshVS s_ubMeshVS; + static UB_Object s_ubObject; + + CGI::GeometryPwn _geo; + CGI::ShaderPwn _shader; + CGI::PipelinePwns _pipe; + CGI::TexturePwns _tex; + Clouds _clouds; + Fog _fog; + Sun _sun; + Wind _wind; + Vector3 _ambientColor = Vector3(0); + Vector3 _ambientColorY0 = Vector3(0); + Vector3 _ambientColorY1 = Vector3(0); + CubeMapBaker _cubeMapBaker; + Mesh _skyDome; + CGI::TextureRAM _texSky; + float _time = 0.5f; + float _timeSpeed = 1 / 300.f; + float _ambientMagnitude = 1; + CGI::CSHandle _cshSkyFS; + CGI::CSHandle _cshSunFS; + CGI::CSHandle _cshMoonFS; + bool _night = false; + bool _async_loaded = false; + + public: + struct Report + { + float _time; + float _speed; + float _cloudiness; + }; + VERUS_TYPEDEFS(Report); + + Atmosphere(); + virtual ~Atmosphere(); + + void Init(); + void Done(); + + void UpdateSun(float time); + void UpdateWind(); + void Update(); + void DrawSky(bool reflection = false); + + void SampleSkyColor(float time, int level, float* pOut); + static float GetMagnitude(float time, float noon, float dusk, float midnight); + + // Time: + float GetTime() const { return _time; } + void SetTime(float x) { _time = x; } + float GetTimeSpeed() const { return _timeSpeed; } + void SetTimeSpeed(float x) { _timeSpeed = x; } + + float GetAmbientMagnitude() const { return _ambientMagnitude; } + RcVector3 GetAmbientColor() const { return _ambientColor; } + RcVector3 GetAmbientColorY0() const { return _ambientColorY0; } + RcVector3 GetAmbientColorY1() const { return _ambientColorY1; } + + // Clouds: + Anim::Elastic& GetCloudiness() { return _clouds._cloudiness; } + void SetCloudiness(float x) { _clouds._cloudiness = x; _clouds._cloudiness.ForceTarget(); } + + // Fog: + RcVector3 GetFogColor() const { return _fog._color; } + float GetFogDensity() const { return _fog._density[0]; } + float GetBaseFogDensity() const { return _fog._density[1]; } + void SetBaseFogDensity(float d) { _fog._density[1] = d; } + + // Sun: + RcVector3 GetDirToSun() const; + Vector3 GetSunShadowMapUpDir() const; + RcVector3 GetSunColor() const; + float GetSunAlpha() const; + void OnWorldResetInitSunLight(); + void SetLatitude(float lat); + + // Wind: + RcMatrix3 GetPlantBendingMatrix() const; + RcVector3 GetBaseWindVelocity() const; + void SetBaseWindVelocity(RcVector3 v); + RcVector3 GetWindVelocity() const; + RcVector3 GetWindDirection() const; + float GetWindSpeed() const; + + // CubeMap: + RCubeMapBaker GetCubeMapBaker() { return _cubeMapBaker; } + + void CreateCelestialBodyMesh(); + + // Net: + void GetReport(RReport report); + void SetReport(RcReport report); + }; + VERUS_TYPEDEFS(Atmosphere); } diff --git a/Verus/src/World/BaseMesh.h b/Verus/src/World/BaseMesh.h index fae4388..d5fac17 100644 --- a/Verus/src/World/BaseMesh.h +++ b/Verus/src/World/BaseMesh.h @@ -1,180 +1,177 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class BaseMesh : public Object, public IO::AsyncDelegate, public AllocatorAware { - class BaseMesh : public Object, public IO::AsyncDelegate, public AllocatorAware + protected: + struct VertexInputBinding0 // 16 bytes, common. { - protected: - struct VertexInputBinding0 // 16 bytes, common. + short _pos[4]; + short _tc0[2]; + char _nrm[4]; + }; + VERUS_TYPEDEFS(VertexInputBinding0); + + struct VertexInputBinding1 // 16 bytes, skinned mesh. + { + short _bw[4]; + short _bi[4]; + }; + VERUS_TYPEDEFS(VertexInputBinding1); + + struct VertexInputBinding2 // 16 bytes, per-pixel lighting / normal maps. + { + short _tan[4]; + short _bin[4]; + }; + VERUS_TYPEDEFS(VertexInputBinding2); + + struct VertexInputBinding3 // 8 bytes, static light maps / extra color. + { + short _tc1[2]; + BYTE _clr[4]; + }; + VERUS_TYPEDEFS(VertexInputBinding3); + + Vector _vIndices; + Vector _vIndices32; + Vector _vBinding0; + Vector _vBinding1; + Vector _vBinding2; + Vector _vBinding3; + Anim::Skeleton _skeleton; + Anim::Warp _warp; + String _warpURL; + String _url; + btBvhTriangleMeshShape* _pShape = nullptr; + int _vertCount = 0; + int _faceCount = 0; + int _indexCount = 0; + int _boneCount = 0; + float _posDeq[6]; + float _tc0Deq[4]; + float _tc1Deq[4]; + bool _loadOnly = false; + bool _robotic = false; + bool _initShape = false; + + public: + struct SourceBuffers + { + Vector _vIndices; + Vector _vPos; + Vector _vTc0; + Vector _vNrm; + bool _recalculateTangentSpace = true; + }; + VERUS_TYPEDEFS(SourceBuffers); + + BaseMesh(); + virtual ~BaseMesh(); + + void Init(CSZ url); + void Init(RcSourceBuffers sourceBuffers); + void Done(); + + Str GetURL() const { return _C(_url); } + + int GetVertCount() const { return _vertCount; } + int GetFaceCount() const { return _faceCount; } + int GetIndexCount() const { return _indexCount; } + int GetBoneCount() const { return _boneCount; } + + virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; + + VERUS_P(void Load(RcBlob blob)); + VERUS_P(void LoadX3D3(RcBlob blob)); + bool IsLoaded() const { return !!_vertCount; } + + // Load extra: + VERUS_P(void LoadRig()); + VERUS_P(void LoadWarp()); + + // Data: + const UINT16* GetIndices() const { return _vIndices.data(); } + const UINT32* GetIndices32() const { return _vIndices32.data(); } + PcVertexInputBinding0 GetVertexInputBinding0() const { return _vBinding0.data(); } + PcVertexInputBinding1 GetVertexInputBinding1() const { return _vBinding1.data(); } + PcVertexInputBinding2 GetVertexInputBinding2() const { return _vBinding2.data(); } + PcVertexInputBinding3 GetVertexInputBinding3() const { return _vBinding3.data(); } + + // Quantization / dequantization: + static void ComputeDeq(glm::vec3& scale, glm::vec3& bias, const glm::vec3& extents, const glm::vec3& minPos); + static void QuantizeV(glm::vec3& v, const glm::vec3& extents, const glm::vec3& minPos); + static void DequantizeUsingDeq2D(const short* in, const float* deq, glm::vec2& out); + static void DequantizeUsingDeq2D(const short* in, const float* deq, RPoint3 out); + static void DequantizeUsingDeq3D(const short* in, const float* deq, glm::vec3& out); + static void DequantizeUsingDeq3D(const short* in, const float* deq, RPoint3 out); + static void DequantizeNrm(const char* in, glm::vec3& out); + static void DequantizeNrm(const char* in, RVector3 out); + static void DequantizeTanBin(const short* in, RVector3 out); + void CopyPosDeqScale(float* p) const { memcpy(p, _posDeq + 0, sizeof(float) * 3); } + void CopyPosDeqBias(float* p) const { memcpy(p, _posDeq + 3, sizeof(float) * 3); } + void CopyTexCoord0Deq(float* p) const { memcpy(p, _tc0Deq, sizeof(float) * 4); } + void CopyTexCoord1Deq(float* p) const { memcpy(p, _tc1Deq, sizeof(float) * 4); } + + void RecalculateTangentSpace(); + + // GPU: + virtual void CreateDeviceBuffers() {} + virtual void UpdateVertexBuffer(const void* p, int binding) {} + int GetPipelineIndex(bool instanced = false) const; + + // Physics: + btBvhTriangleMeshShape* GetShape() const { return _pShape; } + btBvhTriangleMeshShape* InitShape(RcTransform3 tr, CSZ url = nullptr); + void DoneShape(); + + // Bounds: + void GetBounds(RPoint3 mn, RPoint3 mx) const; + Math::Bounds GetBounds() const; + + template + void ForEachVertex(const T& fn, bool boneIndices = false) const + { + VERUS_FOR(i, _vertCount) { - short _pos[4]; - short _tc0[2]; - char _nrm[4]; - }; - VERUS_TYPEDEFS(VertexInputBinding0); - - struct VertexInputBinding1 // 16 bytes, skinned mesh. - { - short _bw[4]; - short _bi[4]; - }; - VERUS_TYPEDEFS(VertexInputBinding1); - - struct VertexInputBinding2 // 16 bytes, per-pixel lighting / normal maps. - { - short _tan[4]; - short _bin[4]; - }; - VERUS_TYPEDEFS(VertexInputBinding2); - - struct VertexInputBinding3 // 8 bytes, static light maps / extra color. - { - short _tc1[2]; - BYTE _clr[4]; - }; - VERUS_TYPEDEFS(VertexInputBinding3); - - Vector _vIndices; - Vector _vIndices32; - Vector _vBinding0; - Vector _vBinding1; - Vector _vBinding2; - Vector _vBinding3; - Anim::Skeleton _skeleton; - Anim::Warp _warp; - String _warpURL; - String _url; - btBvhTriangleMeshShape* _pShape = nullptr; - int _vertCount = 0; - int _faceCount = 0; - int _indexCount = 0; - int _boneCount = 0; - float _posDeq[6]; - float _tc0Deq[4]; - float _tc1Deq[4]; - bool _loadOnly = false; - bool _robotic = false; - bool _initShape = false; - - public: - struct SourceBuffers - { - Vector _vIndices; - Vector _vPos; - Vector _vTc0; - Vector _vNrm; - bool _recalculateTangentSpace = true; - }; - VERUS_TYPEDEFS(SourceBuffers); - - BaseMesh(); - virtual ~BaseMesh(); - - void Init(CSZ url); - void Init(RcSourceBuffers sourceBuffers); - void Done(); - - Str GetURL() const { return _C(_url); } - - int GetVertCount() const { return _vertCount; } - int GetFaceCount() const { return _faceCount; } - int GetIndexCount() const { return _indexCount; } - int GetBoneCount() const { return _boneCount; } - - virtual void Async_WhenLoaded(CSZ url, RcBlob blob) override; - - VERUS_P(void Load(RcBlob blob)); - VERUS_P(void LoadX3D3(RcBlob blob)); - bool IsLoaded() const { return !!_vertCount; } - - // Load extra: - VERUS_P(void LoadRig()); - VERUS_P(void LoadWarp()); - - // Data: - const UINT16* GetIndices() const { return _vIndices.data(); } - const UINT32* GetIndices32() const { return _vIndices32.data(); } - PcVertexInputBinding0 GetVertexInputBinding0() const { return _vBinding0.data(); } - PcVertexInputBinding1 GetVertexInputBinding1() const { return _vBinding1.data(); } - PcVertexInputBinding2 GetVertexInputBinding2() const { return _vBinding2.data(); } - PcVertexInputBinding3 GetVertexInputBinding3() const { return _vBinding3.data(); } - - // Quantization / dequantization: - static void ComputeDeq(glm::vec3& scale, glm::vec3& bias, const glm::vec3& extents, const glm::vec3& minPos); - static void QuantizeV(glm::vec3& v, const glm::vec3& extents, const glm::vec3& minPos); - static void DequantizeUsingDeq2D(const short* in, const float* deq, glm::vec2& out); - static void DequantizeUsingDeq2D(const short* in, const float* deq, RPoint3 out); - static void DequantizeUsingDeq3D(const short* in, const float* deq, glm::vec3& out); - static void DequantizeUsingDeq3D(const short* in, const float* deq, RPoint3 out); - static void DequantizeNrm(const char* in, glm::vec3& out); - static void DequantizeNrm(const char* in, RVector3 out); - static void DequantizeTanBin(const short* in, RVector3 out); - void CopyPosDeqScale(float* p) const { memcpy(p, _posDeq + 0, sizeof(float) * 3); } - void CopyPosDeqBias(float* p) const { memcpy(p, _posDeq + 3, sizeof(float) * 3); } - void CopyTexCoord0Deq(float* p) const { memcpy(p, _tc0Deq, sizeof(float) * 4); } - void CopyTexCoord1Deq(float* p) const { memcpy(p, _tc1Deq, sizeof(float) * 4); } - - void RecalculateTangentSpace(); - - // GPU: - virtual void CreateDeviceBuffers() {} - virtual void UpdateVertexBuffer(const void* p, int binding) {} - int GetPipelineIndex(bool instanced = false) const; - - // Physics: - btBvhTriangleMeshShape* GetShape() const { return _pShape; } - btBvhTriangleMeshShape* InitShape(RcTransform3 tr, CSZ url = nullptr); - void DoneShape(); - - // Bounds: - void GetBounds(RPoint3 mn, RPoint3 mx) const; - Math::Bounds GetBounds() const; - - template - void ForEachVertex(const T& fn, bool boneIndices = false) const - { - VERUS_FOR(i, _vertCount) + Point3 pos, tc; + Vector3 nrm; + DequantizeUsingDeq3D(_vBinding0[i]._pos, _posDeq, pos); + DequantizeNrm(_vBinding0[i]._nrm, nrm); + DequantizeUsingDeq2D(_vBinding0[i]._tc0, _tc0Deq, tc); + if (_vBinding1.empty() || !boneIndices) { - Point3 pos, tc; - Vector3 nrm; - DequantizeUsingDeq3D(_vBinding0[i]._pos, _posDeq, pos); - DequantizeNrm(_vBinding0[i]._nrm, nrm); - DequantizeUsingDeq2D(_vBinding0[i]._tc0, _tc0Deq, tc); - if (_vBinding1.empty() || !boneIndices) + if (Continue::no == fn(i, pos, nrm, tc)) + break; + } + else + { + bool done = false; + VERUS_FOR(j, 4) { - if (Continue::no == fn(i, pos, nrm, tc)) - break; - } - else - { - bool done = false; - VERUS_FOR(j, 4) + if (_vBinding1[i]._bw[j] > 0) { - if (_vBinding1[i]._bw[j] > 0) + if (Continue::no == fn(_vBinding1[i]._bi[j], pos, nrm, tc)) { - if (Continue::no == fn(_vBinding1[i]._bi[j], pos, nrm, tc)) - { - done = true; - break; - } + done = true; + break; } } - if (done) - break; } + if (done) + break; } } + } - Anim::RSkeleton GetSkeleton() { return _skeleton; } - Anim::RcSkeleton GetSkeleton() const { return _skeleton; } - Anim::RWarp GetWarp() { return _warp; } + Anim::RSkeleton GetSkeleton() { return _skeleton; } + Anim::RcSkeleton GetSkeleton() const { return _skeleton; } + Anim::RWarp GetWarp() { return _warp; } - String ToXmlString() const; - String ToObjString() const; - }; - VERUS_TYPEDEFS(BaseMesh); - } + String ToXmlString() const; + String ToObjString() const; + }; + VERUS_TYPEDEFS(BaseMesh); } diff --git a/Verus/src/World/Camera.h b/Verus/src/World/Camera.h index 953edb7..2b91e51 100644 --- a/Verus/src/World/Camera.h +++ b/Verus/src/World/Camera.h @@ -1,140 +1,137 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // Basic camera without extra features. For shadow map computations, etc. + class Camera { - // Basic camera without extra features. For shadow map computations, etc. - class Camera + protected: + enum class Update : BYTE { - protected: - enum class Update : BYTE - { - none, - v = (1 << 0), - p = (1 << 1) - }; - - private: - Math::Frustum _frustum; - Transform3 _matV = Transform3::identity(); - Transform3 _matInvV = Transform3::identity(); - Matrix4 _matP = Matrix4::identity(); - Matrix4 _matInvP = Matrix4::identity(); - Matrix4 _matVP = Matrix4::identity(); - VERUS_PD(Point3 _eyePos = Point3(0)); - VERUS_PD(Point3 _atPos = Point3(0, 0, -1)); - VERUS_PD(Vector3 _upDir = Vector3(0, 1, 0)); - VERUS_PD(Vector3 _frontDir = Vector3(0, 0, -1)); - float _yFov = VERUS_PI / 4; // Zero FOV means ortho. - float _aspectRatio = 1; - float _zNear = 0.1f; // 10 cm. - float _zFar = 10000; // 10 km. - float _xMag = 80; - float _yMag = 60; - float _fovScale = 1; - VERUS_PD(Update _update = Update::none); - VERUS_PD(void UpdateInternal()); - - public: - virtual void Update(); - virtual void UpdateUsingViewDesc(CGI::RcViewDesc viewDesc); - virtual void UpdateUsingHeadPose(Math::RcPose pose); - void UpdateZNearFar(); - void UpdateView(); - void UpdateVP(); - - // Frustum: - void SetFrustumNear(float zNear); - void SetFrustumFar(float zFar); - Math::RFrustum GetFrustum() { return _frustum; } - - // Positions: - RcPoint3 GetEyePosition() const { return _eyePos; } - RcPoint3 GetAtPosition() const { return _atPos; } - void MoveEyeTo(RcPoint3 pos) { _update |= Update::v; _eyePos = pos; } - void MoveAtTo(RcPoint3 pos) { _update |= Update::v; _atPos = pos; } - - // Directions: - RcVector3 GetFrontDirection() const { return _frontDir; } - RcVector3 GetUpDirection() const { return _upDir; } - void SetUpDirection(RcVector3 dir) { _update |= Update::v; _upDir = dir; } - float ComputeYaw() const; - - // Matrices: - RcTransform3 GetMatrixV() const { return _matV; } - RcTransform3 GetMatrixInvV() const { return _matInvV; } - RcMatrix4 GetMatrixP() const { return _matP; } - RcMatrix4 GetMatrixInvP() const { return _matInvP; } - RcMatrix4 GetMatrixVP() const { return _matVP; } - - // Perspective: - float GetYFov() const { return _yFov; } - void SetYFov(float yFov) { _update |= Update::p; _yFov = yFov; } - void SetXFov(float xFov); // Set correct aspect ratio before calling this method. - float GetAspectRatio() const { return _aspectRatio; } - void SetAspectRatio(float aspectRatio) { _update |= Update::p; _aspectRatio = aspectRatio; } - float GetZNear() const { return _zNear; } - void SetZNear(float zNear) { _update |= Update::p; _zNear = zNear; } - float GetZFar() const { return _zFar; } - void SetZFar(float zFar) { _update |= Update::p; _zFar = zFar; } - float GetFovScale() const { return _fovScale; } // For converting offsets in meters to offsets in texture coords. - Vector4 GetZNearFarEx() const; - - // Ortho: - float GetXMag() const { return _xMag; } - float GetYMag() const { return _yMag; } - void SetXMag(float xMag) { _update |= Update::p; _xMag = (0 == xMag) ? _aspectRatio * _yMag : xMag; } - void SetYMag(float yMag) { _update |= Update::p; _yMag = yMag; } - - // Reflection, water, special effects: - void EnableReflectionMode(); - void GetClippingSpacePlane(RVector4 plane) const; - void ExcludeWaterLine(float h = 0.25f); - - // Motion: - void ApplyMotion(CSZ boneName, Anim::RMotion motion, float time); - void BakeMotion(CSZ boneName, Anim::RMotion motion, int frame); - - // State: - virtual void SaveState(int slot); - virtual void LoadState(int slot); + none, + v = (1 << 0), + p = (1 << 1) }; - VERUS_TYPEDEFS(Camera); - // The interface for getting the cursor's position. - struct CursorPosProvider - { - virtual void GetPos(int& x, int& y) = 0; - }; - VERUS_TYPEDEFS(CursorPosProvider); + private: + Math::Frustum _frustum; + Transform3 _matV = Transform3::identity(); + Transform3 _matInvV = Transform3::identity(); + Matrix4 _matP = Matrix4::identity(); + Matrix4 _matInvP = Matrix4::identity(); + Matrix4 _matVP = Matrix4::identity(); + VERUS_PD(Point3 _eyePos = Point3(0)); + VERUS_PD(Point3 _atPos = Point3(0, 0, -1)); + VERUS_PD(Vector3 _upDir = Vector3(0, 1, 0)); + VERUS_PD(Vector3 _frontDir = Vector3(0, 0, -1)); + float _yFov = VERUS_PI / 4; // Zero FOV means ortho. + float _aspectRatio = 1; + float _zNear = 0.1f; // 10 cm. + float _zFar = 10000; // 10 km. + float _xMag = 80; + float _yMag = 60; + float _fovScale = 1; + VERUS_PD(Update _update = Update::none); + VERUS_PD(void UpdateInternal()); - // More advanced camera, used to show the world to the user. With motion blur. - class MainCamera : public Camera - { - Matrix4 _matPrevVP = Matrix4::identity(); // For motion blur. - PCursorPosProvider _pCpp = nullptr; - UINT64 _currentFrame = UINT64_MAX; - bool _cutMotionBlur = false; + public: + virtual void Update(); + virtual void UpdateUsingViewDesc(CGI::RcViewDesc viewDesc); + virtual void UpdateUsingHeadPose(Math::RcPose pose); + void UpdateZNearFar(); + void UpdateView(); + void UpdateVP(); - public: - void operator=(const MainCamera& that); + // Frustum: + void SetFrustumNear(float zNear); + void SetFrustumFar(float zFar); + Math::RFrustum GetFrustum() { return _frustum; } - virtual void Update() override; - virtual void UpdateUsingViewDesc(CGI::RcViewDesc viewDesc) override; - virtual void UpdateUsingHeadPose(Math::RcPose pose); - void UpdateVP(); + // Positions: + RcPoint3 GetEyePosition() const { return _eyePos; } + RcPoint3 GetAtPosition() const { return _atPos; } + void MoveEyeTo(RcPoint3 pos) { _update |= Update::v; _eyePos = pos; } + void MoveAtTo(RcPoint3 pos) { _update |= Update::v; _atPos = pos; } - // Motion blur: - RcMatrix4 GetMatrixPrevVP() const { return _matPrevVP; } - float ComputeMotionBlur(RcPoint3 pos, RcPoint3 posPrev) const; - void CutMotionBlur() { _cutMotionBlur = true; } + // Directions: + RcVector3 GetFrontDirection() const { return _frontDir; } + RcVector3 GetUpDirection() const { return _upDir; } + void SetUpDirection(RcVector3 dir) { _update |= Update::v; _upDir = dir; } + float ComputeYaw() const; - // Picking: - void SetCursorPosProvider(PCursorPosProvider p) { _pCpp = p; } - void GetPickingRay(RPoint3 pos, RVector3 dir) const; - }; - VERUS_TYPEDEFS(MainCamera); - } + // Matrices: + RcTransform3 GetMatrixV() const { return _matV; } + RcTransform3 GetMatrixInvV() const { return _matInvV; } + RcMatrix4 GetMatrixP() const { return _matP; } + RcMatrix4 GetMatrixInvP() const { return _matInvP; } + RcMatrix4 GetMatrixVP() const { return _matVP; } + + // Perspective: + float GetYFov() const { return _yFov; } + void SetYFov(float yFov) { _update |= Update::p; _yFov = yFov; } + void SetXFov(float xFov); // Set correct aspect ratio before calling this method. + float GetAspectRatio() const { return _aspectRatio; } + void SetAspectRatio(float aspectRatio) { _update |= Update::p; _aspectRatio = aspectRatio; } + float GetZNear() const { return _zNear; } + void SetZNear(float zNear) { _update |= Update::p; _zNear = zNear; } + float GetZFar() const { return _zFar; } + void SetZFar(float zFar) { _update |= Update::p; _zFar = zFar; } + float GetFovScale() const { return _fovScale; } // For converting offsets in meters to offsets in texture coords. + Vector4 GetZNearFarEx() const; + + // Ortho: + float GetXMag() const { return _xMag; } + float GetYMag() const { return _yMag; } + void SetXMag(float xMag) { _update |= Update::p; _xMag = (0 == xMag) ? _aspectRatio * _yMag : xMag; } + void SetYMag(float yMag) { _update |= Update::p; _yMag = yMag; } + + // Reflection, water, special effects: + void EnableReflectionMode(); + void GetClippingSpacePlane(RVector4 plane) const; + void ExcludeWaterLine(float h = 0.25f); + + // Motion: + void ApplyMotion(CSZ boneName, Anim::RMotion motion, float time); + void BakeMotion(CSZ boneName, Anim::RMotion motion, int frame); + + // State: + virtual void SaveState(int slot); + virtual void LoadState(int slot); + }; + VERUS_TYPEDEFS(Camera); + + // The interface for getting the cursor's position. + struct CursorPosProvider + { + virtual void GetPos(int& x, int& y) = 0; + }; + VERUS_TYPEDEFS(CursorPosProvider); + + // More advanced camera, used to show the world to the user. With motion blur. + class MainCamera : public Camera + { + Matrix4 _matPrevVP = Matrix4::identity(); // For motion blur. + PCursorPosProvider _pCpp = nullptr; + UINT64 _currentFrame = UINT64_MAX; + bool _cutMotionBlur = false; + + public: + void operator=(const MainCamera& that); + + virtual void Update() override; + virtual void UpdateUsingViewDesc(CGI::RcViewDesc viewDesc) override; + virtual void UpdateUsingHeadPose(Math::RcPose pose); + void UpdateVP(); + + // Motion blur: + RcMatrix4 GetMatrixPrevVP() const { return _matPrevVP; } + float ComputeMotionBlur(RcPoint3 pos, RcPoint3 posPrev) const; + void CutMotionBlur() { _cutMotionBlur = true; } + + // Picking: + void SetCursorPosProvider(PCursorPosProvider p) { _pCpp = p; } + void GetPickingRay(RPoint3 pos, RVector3 dir) const; + }; + VERUS_TYPEDEFS(MainCamera); } diff --git a/Verus/src/World/CubeMapBaker.h b/Verus/src/World/CubeMapBaker.h index 8d256e9..6ea8d15 100644 --- a/Verus/src/World/CubeMapBaker.h +++ b/Verus/src/World/CubeMapBaker.h @@ -1,49 +1,46 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class CubeMapBaker : public Object { - class CubeMapBaker : public Object + public: + enum TEX { - public: - enum TEX - { - TEX_COLOR, - TEX_DEPTH, - TEX_COUNT - }; - - private: - Point3 _center; - CGI::TexturePwns _tex; - CGI::RPHandle _rph; - CGI::FBHandle _fbh[+CGI::CubeMapFace::count]; - MainCamera _passCamera; - PCamera _pPrevPassCamera = nullptr; - int _side = 0; - bool _baking = false; - - public: - CubeMapBaker(); - ~CubeMapBaker(); - - void Init(int side = 512); - void Done(); - - // - void BeginEnvMap(CGI::CubeMapFace cubeMapFace, RcPoint3 center); - void EndEnvMap(); - bool IsBaking() const { return _baking; } - CGI::RPHandle GetRenderPassHandle() const { return _rph; } - // - - CGI::TexturePtr GetColorTexture(); - CGI::TexturePtr GetDepthTexture(); - - RcPoint3 GetCenter() const { return _center; } + TEX_COLOR, + TEX_DEPTH, + TEX_COUNT }; - VERUS_TYPEDEFS(CubeMapBaker); - } + + private: + Point3 _center; + CGI::TexturePwns _tex; + CGI::RPHandle _rph; + CGI::FBHandle _fbh[+CGI::CubeMapFace::count]; + MainCamera _passCamera; + PCamera _pPrevPassCamera = nullptr; + int _side = 0; + bool _baking = false; + + public: + CubeMapBaker(); + ~CubeMapBaker(); + + void Init(int side = 512); + void Done(); + + // + void BeginEnvMap(CGI::CubeMapFace cubeMapFace, RcPoint3 center); + void EndEnvMap(); + bool IsBaking() const { return _baking; } + CGI::RPHandle GetRenderPassHandle() const { return _rph; } + // + + CGI::TexturePtr GetColorTexture(); + CGI::TexturePtr GetDepthTexture(); + + RcPoint3 GetCenter() const { return _center; } + }; + VERUS_TYPEDEFS(CubeMapBaker); } diff --git a/Verus/src/World/EditorOverlays.h b/Verus/src/World/EditorOverlays.h index b8a43fc..e08912b 100644 --- a/Verus/src/World/EditorOverlays.h +++ b/Verus/src/World/EditorOverlays.h @@ -1,53 +1,50 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class EditorOverlays : public Singleton, public Object { - class EditorOverlays : public Singleton, public Object + private: + struct Vertex { - private: - struct Vertex + Point3 _pos; + UINT32 _color; + + Vertex() {} + Vertex(RcPoint3 pos, UINT32 color) { - Point3 _pos; - UINT32 _color; - - Vertex() {} - Vertex(RcPoint3 pos, UINT32 color) - { - _pos = pos; - _color = color; - } - }; - - Vector _vBasis; - Vector _vBox; - Vector _vCircle; - Vector _vGrid; - Vector _vLight; - Mesh _sphere; - - public: - EditorOverlays(); - ~EditorOverlays(); - - void Init(); - void Done(); - - void DrawBasis(PcTransform3 pMat = nullptr, int axis = -1, bool depthTestEnable = true, UINT32 middleColor = 0); - void DrawBox(PcTransform3 pMat = nullptr, UINT32 color = 0); - void DrawCircle(PcTransform3 pMat, float radius, UINT32 color); - void DrawTerrainCircle(RcPoint3 pos, float radius, UINT32 color, RTerrain terrain); - void DrawGrid(); - void DrawLight(RcPoint3 pos, UINT32 color = 0, PcPoint3 pTarget = nullptr); - void DrawSphere(RcPoint3 pos, float r, UINT32 color, CGI::CommandBufferPtr cb); - - static UINT32 GetBasisColorX(bool linear = false, int alpha = 255); - static UINT32 GetBasisColorY(bool linear = false, int alpha = 255); - static UINT32 GetBasisColorZ(bool linear = false, int alpha = 255); - static UINT32 GetLightColor(int alpha = 255); + _pos = pos; + _color = color; + } }; - VERUS_TYPEDEFS(EditorOverlays); - } + + Vector _vBasis; + Vector _vBox; + Vector _vCircle; + Vector _vGrid; + Vector _vLight; + Mesh _sphere; + + public: + EditorOverlays(); + ~EditorOverlays(); + + void Init(); + void Done(); + + void DrawBasis(PcTransform3 pMat = nullptr, int axis = -1, bool depthTestEnable = true, UINT32 middleColor = 0); + void DrawBox(PcTransform3 pMat = nullptr, UINT32 color = 0); + void DrawCircle(PcTransform3 pMat, float radius, UINT32 color); + void DrawTerrainCircle(RcPoint3 pos, float radius, UINT32 color, RTerrain terrain); + void DrawGrid(); + void DrawLight(RcPoint3 pos, UINT32 color = 0, PcPoint3 pTarget = nullptr); + void DrawSphere(RcPoint3 pos, float r, UINT32 color, CGI::CommandBufferPtr cb); + + static UINT32 GetBasisColorX(bool linear = false, int alpha = 255); + static UINT32 GetBasisColorY(bool linear = false, int alpha = 255); + static UINT32 GetBasisColorZ(bool linear = false, int alpha = 255); + static UINT32 GetLightColor(int alpha = 255); + }; + VERUS_TYPEDEFS(EditorOverlays); } diff --git a/Verus/src/World/EditorTerrain.h b/Verus/src/World/EditorTerrain.h index 92c2848..afd9a5d 100644 --- a/Verus/src/World/EditorTerrain.h +++ b/Verus/src/World/EditorTerrain.h @@ -1,44 +1,41 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + enum TerrainSplatMode { - enum TerrainSplatMode - { - solid, - grad, - normal, - inversedNormal, - rand - }; + solid, + grad, + normal, + inversedNormal, + rand + }; - class EditorTerrain : public Terrain - { - public: - void ConvertToBufferCoords(const float xz[2], int ij[2]) const; - glm::int4 ComputeBrushRect(const int ij[2], int radius) const; + class EditorTerrain : public Terrain + { + public: + void ConvertToBufferCoords(const float xz[2], int ij[2]) const; + glm::int4 ComputeBrushRect(const int ij[2], int radius) const; - // Height: - void SmoothenHeight(short stepSize); - void ApplyBrushHeight(const float xz[2], int radius, int strength); - void ApplyBrushFlatten(const float xz[2], int radius, int strength, bool useNormal = false, PcVector3 pNormal = nullptr, const float* pHeight = nullptr); - void ApplyBrushSmoothen(const float xz[2], int radius, int strength); + // Height: + void SmoothenHeight(short stepSize); + void ApplyBrushHeight(const float xz[2], int radius, int strength); + void ApplyBrushFlatten(const float xz[2], int radius, int strength, bool useNormal = false, PcVector3 pNormal = nullptr, const float* pHeight = nullptr); + void ApplyBrushSmoothen(const float xz[2], int radius, int strength); - // Normals: - void UpdateNormalsForArea(const glm::int4& rc); + // Normals: + void UpdateNormalsForArea(const glm::int4& rc); - // Splat: - void SplatTileAt(const int ij[2], int channel, int strength); - void SplatTileAtEx(const int ij[2], int layer, float maskValue, bool extended = false); - void SwapSplatLayersAt(const int ij[2], int a, int b); - bool IsSplatChannelBlankAt(const int ij[2], int channel) const; - bool CanSplatTileAt(const int ij[2], int layer) const; - void ApplyBrushSplat(const float xz[2], int layer, int radius, float strength, - TerrainSplatMode mode = TerrainSplatMode::solid, const float* pMask = nullptr, bool updateTexture = true); - void SplatFromFile(CSZ url, int layer); - }; - VERUS_TYPEDEFS(EditorTerrain); - } + // Splat: + void SplatTileAt(const int ij[2], int channel, int strength); + void SplatTileAtEx(const int ij[2], int layer, float maskValue, bool extended = false); + void SwapSplatLayersAt(const int ij[2], int a, int b); + bool IsSplatChannelBlankAt(const int ij[2], int channel) const; + bool CanSplatTileAt(const int ij[2], int layer) const; + void ApplyBrushSplat(const float xz[2], int layer, int radius, float strength, + TerrainSplatMode mode = TerrainSplatMode::solid, const float* pMask = nullptr, bool updateTexture = true); + void SplatFromFile(CSZ url, int layer); + }; + VERUS_TYPEDEFS(EditorTerrain); } diff --git a/Verus/src/World/Forest.h b/Verus/src/World/Forest.h index 8ae6ee0..1ea1ecb 100644 --- a/Verus/src/World/Forest.h +++ b/Verus/src/World/Forest.h @@ -1,280 +1,277 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class Forest : public Object, public ScatterDelegate, public Math::OctreeDelegate { - class Forest : public Object, public ScatterDelegate, public Math::OctreeDelegate - { #include "../Shaders/DS_Forest.inc.hlsl" #include "../Shaders/SimpleForest.inc.hlsl" - enum SHADER - { - SHADER_MAIN, - SHADER_SIMPLE, - SHADER_COUNT - }; - - enum PIPE - { - PIPE_MAIN, - PIPE_DEPTH, - PIPE_SIMPLE_ENV_MAP, - PIPE_SIMPLE_PLANAR_REF, - PIPE_MESH_BAKE, - PIPE_COUNT - }; - - public: - enum SCATTER_TYPE - { - SCATTER_TYPE_100, - SCATTER_TYPE_50, - SCATTER_TYPE_25, - SCATTER_TYPE_20, - SCATTER_TYPE_15, - SCATTER_TYPE_10, - SCATTER_TYPE_5, - SCATTER_TYPE_3, - SCATTER_TYPE_COUNT - }; - - static const int s_scatterSide = 32; - - private: - struct Vertex - { - glm::vec3 _pos; - half _tc[2]; // {psize, angle} - }; - VERUS_TYPEDEFS(Vertex); - - class BakedChunk - { - public: - Math::Bounds _bounds; - Vector _vSprites; - int _vbOffset = 0; - bool _visible = false; - }; - VERUS_TYPEDEFS(BakedChunk); - - class CollisionPlant - { - public: - int _id = -1; - int _poolBlockIndex = -1; - - int GetID() const { return _id; } - }; - VERUS_TYPEDEFS(CollisionPlant); - - class alignas(VERUS_MEMORY_ALIGNMENT) CollisionPoolBlock - { - public: - BYTE _data[sizeof(btCompoundShape) + 2 * sizeof(btUniformScalingShape) + sizeof(btDefaultMotionState) + sizeof(btRigidBody)]; - bool _reserved = false; - - bool IsReserved() const { return _reserved; } - void Reserve() { _reserved = true; } - void Free() { _reserved = false; } - - btCompoundShape* GetCompoundShape() - { - return reinterpret_cast(&_data[0]); - } - btUniformScalingShape* GetUniformScalingShapeForTrunk() - { - return reinterpret_cast(&_data[sizeof(btCompoundShape)]); - } - btUniformScalingShape* GetUniformScalingShapeForBranches() - { - return reinterpret_cast(&_data[sizeof(btCompoundShape) + sizeof(btUniformScalingShape)]); - } - btDefaultMotionState* GetDefaultMotionState() - { - return reinterpret_cast(&_data[sizeof(btCompoundShape) + 2 * sizeof(btUniformScalingShape)]); - } - btRigidBody* GetRigidBody() - { - return reinterpret_cast(&_data[sizeof(btCompoundShape) + 2 * sizeof(btUniformScalingShape) + sizeof(btDefaultMotionState)]); - } - }; - VERUS_TYPEDEFS(CollisionPoolBlock); - - class Plant - { - public: - enum TEX - { - TEX_GBUFFER_0, - TEX_GBUFFER_1, - TEX_GBUFFER_2, - TEX_GBUFFER_3, - TEX_COUNT - }; - - String _url; - Mesh _mesh; - MaterialPwn _material; - CGI::TexturePwns _tex; - CGI::CSHandle _csh; - CGI::CSHandle _cshSimple; - LocalPtr _pConvexHullShapeForTrunk; - LocalPtr _pConvexHullShapeForBranches; - Vector _vBakedChunks; - Vector _vScales; - float _alignToNormal = 1; - float _maxScale = 0; - float _maxSize = 0; - float _windBending = 1; - float _hullSplitU = -1; - char _allowedNormal = 116; - - float GetSize() const; - }; - VERUS_TYPEDEFS(Plant); - - class LayerData - { - public: - char _plants[SCATTER_TYPE_COUNT]; - BYTE _occlusion[s_scatterSide * s_scatterSide]; - - LayerData() - { - std::fill(_plants, _plants + SCATTER_TYPE_COUNT, -1); - std::fill(_occlusion, _occlusion + sizeof(_occlusion), 0xFF); - } - }; - VERUS_TYPEDEFS(LayerData); - - class DrawPlant - { - public: - Matrix3 _basis = Matrix3::identity(); - Point3 _pos = Point3(0); - Vector3 _pushBack = Vector3(0); - float _scale = 1; - float _angle = 0; - float _distToEyeSq = 0; - float _windBending = 0; - int _plantIndex = 0; - }; - VERUS_TYPEDEFS(DrawPlant); - - static CGI::ShaderPwns s_shader; - static UB_ForestVS s_ubForestVS; - static UB_ForestFS s_ubForestFS; - static UB_SimpleForestVS s_ubSimpleForestVS; - static UB_SimpleForestFS s_ubSimpleForestFS; - - PTerrain _pTerrain = nullptr; - CGI::GeometryPwn _geo; - CGI::PipelinePwns _pipe; - Math::Octree _octree; - Scatter _scatter; - Vector _vPlants; - Vector _vLayerData; - Vector _vDrawPlants; - DifferenceVector _vCollisionPlants; - Pool _vCollisionPool; - const float _margin = 1.1f; - float _maxDistForModels = 100; - float _maxDistForChunks = 1000; - float _tessDist = 50; - float _maxSizeAll = 0; - float _phaseY = 0; - float _phaseXZ = 0; - int _capacity = 10000; - int _visibleCount = 0; - int _totalPlantCount = 0; - bool _async_initPlants = false; - - public: - class PlantDesc - { - public: - CSZ _url = nullptr; - float _alignToNormal = 1; - float _minScale = 0.8f; - float _maxScale = 1.25f; - float _windBending = 1; - float _hullSplitU = -1; - char _allowedNormal = 116; - - void Set( - CSZ url, - float alignToNormal = 1, - float minScale = 0.8f, - float maxScale = 1.25f, - float windBending = 1, - float hullSplitU = -1, - char allowedNormal = 116) - { - _url = url; - _alignToNormal = alignToNormal; - _minScale = minScale; - _maxScale = maxScale; - _windBending = windBending; - _hullSplitU = hullSplitU; - _allowedNormal = allowedNormal; - } - }; - VERUS_TYPEDEFS(PlantDesc); - - class LayerDesc - { - public: - PlantDesc _forType[SCATTER_TYPE_COUNT]; - - void Reset() { *this = LayerDesc(); } - }; - VERUS_TYPEDEFS(LayerDesc); - - Forest(); - ~Forest(); - - static void InitStatic(); - static void DoneStatic(); - - void Init(PTerrain pTerrain, CSZ url = nullptr); - void Done(); - - void ResetInstanceCount(); - void Update(); - void Layout(bool reflection = false); - void SortVisible(); - void Draw(bool allowTess = true); - VERUS_P(void DrawModels(bool allowTess)); - VERUS_P(void DrawSprites()); - void DrawSimple(DrawSimpleMode mode, CGI::CubeMapFace cubeMapFace = CGI::CubeMapFace::none); - - void UpdateCollision(const Vector& vZones); - - PTerrain SetTerrain(PTerrain p) { return Utils::Swap(_pTerrain, p); } - void OnTerrainModified(); - float GetMinHeight(const int ij[2], float h) const; - - void SetLayer(int layer, RcLayerDesc desc); - VERUS_P(int FindPlant(CSZ url) const); - VERUS_P(void BakeChunksFor(RPlant plant)); - VERUS_P(void UpdateOcclusionFor(RPlant plant)); - VERUS_P(void AddOcclusionAt(const int ij[2], int layer, int radius)); - - bool LoadSprite(RPlant plant); - void BakeSprite(RPlant plant, CSZ url); - bool BakeSprites(CSZ url); - - virtual void Scatter_AddInstance(const int ij[2], int type, float x, float z, - float scale, float angle, UINT32 r) override; - - virtual Continue Octree_OnElementDetected(void* pToken, void* pUser) override; - - BYTE GetOcclusionAt(const int ij[2], int layer) const; + enum SHADER + { + SHADER_MAIN, + SHADER_SIMPLE, + SHADER_COUNT }; - VERUS_TYPEDEFS(Forest); - } + + enum PIPE + { + PIPE_MAIN, + PIPE_DEPTH, + PIPE_SIMPLE_ENV_MAP, + PIPE_SIMPLE_PLANAR_REF, + PIPE_MESH_BAKE, + PIPE_COUNT + }; + + public: + enum SCATTER_TYPE + { + SCATTER_TYPE_100, + SCATTER_TYPE_50, + SCATTER_TYPE_25, + SCATTER_TYPE_20, + SCATTER_TYPE_15, + SCATTER_TYPE_10, + SCATTER_TYPE_5, + SCATTER_TYPE_3, + SCATTER_TYPE_COUNT + }; + + static const int s_scatterSide = 32; + + private: + struct Vertex + { + glm::vec3 _pos; + half _tc[2]; // {psize, angle} + }; + VERUS_TYPEDEFS(Vertex); + + class BakedChunk + { + public: + Math::Bounds _bounds; + Vector _vSprites; + int _vbOffset = 0; + bool _visible = false; + }; + VERUS_TYPEDEFS(BakedChunk); + + class CollisionPlant + { + public: + int _id = -1; + int _poolBlockIndex = -1; + + int GetID() const { return _id; } + }; + VERUS_TYPEDEFS(CollisionPlant); + + class alignas(VERUS_MEMORY_ALIGNMENT) CollisionPoolBlock + { + public: + BYTE _data[sizeof(btCompoundShape) + 2 * sizeof(btUniformScalingShape) + sizeof(btDefaultMotionState) + sizeof(btRigidBody)]; + bool _reserved = false; + + bool IsReserved() const { return _reserved; } + void Reserve() { _reserved = true; } + void Free() { _reserved = false; } + + btCompoundShape* GetCompoundShape() + { + return reinterpret_cast(&_data[0]); + } + btUniformScalingShape* GetUniformScalingShapeForTrunk() + { + return reinterpret_cast(&_data[sizeof(btCompoundShape)]); + } + btUniformScalingShape* GetUniformScalingShapeForBranches() + { + return reinterpret_cast(&_data[sizeof(btCompoundShape) + sizeof(btUniformScalingShape)]); + } + btDefaultMotionState* GetDefaultMotionState() + { + return reinterpret_cast(&_data[sizeof(btCompoundShape) + 2 * sizeof(btUniformScalingShape)]); + } + btRigidBody* GetRigidBody() + { + return reinterpret_cast(&_data[sizeof(btCompoundShape) + 2 * sizeof(btUniformScalingShape) + sizeof(btDefaultMotionState)]); + } + }; + VERUS_TYPEDEFS(CollisionPoolBlock); + + class Plant + { + public: + enum TEX + { + TEX_GBUFFER_0, + TEX_GBUFFER_1, + TEX_GBUFFER_2, + TEX_GBUFFER_3, + TEX_COUNT + }; + + String _url; + Mesh _mesh; + MaterialPwn _material; + CGI::TexturePwns _tex; + CGI::CSHandle _csh; + CGI::CSHandle _cshSimple; + LocalPtr _pConvexHullShapeForTrunk; + LocalPtr _pConvexHullShapeForBranches; + Vector _vBakedChunks; + Vector _vScales; + float _alignToNormal = 1; + float _maxScale = 0; + float _maxSize = 0; + float _windBending = 1; + float _hullSplitU = -1; + char _allowedNormal = 116; + + float GetSize() const; + }; + VERUS_TYPEDEFS(Plant); + + class LayerData + { + public: + char _plants[SCATTER_TYPE_COUNT]; + BYTE _occlusion[s_scatterSide * s_scatterSide]; + + LayerData() + { + std::fill(_plants, _plants + SCATTER_TYPE_COUNT, -1); + std::fill(_occlusion, _occlusion + sizeof(_occlusion), 0xFF); + } + }; + VERUS_TYPEDEFS(LayerData); + + class DrawPlant + { + public: + Matrix3 _basis = Matrix3::identity(); + Point3 _pos = Point3(0); + Vector3 _pushBack = Vector3(0); + float _scale = 1; + float _angle = 0; + float _distToEyeSq = 0; + float _windBending = 0; + int _plantIndex = 0; + }; + VERUS_TYPEDEFS(DrawPlant); + + static CGI::ShaderPwns s_shader; + static UB_ForestVS s_ubForestVS; + static UB_ForestFS s_ubForestFS; + static UB_SimpleForestVS s_ubSimpleForestVS; + static UB_SimpleForestFS s_ubSimpleForestFS; + + PTerrain _pTerrain = nullptr; + CGI::GeometryPwn _geo; + CGI::PipelinePwns _pipe; + Math::Octree _octree; + Scatter _scatter; + Vector _vPlants; + Vector _vLayerData; + Vector _vDrawPlants; + DifferenceVector _vCollisionPlants; + Pool _vCollisionPool; + const float _margin = 1.1f; + float _maxDistForModels = 100; + float _maxDistForChunks = 1000; + float _tessDist = 50; + float _maxSizeAll = 0; + float _phaseY = 0; + float _phaseXZ = 0; + int _capacity = 10000; + int _visibleCount = 0; + int _totalPlantCount = 0; + bool _async_initPlants = false; + + public: + class PlantDesc + { + public: + CSZ _url = nullptr; + float _alignToNormal = 1; + float _minScale = 0.8f; + float _maxScale = 1.25f; + float _windBending = 1; + float _hullSplitU = -1; + char _allowedNormal = 116; + + void Set( + CSZ url, + float alignToNormal = 1, + float minScale = 0.8f, + float maxScale = 1.25f, + float windBending = 1, + float hullSplitU = -1, + char allowedNormal = 116) + { + _url = url; + _alignToNormal = alignToNormal; + _minScale = minScale; + _maxScale = maxScale; + _windBending = windBending; + _hullSplitU = hullSplitU; + _allowedNormal = allowedNormal; + } + }; + VERUS_TYPEDEFS(PlantDesc); + + class LayerDesc + { + public: + PlantDesc _forType[SCATTER_TYPE_COUNT]; + + void Reset() { *this = LayerDesc(); } + }; + VERUS_TYPEDEFS(LayerDesc); + + Forest(); + ~Forest(); + + static void InitStatic(); + static void DoneStatic(); + + void Init(PTerrain pTerrain, CSZ url = nullptr); + void Done(); + + void ResetInstanceCount(); + void Update(); + void Layout(bool reflection = false); + void SortVisible(); + void Draw(bool allowTess = true); + VERUS_P(void DrawModels(bool allowTess)); + VERUS_P(void DrawSprites()); + void DrawSimple(DrawSimpleMode mode, CGI::CubeMapFace cubeMapFace = CGI::CubeMapFace::none); + + void UpdateCollision(const Vector& vZones); + + PTerrain SetTerrain(PTerrain p) { return Utils::Swap(_pTerrain, p); } + void OnTerrainModified(); + float GetMinHeight(const int ij[2], float h) const; + + void SetLayer(int layer, RcLayerDesc desc); + VERUS_P(int FindPlant(CSZ url) const); + VERUS_P(void BakeChunksFor(RPlant plant)); + VERUS_P(void UpdateOcclusionFor(RPlant plant)); + VERUS_P(void AddOcclusionAt(const int ij[2], int layer, int radius)); + + bool LoadSprite(RPlant plant); + void BakeSprite(RPlant plant, CSZ url); + bool BakeSprites(CSZ url); + + virtual void Scatter_AddInstance(const int ij[2], int type, float x, float z, + float scale, float angle, UINT32 r) override; + + virtual Continue Octree_OnElementDetected(void* pToken, void* pUser) override; + + BYTE GetOcclusionAt(const int ij[2], int layer) const; + }; + VERUS_TYPEDEFS(Forest); } diff --git a/Verus/src/World/Grass.h b/Verus/src/World/Grass.h index b6b3da4..9fb41a7 100644 --- a/Verus/src/World/Grass.h +++ b/Verus/src/World/Grass.h @@ -1,118 +1,115 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class Grass : public Object, public Math::QuadtreeIntegralDelegate { - class Grass : public Object, public Math::QuadtreeIntegralDelegate - { - public: + public: #include "../Shaders/DS_Grass.inc.hlsl" - enum PIPE - { - PIPE_MAIN, - PIPE_BILLBOARDS, - PIPE_COUNT - }; - - struct Vertex - { - short _pos[4]; // {xyz, phaseShift}. - short _tc[4]; // {tc0, center.xz}. - }; - VERUS_TYPEDEFS(Vertex); - - struct PerInstanceData - { - short _patchPos[4]; - }; - VERUS_TYPEDEFS(PerInstanceData); - - struct Patch - { - short _i; - short _j; - short _h; - short _type; - }; - VERUS_TYPEDEFS(Patch); - - class Magnet - { - public: - Point3 _pos; - float _radius = 1; - float _radiusSq = 1; - float _radiusSqInv = 1; - float _strength = 1; - bool _active = false; - }; - VERUS_TYPEDEFS(Magnet); - - static const int s_maxBushTypes = 16; - - private: - static CGI::ShaderPwn s_shader; - static UB_GrassVS s_ubGrassVS; - static UB_GrassFS s_ubGrassFS; - - CGI::GeometryPwn _geo; - CGI::PipelinePwns _pipe; - CGI::TexturePwn _tex; - CGI::TextureRAM _texLoaded[s_maxBushTypes]; - PTerrain _pTerrain = nullptr; - Vector _vPatchMeshVB; - Vector _vPatchMeshIB; - Vector _vInstanceBuffer; - Vector _vTextureSubresData; - Vector _vPatches; - Vector _vMagnets; - Physics::Spring _warpSpring = Physics::Spring(55, 2.5f); - float _turbulence = 0; - int _mapSide = 0; - int _mapShift = 0; - int _vertCount = 0; - int _bbVertCount = 0; - int _instanceCount = 0; - int _visiblePatchCount = 0; - CGI::CSHandle _cshVS; - CGI::CSHandle _cshFS; - char _bushTexCoords[s_maxBushTypes][8][2]; - UINT32 _bushMask = 0; - float _phase = 0; - - public: - Grass(); - ~Grass(); - - static void InitStatic(); - static void DoneStatic(); - - void Init(RTerrain terrain, CSZ atlasUrl = nullptr); - void Done(); - - void ResetInstanceCount(); - void Update(); - void Layout(); - void Draw(); - - virtual void QuadtreeIntegral_OnElementDetected(const short ij[2], RcPoint3 center) override; - virtual void QuadtreeIntegral_GetHeights(const short ij[2], float height[2]) override; - - VERUS_P(void CreateBuffers()); - - void ResetAllTextures(); - void LoadLayersFromFile(CSZ url = nullptr); - void SetTexture(int layer, CSZ url, CSZ url2 = nullptr); - VERUS_P(void OnTextureLoaded(int layer)); - void SaveTexture(CSZ url); - - int BeginMagnet(RcPoint3 pos, float radius); - void EndMagnet(int index); - void UpdateMagnet(int index, RcPoint3 pos, float radius = 0); + enum PIPE + { + PIPE_MAIN, + PIPE_BILLBOARDS, + PIPE_COUNT }; - VERUS_TYPEDEFS(Grass); - } + + struct Vertex + { + short _pos[4]; // {xyz, phaseShift}. + short _tc[4]; // {tc0, center.xz}. + }; + VERUS_TYPEDEFS(Vertex); + + struct PerInstanceData + { + short _patchPos[4]; + }; + VERUS_TYPEDEFS(PerInstanceData); + + struct Patch + { + short _i; + short _j; + short _h; + short _type; + }; + VERUS_TYPEDEFS(Patch); + + class Magnet + { + public: + Point3 _pos; + float _radius = 1; + float _radiusSq = 1; + float _radiusSqInv = 1; + float _strength = 1; + bool _active = false; + }; + VERUS_TYPEDEFS(Magnet); + + static const int s_maxBushTypes = 16; + + private: + static CGI::ShaderPwn s_shader; + static UB_GrassVS s_ubGrassVS; + static UB_GrassFS s_ubGrassFS; + + CGI::GeometryPwn _geo; + CGI::PipelinePwns _pipe; + CGI::TexturePwn _tex; + CGI::TextureRAM _texLoaded[s_maxBushTypes]; + PTerrain _pTerrain = nullptr; + Vector _vPatchMeshVB; + Vector _vPatchMeshIB; + Vector _vInstanceBuffer; + Vector _vTextureSubresData; + Vector _vPatches; + Vector _vMagnets; + Physics::Spring _warpSpring = Physics::Spring(55, 2.5f); + float _turbulence = 0; + int _mapSide = 0; + int _mapShift = 0; + int _vertCount = 0; + int _bbVertCount = 0; + int _instanceCount = 0; + int _visiblePatchCount = 0; + CGI::CSHandle _cshVS; + CGI::CSHandle _cshFS; + char _bushTexCoords[s_maxBushTypes][8][2]; + UINT32 _bushMask = 0; + float _phase = 0; + + public: + Grass(); + ~Grass(); + + static void InitStatic(); + static void DoneStatic(); + + void Init(RTerrain terrain, CSZ atlasUrl = nullptr); + void Done(); + + void ResetInstanceCount(); + void Update(); + void Layout(); + void Draw(); + + virtual void QuadtreeIntegral_OnElementDetected(const short ij[2], RcPoint3 center) override; + virtual void QuadtreeIntegral_GetHeights(const short ij[2], float height[2]) override; + + VERUS_P(void CreateBuffers()); + + void ResetAllTextures(); + void LoadLayersFromFile(CSZ url = nullptr); + void SetTexture(int layer, CSZ url, CSZ url2 = nullptr); + VERUS_P(void OnTextureLoaded(int layer)); + void SaveTexture(CSZ url); + + int BeginMagnet(RcPoint3 pos, float radius); + void EndMagnet(int index); + void UpdateMagnet(int index, RcPoint3 pos, float radius = 0); + }; + VERUS_TYPEDEFS(Grass); } diff --git a/Verus/src/World/LightMapBaker.h b/Verus/src/World/LightMapBaker.h index 0c34565..228ee8e 100644 --- a/Verus/src/World/LightMapBaker.h +++ b/Verus/src/World/LightMapBaker.h @@ -1,163 +1,160 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + struct DrawLumelDesc { - struct DrawLumelDesc + Transform3 _matV; + Point3 _eyePos; + Vector3 _frontDir; + }; + VERUS_TYPEDEFS(DrawLumelDesc); + + struct LightMapBakerDelegate + { + virtual void LightMapBaker_Draw(CGI::CubeMapFace cubeMapFace, RcDrawLumelDesc drawLumelDesc) = 0; + }; + VERUS_TYPEDEFS(LightMapBakerDelegate); + + class LightMapBaker : public Singleton, public Object, public Math::QuadtreeDelegate + { + static const int s_batchSize = 400; + static const int s_maxLayers = 8; + + struct Vertex { - Transform3 _matV; - Point3 _eyePos; - Vector3 _frontDir; + glm::vec3 _pos; + glm::vec3 _nrm; + glm::vec2 _tc; }; - VERUS_TYPEDEFS(DrawLumelDesc); + VERUS_TYPEDEFS(Vertex); - struct LightMapBakerDelegate + struct Face { - virtual void LightMapBaker_Draw(CGI::CubeMapFace cubeMapFace, RcDrawLumelDesc drawLumelDesc) = 0; + Vertex _v[3]; }; - VERUS_TYPEDEFS(LightMapBakerDelegate); + VERUS_TYPEDEFS(Face); - class LightMapBaker : public Singleton, public Object, public Math::QuadtreeDelegate + struct Queued { - static const int s_batchSize = 400; - static const int s_maxLayers = 8; - - struct Vertex - { - glm::vec3 _pos; - glm::vec3 _nrm; - glm::vec2 _tc; - }; - VERUS_TYPEDEFS(Vertex); - - struct Face - { - Vertex _v[3]; - }; - VERUS_TYPEDEFS(Face); - - struct Queued - { - Point3 _pos; - Vector3 _nrm; - void* _pDst; - }; - VERUS_TYPEDEFS(Queued); - - public: - enum PIPE - { - PIPE_MESH_SIMPLE_BAKE_AO, - PIPE_MESH_SIMPLE_BAKE_AO_INSTANCED, - PIPE_MESH_SIMPLE_BAKE_AO_ROBOTIC, - PIPE_MESH_SIMPLE_BAKE_AO_SKINNED, - PIPE_HEMICUBE_MASK, - PIPE_QUAD, - PIPE_COUNT - }; - - enum TEX - { - TEX_DEPTH, - TEX_DUMMY, - TEX_COUNT - }; - - enum class Mode : int - { - idle, - faces, - ambientOcclusion - }; - - struct Stats - { - String _info; - float _progress = 0; - float _startTime = 0; - int _maxLayer = 0; - }; - VERUS_TYPEDEFS(Stats); - - struct Desc - { - PcMesh _pMesh = nullptr; - CSZ _pathname = nullptr; - Mode _mode = Mode::idle; - int _texCoordSet = 0; - int _texWidth = 256; - int _texHeight = 256; - int _texLumelSide = 128; - float _distance = 2; - float _bias = 0.001f; - }; - VERUS_TYPEDEFS(Desc); - - private: - Math::Quadtree _quadtree; - PLightMapBakerDelegate _pDelegate = nullptr; - Vector _vFaces; - Vector _vMap; - Vector _vQueued[CGI::BaseRenderer::s_ringBufferSize]; - String _pathname; - Desc _desc; - CGI::PipelinePwns _pipe; - CGI::TexturePwns _tex; - CGI::TexturePwns _texColor[CGI::BaseRenderer::s_ringBufferSize]; - CGI::RPHandle _rph; - CGI::FBHandle _fbh[CGI::BaseRenderer::s_ringBufferSize][s_batchSize]; - CGI::CSHandle _cshQuad[CGI::BaseRenderer::s_ringBufferSize]; - CGI::CSHandle _cshHemicubeMask; - int _repsPerUpdate = 1; - int _drawEmptyState = 0; - int _queuedCount[CGI::BaseRenderer::s_ringBufferSize]; - int _currentLayer = 0; - int _currentI = 0; - int _currentJ = 0; - glm::vec2 _currentUV; - float _invMapSize = 0; - float _normalizationFactor = 0; - Stats _stats; - bool _debugDraw = false; - - public: - LightMapBaker(); - ~LightMapBaker(); - - void Init(RcDesc desc); - void Done(); - - void Update(); - void Draw(); - - PLightMapBakerDelegate SetDelegate(PLightMapBakerDelegate p) { return Utils::Swap(_pDelegate, p); } - - void DrawEmpty(); - void DrawHemicubeMask(); - void DrawLumel(RcPoint3 pos, RcVector3 nrm, int batchIndex); - - RcDesc GetDesc() const { return _desc; } - - bool IsBaking() const { return Mode::idle != _desc._mode; } - Mode GetMode() const { return _desc._mode; } - - bool IsDebugDrawEnabled() const { return _debugDraw; } - void EnableDebugDraw(bool b = true) { _debugDraw = b; } - - virtual Continue Quadtree_OnElementDetected(void* pToken, void* pUser) override; - - Str GetPathname() const { return _C(_pathname); } - RcStats GetStats() const { return _stats; } - float GetProgress() const { return _stats._progress; } - - void ComputeEdgePadding(); - void Save(); - - void BindPipeline(RcMesh mesh, CGI::CommandBufferPtr cb); - void SetViewportAndScissorFor(CGI::CubeMapFace cubeMapFace, CGI::CommandBufferPtr cb); + Point3 _pos; + Vector3 _nrm; + void* _pDst; }; - VERUS_TYPEDEFS(LightMapBaker); - } + VERUS_TYPEDEFS(Queued); + + public: + enum PIPE + { + PIPE_MESH_SIMPLE_BAKE_AO, + PIPE_MESH_SIMPLE_BAKE_AO_INSTANCED, + PIPE_MESH_SIMPLE_BAKE_AO_ROBOTIC, + PIPE_MESH_SIMPLE_BAKE_AO_SKINNED, + PIPE_HEMICUBE_MASK, + PIPE_QUAD, + PIPE_COUNT + }; + + enum TEX + { + TEX_DEPTH, + TEX_DUMMY, + TEX_COUNT + }; + + enum class Mode : int + { + idle, + faces, + ambientOcclusion + }; + + struct Stats + { + String _info; + float _progress = 0; + float _startTime = 0; + int _maxLayer = 0; + }; + VERUS_TYPEDEFS(Stats); + + struct Desc + { + PcMesh _pMesh = nullptr; + CSZ _pathname = nullptr; + Mode _mode = Mode::idle; + int _texCoordSet = 0; + int _texWidth = 256; + int _texHeight = 256; + int _texLumelSide = 128; + float _distance = 2; + float _bias = 0.001f; + }; + VERUS_TYPEDEFS(Desc); + + private: + Math::Quadtree _quadtree; + PLightMapBakerDelegate _pDelegate = nullptr; + Vector _vFaces; + Vector _vMap; + Vector _vQueued[CGI::BaseRenderer::s_ringBufferSize]; + String _pathname; + Desc _desc; + CGI::PipelinePwns _pipe; + CGI::TexturePwns _tex; + CGI::TexturePwns _texColor[CGI::BaseRenderer::s_ringBufferSize]; + CGI::RPHandle _rph; + CGI::FBHandle _fbh[CGI::BaseRenderer::s_ringBufferSize][s_batchSize]; + CGI::CSHandle _cshQuad[CGI::BaseRenderer::s_ringBufferSize]; + CGI::CSHandle _cshHemicubeMask; + int _repsPerUpdate = 1; + int _drawEmptyState = 0; + int _queuedCount[CGI::BaseRenderer::s_ringBufferSize]; + int _currentLayer = 0; + int _currentI = 0; + int _currentJ = 0; + glm::vec2 _currentUV; + float _invMapSize = 0; + float _normalizationFactor = 0; + Stats _stats; + bool _debugDraw = false; + + public: + LightMapBaker(); + ~LightMapBaker(); + + void Init(RcDesc desc); + void Done(); + + void Update(); + void Draw(); + + PLightMapBakerDelegate SetDelegate(PLightMapBakerDelegate p) { return Utils::Swap(_pDelegate, p); } + + void DrawEmpty(); + void DrawHemicubeMask(); + void DrawLumel(RcPoint3 pos, RcVector3 nrm, int batchIndex); + + RcDesc GetDesc() const { return _desc; } + + bool IsBaking() const { return Mode::idle != _desc._mode; } + Mode GetMode() const { return _desc._mode; } + + bool IsDebugDrawEnabled() const { return _debugDraw; } + void EnableDebugDraw(bool b = true) { _debugDraw = b; } + + virtual Continue Quadtree_OnElementDetected(void* pToken, void* pUser) override; + + Str GetPathname() const { return _C(_pathname); } + RcStats GetStats() const { return _stats; } + float GetProgress() const { return _stats._progress; } + + void ComputeEdgePadding(); + void Save(); + + void BindPipeline(RcMesh mesh, CGI::CommandBufferPtr cb); + void SetViewportAndScissorFor(CGI::CubeMapFace cubeMapFace, CGI::CommandBufferPtr cb); + }; + VERUS_TYPEDEFS(LightMapBaker); } diff --git a/Verus/src/World/MaterialManager.cpp b/Verus/src/World/MaterialManager.cpp index 4f39721..7e2dfe7 100644 --- a/Verus/src/World/MaterialManager.cpp +++ b/Verus/src/World/MaterialManager.cpp @@ -310,15 +310,15 @@ void Material::LoadTextures(bool streamParts) String newUrl; auto ExpandPath = [this, &newUrl](CSZ url) - { - if (!strncmp(url, "./", 2)) { - newUrl = Str::GetPath(_C(_name)); - newUrl += url + 1; - return _C(newUrl); - } - return url; - }; + if (!strncmp(url, "./", 2)) + { + newUrl = Str::GetPath(_C(_name)); + newUrl += url + 1; + return _C(newUrl); + } + return url; + }; _texA.Init(ExpandPath(_dict.Find("texA")), streamParts); _texN.Init(ExpandPath(_dict.Find("texN")), streamParts); @@ -603,11 +603,11 @@ void MaterialManager::Update() { VERUS_UPDATE_ONCE_CHECK; - for (auto& x : TStoreTextures::_map) - x.second.Update(); + for (auto& [key, value] : TStoreTextures::_map) + value.Update(); - for (auto& x : TStoreMaterials::_map) - x.second.Update(); + for (auto& [key, value] : TStoreMaterials::_map) + value.Update(); } PTexture MaterialManager::InsertTexture(CSZ url) @@ -676,8 +676,8 @@ Vector MaterialManager::GetMaterialNames() const void MaterialManager::ResetPart() { - for (auto& x : TStoreTextures::_map) - x.second.ResetPart(); + for (auto& [key, value] : TStoreTextures::_map) + value.ResetPart(); } float MaterialManager::ComputePart(float distSq, float objectRadius) diff --git a/Verus/src/World/MaterialManager.h b/Verus/src/World/MaterialManager.h index 3f0adc1..264dc8a 100644 --- a/Verus/src/World/MaterialManager.h +++ b/Verus/src/World/MaterialManager.h @@ -1,223 +1,220 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class Texture : public AllocatorAware { - class Texture : public AllocatorAware + UINT64 _date = 0; + UINT64 _doneFrame = 0; + CGI::TexturePwn _texTiny; + CGI::TexturePwns<2> _texHuge; + int _refCount = 0; + int _currentHuge = 0; + float _requestedPart = 0; + bool _streamParts = false; + bool _loading = false; + + public: + Texture(); + ~Texture(); + + void Init(CSZ url, bool streamParts = false, bool sync = false, CGI::PcSamplerDesc pSamplerDesc = nullptr); + bool Done(); + + void AddRef() { _refCount++; } + + void Update(); + void UpdateStreaming(); + + CGI::TexturePtr GetTex() const; + CGI::TexturePtr GetTinyTex() const; + CGI::TexturePtr GetHugeTex() const; + + void ResetPart() { _requestedPart = FLT_MAX; } + void IncludePart(float part) { _requestedPart = Math::Min(_requestedPart, part); } + int GetPart() const; + }; + VERUS_TYPEDEFS(Texture); + + class TexturePtr : public Ptr + { + public: + void Init(CSZ url, bool streamParts = false, bool sync = false, CGI::PcSamplerDesc pSamplerDesc = nullptr); + }; + VERUS_TYPEDEFS(TexturePtr); + + class TexturePwn : public TexturePtr + { + public: + ~TexturePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(TexturePwn); + + class Material : public Object + { + public: + struct Desc { - UINT64 _date = 0; - UINT64 _doneFrame = 0; - CGI::TexturePwn _texTiny; - CGI::TexturePwns<2> _texHuge; - int _refCount = 0; - int _currentHuge = 0; - float _requestedPart = 0; - bool _streamParts = false; - bool _loading = false; - - public: - Texture(); - ~Texture(); - - void Init(CSZ url, bool streamParts = false, bool sync = false, CGI::PcSamplerDesc pSamplerDesc = nullptr); - bool Done(); - - void AddRef() { _refCount++; } - - void Update(); - void UpdateStreaming(); - - CGI::TexturePtr GetTex() const; - CGI::TexturePtr GetTinyTex() const; - CGI::TexturePtr GetHugeTex() const; - - void ResetPart() { _requestedPart = FLT_MAX; } - void IncludePart(float part) { _requestedPart = Math::Min(_requestedPart, part); } - int GetPart() const; + CSZ _name = nullptr; + bool _load = false; + bool _streamParts = true; + bool _mandatory = true; }; - VERUS_TYPEDEFS(Texture); + VERUS_TYPEDEFS(Desc); - class TexturePtr : public Ptr + enum class Blending : int + { + opaque, + alphaTest, + transparent, + colorAdd, + colorFilter + }; + + class Pick : public glm::vec4 { public: - void Init(CSZ url, bool streamParts = false, bool sync = false, CGI::PcSamplerDesc pSamplerDesc = nullptr); + Pick(); + Pick(const glm::vec4& v); + void SetColor(float r, float g, float b); + void SetAlpha(float x); + void FromString(CSZ sz); + String ToString(); }; - VERUS_TYPEDEFS(TexturePtr); - class TexturePwn : public TexturePtr - { - public: - ~TexturePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(TexturePwn); + INT64 _cshFreeFrame = -1; + String _name; + IO::Dictionary _dict; + glm::vec2 _anisoSpecDir = glm::vec2(0, 1); + float _detail = 0; + float _emission = 0; + float _nmContrast = -2; + float _roughDiffuse = 0; + glm::vec4 _solidA = glm::vec4(1, 1, 1, 0); + glm::vec4 _solidN = glm::vec4(0.5f, 0.5f, 1, 0); + glm::vec4 _solidX = glm::vec4(1, 0.5f, 0.5f, 0); + float _sssHue = 0.5f; + Pick _sssPick; + glm::vec4 _tc0ScaleBias = glm::vec4(1, 1, 0, 0); + TexturePwn _texA; + TexturePwn _texN; + TexturePwn _texX; + glm::vec4 _userColor = glm::vec4(1, 1, 1, 1); + Pick _userPick; + glm::vec2 _xAnisoSpecScaleBias = glm::vec2(1, 0); + glm::vec2 _xMetallicScaleBias = glm::vec2(1, 0); + glm::vec2 _xRoughnessScaleBias = glm::vec2(1, 0); + glm::vec2 _xWrapDiffuseScaleBias = glm::vec2(1, 0); + Blending _blending = Blending::opaque; + CGI::CSHandle _csh; + CGI::CSHandle _cshTiny; + CGI::CSHandle _cshTemp; + CGI::CSHandle _cshSimple; + int _aPart = -1; + int _nPart = -1; + int _xPart = -1; + int _refCount = 0; - class Material : public Object - { - public: - struct Desc - { - CSZ _name = nullptr; - bool _load = false; - bool _streamParts = true; - bool _mandatory = true; - }; - VERUS_TYPEDEFS(Desc); + Material(); + ~Material(); - enum class Blending : int - { - opaque, - alphaTest, - transparent, - colorAdd, - colorFilter - }; + void Init(RcDesc desc); + bool Done(); - class Pick : public glm::vec4 - { - public: - Pick(); - Pick(const glm::vec4& v); - void SetColor(float r, float g, float b); - void SetAlpha(float x); - void FromString(CSZ sz); - String ToString(); - }; + void AddRef() { _refCount++; } - INT64 _cshFreeFrame = -1; - String _name; - IO::Dictionary _dict; - glm::vec2 _anisoSpecDir = glm::vec2(0, 1); - float _detail = 0; - float _emission = 0; - float _nmContrast = -2; - float _roughDiffuse = 0; - glm::vec4 _solidA = glm::vec4(1, 1, 1, 0); - glm::vec4 _solidN = glm::vec4(0.5f, 0.5f, 1, 0); - glm::vec4 _solidX = glm::vec4(1, 0.5f, 0.5f, 0); - float _sssHue = 0.5f; - Pick _sssPick; - glm::vec4 _tc0ScaleBias = glm::vec4(1, 1, 0, 0); - TexturePwn _texA; - TexturePwn _texN; - TexturePwn _texX; - glm::vec4 _userColor = glm::vec4(1, 1, 1, 1); - Pick _userPick; - glm::vec2 _xAnisoSpecScaleBias = glm::vec2(1, 0); - glm::vec2 _xMetallicScaleBias = glm::vec2(1, 0); - glm::vec2 _xRoughnessScaleBias = glm::vec2(1, 0); - glm::vec2 _xWrapDiffuseScaleBias = glm::vec2(1, 0); - Blending _blending = Blending::opaque; - CGI::CSHandle _csh; - CGI::CSHandle _cshTiny; - CGI::CSHandle _cshTemp; - CGI::CSHandle _cshSimple; - int _aPart = -1; - int _nPart = -1; - int _xPart = -1; - int _refCount = 0; + bool operator<(const Material& that) const; - Material(); - ~Material(); + void Update(); - void Init(RcDesc desc); - bool Done(); + bool IsLoaded() const; + VERUS_P(void LoadTextures(bool streamParts)); - void AddRef() { _refCount++; } + void SetName(CSZ name) { _name = name; } - bool operator<(const Material& that) const; + String ToString(bool cleanDict = false); + void FromString(CSZ txt); - void Update(); + // Mesh interaction: + CGI::CSHandle GetComplexSetHandle() const; + CGI::CSHandle GetComplexSetHandleSimple() const; + void BindDescriptorSetTextures(); + bool UpdateMeshUniformBuffer(float motionBlur = 1, bool resolveDitheringMaskEnabled = true); + bool UpdateMeshUniformBufferSimple(); - bool IsLoaded() const; - VERUS_P(void LoadTextures(bool streamParts)); + void IncludePart(float part); + }; + VERUS_TYPEDEFS(Material); - void SetName(CSZ name) { _name = name; } + class MaterialPtr : public Ptr + { + public: + void Init(Material::RcDesc desc); + }; + VERUS_TYPEDEFS(MaterialPtr); - String ToString(bool cleanDict = false); - void FromString(CSZ txt); + class MaterialPwn : public MaterialPtr + { + public: + ~MaterialPwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(MaterialPwn); - // Mesh interaction: - CGI::CSHandle GetComplexSetHandle() const; - CGI::CSHandle GetComplexSetHandleSimple() const; - void BindDescriptorSetTextures(); - bool UpdateMeshUniformBuffer(float motionBlur = 1, bool resolveDitheringMaskEnabled = true); - bool UpdateMeshUniformBufferSimple(); + typedef StoreUnique TStoreTextures; + typedef StoreUnique TStoreMaterials; + class MaterialManager : public Singleton, public Object, private TStoreTextures, private TStoreMaterials + { + TexturePwn _texDefaultA; + TexturePwn _texDefaultN; + TexturePwn _texDefaultX; + TexturePwn _texDetail; + TexturePwn _texDetailN; + TexturePwn _texStrass; + CGI::TexturePwn _texDummyShadow; + CGI::CSHandle _cshDefault; // For missing, non-mandatory materials. + CGI::CSHandle _cshDefaultSimple; - void IncludePart(float part); - }; - VERUS_TYPEDEFS(Material); + public: + MaterialManager(); + ~MaterialManager(); - class MaterialPtr : public Ptr - { - public: - void Init(Material::RcDesc desc); - }; - VERUS_TYPEDEFS(MaterialPtr); + void Init(); + void InitCmd(); + void Done(); + void DeleteAll(); - class MaterialPwn : public MaterialPtr - { - public: - ~MaterialPwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(MaterialPwn); + void Update(); - typedef StoreUnique TStoreTextures; - typedef StoreUnique TStoreMaterials; - class MaterialManager : public Singleton, public Object, private TStoreTextures, private TStoreMaterials - { - TexturePwn _texDefaultA; - TexturePwn _texDefaultN; - TexturePwn _texDefaultX; - TexturePwn _texDetail; - TexturePwn _texDetailN; - TexturePwn _texStrass; - CGI::TexturePwn _texDummyShadow; - CGI::CSHandle _cshDefault; // For missing, non-mandatory materials. - CGI::CSHandle _cshDefaultSimple; + CGI::TexturePtr GetDefaultTexture() { return _texDefaultA->GetTex(); } + CGI::TexturePtr GetDetailTexture() { return _texDetail->GetTex(); } + CGI::TexturePtr GetDetailNTexture() { return _texDetailN->GetTex(); } + CGI::TexturePtr GetStrassTexture() { return _texStrass->GetTex(); } - public: - MaterialManager(); - ~MaterialManager(); + CGI::CSHandle GetDefaultComplexSetHandle(bool simple = false) const { return simple ? _cshDefaultSimple : _cshDefault; } - void Init(); - void InitCmd(); - void Done(); - void DeleteAll(); + // Textures: + PTexture InsertTexture(CSZ url); + PTexture FindTexture(CSZ url); + void DeleteTexture(CSZ url); + void DeleteAllTextures(); - void Update(); + // Materials: + PMaterial InsertMaterial(CSZ name); + PMaterial FindMaterial(CSZ name); + void DeleteMaterial(CSZ name); + void DeleteAllMaterials(); - CGI::TexturePtr GetDefaultTexture() { return _texDefaultA->GetTex(); } - CGI::TexturePtr GetDetailTexture() { return _texDetail->GetTex(); } - CGI::TexturePtr GetDetailNTexture() { return _texDetailN->GetTex(); } - CGI::TexturePtr GetStrassTexture() { return _texStrass->GetTex(); } + void Serialize(IO::RSeekableStream stream); + void Deserialize(IO::RStream stream); - CGI::CSHandle GetDefaultComplexSetHandle(bool simple = false) const { return simple ? _cshDefaultSimple : _cshDefault; } + Vector GetTextureNames() const; + Vector GetMaterialNames() const; - // Textures: - PTexture InsertTexture(CSZ url); - PTexture FindTexture(CSZ url); - void DeleteTexture(CSZ url); - void DeleteAllTextures(); - - // Materials: - PMaterial InsertMaterial(CSZ name); - PMaterial FindMaterial(CSZ name); - void DeleteMaterial(CSZ name); - void DeleteAllMaterials(); - - void Serialize(IO::RSeekableStream stream); - void Deserialize(IO::RStream stream); - - Vector GetTextureNames() const; - Vector GetMaterialNames() const; - - void ResetPart(); - static float ComputePart(float distSq, float objectRadius); - }; - VERUS_TYPEDEFS(MaterialManager); - } + void ResetPart(); + static float ComputePart(float distSq, float objectRadius); + }; + VERUS_TYPEDEFS(MaterialManager); } diff --git a/Verus/src/World/Mesh.h b/Verus/src/World/Mesh.h index eb2ad17..0084859 100644 --- a/Verus/src/World/Mesh.h +++ b/Verus/src/World/Mesh.h @@ -1,190 +1,187 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class Mesh : public BaseMesh { - class Mesh : public BaseMesh - { - public: + public: #include "../Shaders/DS_Mesh.inc.hlsl" #include "../Shaders/SimpleMesh.inc.hlsl" - enum SHADER - { - SHADER_MAIN, - SHADER_SIMPLE, - SHADER_COUNT - }; - - enum PIPE - { - PIPE_MAIN, - PIPE_INSTANCED, - PIPE_ROBOTIC, - PIPE_SKINNED, - PIPE_PLANT, - - PIPE_TESS, - PIPE_TESS_INSTANCED, - PIPE_TESS_ROBOTIC, - PIPE_TESS_SKINNED, - PIPE_TESS_PLANT, - - PIPE_DEPTH, - PIPE_DEPTH_INSTANCED, - PIPE_DEPTH_ROBOTIC, - PIPE_DEPTH_SKINNED, - PIPE_DEPTH_PLANT, - - PIPE_DEPTH_TESS, - PIPE_DEPTH_TESS_INSTANCED, - PIPE_DEPTH_TESS_ROBOTIC, - PIPE_DEPTH_TESS_SKINNED, - PIPE_DEPTH_TESS_PLANT, - - PIPE_WIREFRAME, - PIPE_WIREFRAME_INSTANCED, - PIPE_WIREFRAME_ROBOTIC, - PIPE_WIREFRAME_SKINNED, - - PIPE_SIMPLE_ENV_MAP, - PIPE_SIMPLE_ENV_MAP_INSTANCED, - PIPE_SIMPLE_ENV_MAP_ROBOTIC, - PIPE_SIMPLE_ENV_MAP_SKINNED, - - PIPE_SIMPLE_PLANAR_REF, - PIPE_SIMPLE_PLANAR_REF_INSTANCED, - PIPE_SIMPLE_PLANAR_REF_ROBOTIC, - PIPE_SIMPLE_PLANAR_REF_SKINNED, - - PIPE_SIMPLE_TEX_ADD, - PIPE_SIMPLE_TEX_ADD_INSTANCED, - PIPE_SIMPLE_TEX_ADD_ROBOTIC, - PIPE_SIMPLE_TEX_ADD_SKINNED, - - PIPE_SIMPLE_PLASMA_FX, - - PIPE_COUNT - }; - - enum class InstanceBufferFormat : int - { - pid0_mataff_float4, - pid0_mataff_float4_pid1_float4, - pid0_mataff_float4_pid1_mataff_float4, - pid0_mataff_float4_pid1_matrix_float4 - }; - - private: - static CGI::ShaderPwns s_shader; - static CGI::PipelinePwns s_pipe; - - static UB_View s_ubView; - static UB_MaterialFS s_ubMaterialFS; - static UB_MeshVS s_ubMeshVS; - static UB_SkeletonVS s_ubSkeletonVS; - static UB_Object s_ubObject; - - static UB_SimpleView s_ubSimpleView; - static UB_SimpleMaterialFS s_ubSimpleMaterialFS; - static UB_SimpleMeshVS s_ubSimpleMeshVS; - static UB_SimpleSkeletonVS s_ubSimpleSkeletonVS; - static UB_SimpleObject s_ubSimpleObject; - - CGI::GeometryPwn _geo; - Vector _vInstanceBuffer; - Vector> _vStorageBuffers; - int _instanceCapacity = 0; - int _instanceCount = 0; - int _markedInstance = 0; - InstanceBufferFormat _instanceBufferFormat = InstanceBufferFormat::pid0_mataff_float4; - UINT32 _bindingsMask = 0; - - public: - struct Desc - { - CSZ _url = nullptr; - CSZ _warpURL = nullptr; - int _instanceCapacity = 0; - InstanceBufferFormat _instanceBufferFormat = InstanceBufferFormat::pid0_mataff_float4; - bool _initShape = false; - - Desc(CSZ url = nullptr) : _url(url) {} - }; - VERUS_TYPEDEFS(Desc); - - struct DrawDesc - { - Transform3 _matW = Transform3::identity(); - Vector4 _userColor = Vector4(0); - CGI::CSHandle _cshMaterial; - PcVector4 _pOverrideFogColor = nullptr; - PIPE _pipe = PIPE_COUNT; - bool _allowTess = true; - bool _bindMaterial = true; - bool _bindPipeline = true; - bool _bindSkeleton = true; - }; - VERUS_TYPEDEFS(DrawDesc); - - Mesh(); - virtual ~Mesh(); - - static void InitStatic(); - static void DoneStatic(); - - void Init(RcDesc desc = Desc()); - void Init(RcSourceBuffers sourceBuffers, RcDesc desc = Desc()); - void Done(); - - void Draw(RcDrawDesc drawDesc, CGI::CommandBufferPtr cb); - void DrawSimple(RcDrawDesc drawDesc, CGI::CommandBufferPtr cb); - - void BindPipeline(PIPE pipe, CGI::CommandBufferPtr cb); - void BindPipeline(CGI::CommandBufferPtr cb, bool allowTess = true); - void BindPipelineInstanced(CGI::CommandBufferPtr cb, bool allowTess = true, bool plant = false); - void BindGeo(CGI::CommandBufferPtr cb, UINT32 bindingsFilter = 0); - - static CGI::ShaderPtr GetShader() { return s_shader[SHADER_MAIN]; } - static UB_MaterialFS& GetUbMaterialFS() { return s_ubMaterialFS; } - void UpdateUniformBuffer_View(float invTessDist = 0); - void UpdateUniformBuffer_MeshVS(); - void UpdateUniformBuffer_SkeletonVS(); - void UpdateUniformBuffer_Object(RcTransform3 tr, RcVector4 color = Vector4(0.5f, 0.5f, 0.5f, 1)); - - static CGI::ShaderPtr GetSimpleShader() { return s_shader[SHADER_SIMPLE]; } - static UB_SimpleMaterialFS& GetUbSimpleMaterialFS() { return s_ubSimpleMaterialFS; } - void UpdateUniformBuffer_SimpleView(DrawSimpleMode mode); - void UpdateUniformBuffer_SimpleSkeletonVS(); - - CGI::GeometryPtr GetGeometry() const { return _geo; } - virtual void CreateDeviceBuffers() override; - virtual void UpdateVertexBuffer(const void* p, int binding) override; - void CreateStorageBuffer(int count, int structSize, int sbIndex, CGI::ShaderStageFlags stageFlags); - - // - void ResetInstanceCount(); - void MarkInstance() { _markedInstance = _instanceCount; } - int GetMarkedInstance() const { return _markedInstance; } - int GetInstanceSize() const; - int GetInstanceCount(bool fromMarkedInstance = false) const { return fromMarkedInstance ? _instanceCount - _markedInstance : _instanceCount; } - int GetInstanceCapacity() const { return _instanceCapacity; } - bool IsInstanceBufferEmpty(bool fromMarkedInstance = false) const; - bool IsInstanceBufferFull() const; - VERUS_P(bool PushInstanceCheck() const); - void PushStorageBufferData(int sbIndex, const void* p, bool incInstanceCount = false); - void PushInstance(RcTransform3 matW, RcVector4 instData); - void PushInstance(RcTransform3 matW, RcVector4 instData, RcVector4 pid1_instData); - void PushInstance(RcTransform3 matW, RcVector4 instData, RcTransform3 pid1_mat, RcVector4 pid1_instData); - void PushInstance(RcTransform3 matW, RcVector4 instData, RcMatrix4 pid1_mat, RcVector4 pid1_instData); - void UpdateStorageBuffer(int sbIndex); - void UpdateInstanceBuffer(); - // - - UINT32 GetBindingsMask() const { return _bindingsMask; } + enum SHADER + { + SHADER_MAIN, + SHADER_SIMPLE, + SHADER_COUNT }; - VERUS_TYPEDEFS(Mesh); - } + + enum PIPE + { + PIPE_MAIN, + PIPE_INSTANCED, + PIPE_ROBOTIC, + PIPE_SKINNED, + PIPE_PLANT, + + PIPE_TESS, + PIPE_TESS_INSTANCED, + PIPE_TESS_ROBOTIC, + PIPE_TESS_SKINNED, + PIPE_TESS_PLANT, + + PIPE_DEPTH, + PIPE_DEPTH_INSTANCED, + PIPE_DEPTH_ROBOTIC, + PIPE_DEPTH_SKINNED, + PIPE_DEPTH_PLANT, + + PIPE_DEPTH_TESS, + PIPE_DEPTH_TESS_INSTANCED, + PIPE_DEPTH_TESS_ROBOTIC, + PIPE_DEPTH_TESS_SKINNED, + PIPE_DEPTH_TESS_PLANT, + + PIPE_WIREFRAME, + PIPE_WIREFRAME_INSTANCED, + PIPE_WIREFRAME_ROBOTIC, + PIPE_WIREFRAME_SKINNED, + + PIPE_SIMPLE_ENV_MAP, + PIPE_SIMPLE_ENV_MAP_INSTANCED, + PIPE_SIMPLE_ENV_MAP_ROBOTIC, + PIPE_SIMPLE_ENV_MAP_SKINNED, + + PIPE_SIMPLE_PLANAR_REF, + PIPE_SIMPLE_PLANAR_REF_INSTANCED, + PIPE_SIMPLE_PLANAR_REF_ROBOTIC, + PIPE_SIMPLE_PLANAR_REF_SKINNED, + + PIPE_SIMPLE_TEX_ADD, + PIPE_SIMPLE_TEX_ADD_INSTANCED, + PIPE_SIMPLE_TEX_ADD_ROBOTIC, + PIPE_SIMPLE_TEX_ADD_SKINNED, + + PIPE_SIMPLE_PLASMA_FX, + + PIPE_COUNT + }; + + enum class InstanceBufferFormat : int + { + pid0_mataff_float4, + pid0_mataff_float4_pid1_float4, + pid0_mataff_float4_pid1_mataff_float4, + pid0_mataff_float4_pid1_matrix_float4 + }; + + private: + static CGI::ShaderPwns s_shader; + static CGI::PipelinePwns s_pipe; + + static UB_View s_ubView; + static UB_MaterialFS s_ubMaterialFS; + static UB_MeshVS s_ubMeshVS; + static UB_SkeletonVS s_ubSkeletonVS; + static UB_Object s_ubObject; + + static UB_SimpleView s_ubSimpleView; + static UB_SimpleMaterialFS s_ubSimpleMaterialFS; + static UB_SimpleMeshVS s_ubSimpleMeshVS; + static UB_SimpleSkeletonVS s_ubSimpleSkeletonVS; + static UB_SimpleObject s_ubSimpleObject; + + CGI::GeometryPwn _geo; + Vector _vInstanceBuffer; + Vector> _vStorageBuffers; + int _instanceCapacity = 0; + int _instanceCount = 0; + int _markedInstance = 0; + InstanceBufferFormat _instanceBufferFormat = InstanceBufferFormat::pid0_mataff_float4; + UINT32 _bindingsMask = 0; + + public: + struct Desc + { + CSZ _url = nullptr; + CSZ _warpURL = nullptr; + int _instanceCapacity = 0; + InstanceBufferFormat _instanceBufferFormat = InstanceBufferFormat::pid0_mataff_float4; + bool _initShape = false; + + Desc(CSZ url = nullptr) : _url(url) {} + }; + VERUS_TYPEDEFS(Desc); + + struct DrawDesc + { + Transform3 _matW = Transform3::identity(); + Vector4 _userColor = Vector4(0); + CGI::CSHandle _cshMaterial; + PcVector4 _pOverrideFogColor = nullptr; + PIPE _pipe = PIPE_COUNT; + bool _allowTess = true; + bool _bindMaterial = true; + bool _bindPipeline = true; + bool _bindSkeleton = true; + }; + VERUS_TYPEDEFS(DrawDesc); + + Mesh(); + virtual ~Mesh(); + + static void InitStatic(); + static void DoneStatic(); + + void Init(RcDesc desc = Desc()); + void Init(RcSourceBuffers sourceBuffers, RcDesc desc = Desc()); + void Done(); + + void Draw(RcDrawDesc drawDesc, CGI::CommandBufferPtr cb); + void DrawSimple(RcDrawDesc drawDesc, CGI::CommandBufferPtr cb); + + void BindPipeline(PIPE pipe, CGI::CommandBufferPtr cb); + void BindPipeline(CGI::CommandBufferPtr cb, bool allowTess = true); + void BindPipelineInstanced(CGI::CommandBufferPtr cb, bool allowTess = true, bool plant = false); + void BindGeo(CGI::CommandBufferPtr cb, UINT32 bindingsFilter = 0); + + static CGI::ShaderPtr GetShader() { return s_shader[SHADER_MAIN]; } + static UB_MaterialFS& GetUbMaterialFS() { return s_ubMaterialFS; } + void UpdateUniformBuffer_View(float invTessDist = 0); + void UpdateUniformBuffer_MeshVS(); + void UpdateUniformBuffer_SkeletonVS(); + void UpdateUniformBuffer_Object(RcTransform3 tr, RcVector4 color = Vector4(0.5f, 0.5f, 0.5f, 1)); + + static CGI::ShaderPtr GetSimpleShader() { return s_shader[SHADER_SIMPLE]; } + static UB_SimpleMaterialFS& GetUbSimpleMaterialFS() { return s_ubSimpleMaterialFS; } + void UpdateUniformBuffer_SimpleView(DrawSimpleMode mode); + void UpdateUniformBuffer_SimpleSkeletonVS(); + + CGI::GeometryPtr GetGeometry() const { return _geo; } + virtual void CreateDeviceBuffers() override; + virtual void UpdateVertexBuffer(const void* p, int binding) override; + void CreateStorageBuffer(int count, int structSize, int sbIndex, CGI::ShaderStageFlags stageFlags); + + // + void ResetInstanceCount(); + void MarkInstance() { _markedInstance = _instanceCount; } + int GetMarkedInstance() const { return _markedInstance; } + int GetInstanceSize() const; + int GetInstanceCount(bool fromMarkedInstance = false) const { return fromMarkedInstance ? _instanceCount - _markedInstance : _instanceCount; } + int GetInstanceCapacity() const { return _instanceCapacity; } + bool IsInstanceBufferEmpty(bool fromMarkedInstance = false) const; + bool IsInstanceBufferFull() const; + VERUS_P(bool PushInstanceCheck() const); + void PushStorageBufferData(int sbIndex, const void* p, bool incInstanceCount = false); + void PushInstance(RcTransform3 matW, RcVector4 instData); + void PushInstance(RcTransform3 matW, RcVector4 instData, RcVector4 pid1_instData); + void PushInstance(RcTransform3 matW, RcVector4 instData, RcTransform3 pid1_mat, RcVector4 pid1_instData); + void PushInstance(RcTransform3 matW, RcVector4 instData, RcMatrix4 pid1_mat, RcVector4 pid1_instData); + void UpdateStorageBuffer(int sbIndex); + void UpdateInstanceBuffer(); + // + + UINT32 GetBindingsMask() const { return _bindingsMask; } + }; + VERUS_TYPEDEFS(Mesh); } diff --git a/Verus/src/World/OrbitingCamera.h b/Verus/src/World/OrbitingCamera.h index fd1e1ae..4af1718 100644 --- a/Verus/src/World/OrbitingCamera.h +++ b/Verus/src/World/OrbitingCamera.h @@ -1,43 +1,40 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class OrbitingCamera : public MainCamera, public Input::DragControllerDelegate { - class OrbitingCamera : public MainCamera, public Input::DragControllerDelegate - { - Anim::Elastic _pitch; - Anim::Elastic _yaw; - Anim::Elastic _radius; - bool _elastic = false; + Anim::Elastic _pitch; + Anim::Elastic _yaw; + Anim::Elastic _radius; + bool _elastic = false; - public: - OrbitingCamera(); - virtual ~OrbitingCamera(); + public: + OrbitingCamera(); + virtual ~OrbitingCamera(); - virtual void Update() override; - void UpdateUsingEyeAt(); - void UpdateElastic(); + virtual void Update() override; + void UpdateUsingEyeAt(); + void UpdateElastic(); - virtual void DragController_GetParams(float& x, float& y) override; - virtual void DragController_SetParams(float x, float y) override; - virtual void DragController_GetRatio(float& x, float& y) override; + virtual void DragController_GetParams(float& x, float& y) override; + virtual void DragController_SetParams(float x, float y) override; + virtual void DragController_GetRatio(float& x, float& y) override; - float GetPitch() const { return _pitch; } - float GetYaw() const { return _yaw; } - float GetTargetPitch() const { return _pitch.GetTarget(); } - float GetTargetYaw() const { return _yaw.GetTarget(); } - void SetPitch(float a); - void SetYaw(float a); + float GetPitch() const { return _pitch; } + float GetYaw() const { return _yaw; } + float GetTargetPitch() const { return _pitch.GetTarget(); } + float GetTargetYaw() const { return _yaw.GetTarget(); } + void SetPitch(float a); + void SetYaw(float a); - float GetRadius() const { return _radius; } - float GetTargetRadius() const { return _radius.GetTarget(); } - void SetRadius(float r); - void MulRadiusBy(float x); + float GetRadius() const { return _radius; } + float GetTargetRadius() const { return _radius.GetTarget(); } + void SetRadius(float r); + void MulRadiusBy(float x); - void EnableElastic(bool b = true) { _elastic = b; } - }; - VERUS_TYPEDEFS(OrbitingCamera); - } + void EnableElastic(bool b = true) { _elastic = b; } + }; + VERUS_TYPEDEFS(OrbitingCamera); } diff --git a/Verus/src/World/Scatter.h b/Verus/src/World/Scatter.h index 22170fc..d2a4e8c 100644 --- a/Verus/src/World/Scatter.h +++ b/Verus/src/World/Scatter.h @@ -1,70 +1,67 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + struct ScatterDelegate { - struct ScatterDelegate - { - virtual void Scatter_AddInstance(const int ij[2], int type, float x, float z, - float scale, float angle, UINT32 r) = 0; - }; - VERUS_TYPEDEFS(ScatterDelegate); + virtual void Scatter_AddInstance(const int ij[2], int type, float x, float z, + float scale, float angle, UINT32 r) = 0; + }; + VERUS_TYPEDEFS(ScatterDelegate); - class Scatter : public Object, public Math::QuadtreeIntegralDelegate + class Scatter : public Object, public Math::QuadtreeIntegralDelegate + { + public: + class Instance { public: - class Instance - { - public: - int _type = 0; - float _x = 0; - float _z = 0; - float _scale = 1; - float _angle = 0; - UINT32 _rand = 0; - }; - VERUS_TYPEDEFS(Instance); - - private: - PScatterDelegate _pDelegate = nullptr; - Vector _vInstances; - float _maxDistSq = FLT_MAX; - int _side = 0; - int _shift = 0; - - public: - class TypeDesc - { - public: - int _type = 0; - int _permille = 0; - float _minOffset = 0.25f; - float _maxOffset = 0.75f; - float _minScale = 0.8f; - float _maxScale = 1.25f; - float _minAngle = 0; - float _maxAngle = VERUS_2PI; - TypeDesc(int type, int permille) : _type(type), _permille(permille) {} - }; - VERUS_TYPEDEFS(TypeDesc); - - Scatter(); - ~Scatter(); - - void Init(int side, int typeCount, PcTypeDesc pTypes, int seed = 192000); - void Done(); - - void SetMaxDist(float dist) { _maxDistSq = dist * dist; } - - PScatterDelegate SetDelegate(PScatterDelegate p) { return Utils::Swap(_pDelegate, p); } - - virtual void QuadtreeIntegral_OnElementDetected(const short ij[2], RcPoint3 center) override; - virtual void QuadtreeIntegral_GetHeights(const short ij[2], float height[2]) override; - - RcInstance GetInstanceAt(const int ij[2]) const; + int _type = 0; + float _x = 0; + float _z = 0; + float _scale = 1; + float _angle = 0; + UINT32 _rand = 0; }; - VERUS_TYPEDEFS(Scatter); - } + VERUS_TYPEDEFS(Instance); + + private: + PScatterDelegate _pDelegate = nullptr; + Vector _vInstances; + float _maxDistSq = FLT_MAX; + int _side = 0; + int _shift = 0; + + public: + class TypeDesc + { + public: + int _type = 0; + int _permille = 0; + float _minOffset = 0.25f; + float _maxOffset = 0.75f; + float _minScale = 0.8f; + float _maxScale = 1.25f; + float _minAngle = 0; + float _maxAngle = VERUS_2PI; + TypeDesc(int type, int permille) : _type(type), _permille(permille) {} + }; + VERUS_TYPEDEFS(TypeDesc); + + Scatter(); + ~Scatter(); + + void Init(int side, int typeCount, PcTypeDesc pTypes, int seed = 192000); + void Done(); + + void SetMaxDist(float dist) { _maxDistSq = dist * dist; } + + PScatterDelegate SetDelegate(PScatterDelegate p) { return Utils::Swap(_pDelegate, p); } + + virtual void QuadtreeIntegral_OnElementDetected(const short ij[2], RcPoint3 center) override; + virtual void QuadtreeIntegral_GetHeights(const short ij[2], float height[2]) override; + + RcInstance GetInstanceAt(const int ij[2]) const; + }; + VERUS_TYPEDEFS(Scatter); } diff --git a/Verus/src/World/ShadowMapBaker.h b/Verus/src/World/ShadowMapBaker.h index 729e5a1..f5c05ed 100644 --- a/Verus/src/World/ShadowMapBaker.h +++ b/Verus/src/World/ShadowMapBaker.h @@ -1,97 +1,94 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class ShadowMapBaker : public Object { - class ShadowMapBaker : public Object + public: + struct Config { - public: - struct Config - { - float _unormDepthScale = 0; // Scale depth buffer values by this (typically zFar-zNear). - float _wrapDiffuseScale = 4; // How much wrapDiffuse affects penumbra. - float _normalDepthBias = 0.04f; // Depth bias along normals. - float _csmContrastScale = 1.3f; // Makes distant slices sharper. - }; - VERUS_TYPEDEFS(Config); - - protected: - Matrix4 _matShadow = Matrix4::identity(); - Matrix4 _matShadowForDS = Matrix4::identity(); // For WV positions in Deferred Shading. - Config _config; - CGI::TexturePwn _tex; - CGI::RPHandle _rph; - CGI::FBHandle _fbh; - Camera _passCamera; - PCamera _pPrevPassCamera = nullptr; - int _side = 0; - bool _baking = false; - bool _snapToTexels = true; - - public: - ShadowMapBaker(); - ~ShadowMapBaker(); - - void Init(int side); - void Done(); - - // - void Begin(RcVector3 dirToSun, RcVector3 up = Vector3(0, 1, 0)); - void End(); - bool IsBaking() const { return _baking; } - CGI::RPHandle GetRenderPassHandle() const { return _rph; } - // - - void UpdateMatrixForCurrentView(); - - RcMatrix4 GetShadowMatrix() const; - RcMatrix4 GetShadowMatrixForDS() const; - - CGI::TexturePtr GetTexture() const; - - RConfig GetConfig() { return _config; } - - void SetSnapToTexels(bool b) { _snapToTexels = b; } + float _unormDepthScale = 0; // Scale depth buffer values by this (typically zFar-zNear). + float _wrapDiffuseScale = 4; // How much wrapDiffuse affects penumbra. + float _normalDepthBias = 0.04f; // Depth bias along normals. + float _csmContrastScale = 1.3f; // Makes distant slices sharper. }; - VERUS_TYPEDEFS(ShadowMapBaker); + VERUS_TYPEDEFS(Config); - class CascadedShadowMapBaker : public Singleton, public ShadowMapBaker - { - Matrix4 _matShadowCSM[4]; - Matrix4 _matShadowCSM_DS[4]; // For WV positions in Deferred Shading. - Matrix4 _matOffset[4]; - Matrix4 _matScreenVP = Matrix4::identity(); - Matrix4 _matScreenP = Matrix4::identity(); - Vector4 _sliceBounds = Vector4(0); - int _currentSlice = -1; - float _depth = 0; - float _headCameraPreferredRange = 0; + protected: + Matrix4 _matShadow = Matrix4::identity(); + Matrix4 _matShadowForDS = Matrix4::identity(); // For WV positions in Deferred Shading. + Config _config; + CGI::TexturePwn _tex; + CGI::RPHandle _rph; + CGI::FBHandle _fbh; + Camera _passCamera; + PCamera _pPrevPassCamera = nullptr; + int _side = 0; + bool _baking = false; + bool _snapToTexels = true; - public: - CascadedShadowMapBaker(); - ~CascadedShadowMapBaker(); + public: + ShadowMapBaker(); + ~ShadowMapBaker(); - void Init(int side = 4096); - void Done(); + void Init(int side); + void Done(); - // - void Begin(RcVector3 dirToSun, int slice, RcVector3 up = Vector3(0, 1, 0)); - void End(int slice); - // + // + void Begin(RcVector3 dirToSun, RcVector3 up = Vector3(0, 1, 0)); + void End(); + bool IsBaking() const { return _baking; } + CGI::RPHandle GetRenderPassHandle() const { return _rph; } + // - void UpdateMatrixForCurrentView(); + void UpdateMatrixForCurrentView(); - RcMatrix4 GetShadowMatrix(int slice) const; - RcMatrix4 GetShadowMatrixForDS(int slice) const; + RcMatrix4 GetShadowMatrix() const; + RcMatrix4 GetShadowMatrixForDS() const; - RcMatrix4 GetScreenMatrixVP() const { return _matScreenVP; } - RcMatrix4 GetScreenMatrixP() const { return _matScreenP; } + CGI::TexturePtr GetTexture() const; - int GetCurrentSlice() const { return _currentSlice; } - RcVector4 GetSliceBounds() const { return _sliceBounds; } - }; - VERUS_TYPEDEFS(CascadedShadowMapBaker); - } + RConfig GetConfig() { return _config; } + + void SetSnapToTexels(bool b) { _snapToTexels = b; } + }; + VERUS_TYPEDEFS(ShadowMapBaker); + + class CascadedShadowMapBaker : public Singleton, public ShadowMapBaker + { + Matrix4 _matShadowCSM[4]; + Matrix4 _matShadowCSM_DS[4]; // For WV positions in Deferred Shading. + Matrix4 _matOffset[4]; + Matrix4 _matScreenVP = Matrix4::identity(); + Matrix4 _matScreenP = Matrix4::identity(); + Vector4 _sliceBounds = Vector4(0); + int _currentSlice = -1; + float _depth = 0; + float _headCameraPreferredRange = 0; + + public: + CascadedShadowMapBaker(); + ~CascadedShadowMapBaker(); + + void Init(int side = 4096); + void Done(); + + // + void Begin(RcVector3 dirToSun, int slice, RcVector3 up = Vector3(0, 1, 0)); + void End(int slice); + // + + void UpdateMatrixForCurrentView(); + + RcMatrix4 GetShadowMatrix(int slice) const; + RcMatrix4 GetShadowMatrixForDS(int slice) const; + + RcMatrix4 GetScreenMatrixVP() const { return _matScreenVP; } + RcMatrix4 GetScreenMatrixP() const { return _matScreenP; } + + int GetCurrentSlice() const { return _currentSlice; } + RcVector4 GetSliceBounds() const { return _sliceBounds; } + }; + VERUS_TYPEDEFS(CascadedShadowMapBaker); } diff --git a/Verus/src/World/ShadowMapBakerPool.h b/Verus/src/World/ShadowMapBakerPool.h index f19c5cc..050741d 100644 --- a/Verus/src/World/ShadowMapBakerPool.h +++ b/Verus/src/World/ShadowMapBakerPool.h @@ -1,95 +1,92 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class ShadowMapBakerPool : public Singleton, public Object { - class ShadowMapBakerPool : public Singleton, public Object + enum TEX { - enum TEX - { - TEX_DEPTH, - TEX_2CH, - TEX_COUNT - }; + TEX_DEPTH, + TEX_2CH, + TEX_COUNT + }; - static const int s_blockSide = 4; + static const int s_blockSide = 4; - class Block : public Object - { - CGI::TexturePwn _tex; - CGI::FBHandle _fbhPong; - CGI::CSHandle _csh; - UINT64 _doneFrame = 0; - UINT16 _reserved = 0; - UINT16 _baked = 0; - float _presence[s_blockSide * s_blockSide]; - - public: - Block(); - ~Block(); - - void Init(int side); - void Done(); - - void Update(); - - bool HasFreeCells() const; - int FindFreeCell() const; - bool IsUnused() const; - bool IsReserved(int cellIndex) const; - void Reserve(int cellIndex); - void Free(int cellIndex); - void MarkBaked(int cellIndex); - - CGI::TexturePtr GetTexture() const { return _tex; } - CGI::FBHandle GetFramebufferHandle() const { return _fbhPong; } - CGI::CSHandle GetComplexSetHandle() const { return _csh; } - float GetPresence(int cellIndex) const { return _presence[cellIndex]; } - - UINT64 GetDoneFrame() const { return _doneFrame; } - }; - VERUS_TYPEDEFS(Block); - - Vector _vBlocks; - CGI::TexturePwns _tex; - CGI::FBHandle _fbh; - CGI::FBHandle _fbhPing; - CGI::CSHandle _cshPing; - CGI::CSHandle _cshPong; - MainCamera _passCamera; - PCamera _pPrevPassCamera = nullptr; - PMainCamera _pPrevHeadCamera = nullptr; - ShadowMapHandle _activeBlockHandle; - int _side = 0; - bool _baking = false; + class Block : public Object + { + CGI::TexturePwn _tex; + CGI::FBHandle _fbhPong; + CGI::CSHandle _csh; + UINT64 _doneFrame = 0; + UINT16 _reserved = 0; + UINT16 _baked = 0; + float _presence[s_blockSide * s_blockSide]; public: - ShadowMapBakerPool(); - ~ShadowMapBakerPool(); + Block(); + ~Block(); - void Init(int side = 512); + void Init(int side); void Done(); void Update(); - // - void Begin(RLightNode lightNode); - void End(); - bool IsBaking() const { return _baking; } - // + bool HasFreeCells() const; + int FindFreeCell() const; + bool IsUnused() const; + bool IsReserved(int cellIndex) const; + void Reserve(int cellIndex); + void Free(int cellIndex); + void MarkBaked(int cellIndex); - Matrix4 GetOffsetMatrix(ShadowMapHandle handle) const; + CGI::TexturePtr GetTexture() const { return _tex; } + CGI::FBHandle GetFramebufferHandle() const { return _fbhPong; } + CGI::CSHandle GetComplexSetHandle() const { return _csh; } + float GetPresence(int cellIndex) const { return _presence[cellIndex]; } - CGI::CSHandle GetComplexSetHandle(ShadowMapHandle handle) const; - float GetPresence(ShadowMapHandle handle) const; - - ShadowMapHandle ReserveCell(); - void FreeCell(ShadowMapHandle handle); - - void GarbageCollection(); + UINT64 GetDoneFrame() const { return _doneFrame; } }; - VERUS_TYPEDEFS(ShadowMapBakerPool); - } + VERUS_TYPEDEFS(Block); + + Vector _vBlocks; + CGI::TexturePwns _tex; + CGI::FBHandle _fbh; + CGI::FBHandle _fbhPing; + CGI::CSHandle _cshPing; + CGI::CSHandle _cshPong; + MainCamera _passCamera; + PCamera _pPrevPassCamera = nullptr; + PMainCamera _pPrevHeadCamera = nullptr; + ShadowMapHandle _activeBlockHandle; + int _side = 0; + bool _baking = false; + + public: + ShadowMapBakerPool(); + ~ShadowMapBakerPool(); + + void Init(int side = 512); + void Done(); + + void Update(); + + // + void Begin(RLightNode lightNode); + void End(); + bool IsBaking() const { return _baking; } + // + + Matrix4 GetOffsetMatrix(ShadowMapHandle handle) const; + + CGI::CSHandle GetComplexSetHandle(ShadowMapHandle handle) const; + float GetPresence(ShadowMapHandle handle) const; + + ShadowMapHandle ReserveCell(); + void FreeCell(ShadowMapHandle handle); + + void GarbageCollection(); + }; + VERUS_TYPEDEFS(ShadowMapBakerPool); } diff --git a/Verus/src/World/Terrain.h b/Verus/src/World/Terrain.h index 8d44305..efbc90d 100644 --- a/Verus/src/World/Terrain.h +++ b/Verus/src/World/Terrain.h @@ -1,287 +1,284 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class Terrain; + class Forest; + + enum class TerrainTBN : int { - class Terrain; - class Forest; + tangent, + binormal, + normal + }; - enum class TerrainTBN : int + class TerrainPhysics + { + LocalPtr _pShape; + Physics::LocalRigidBody _pRigidBody; + bool _debugDraw = false; + + public: + TerrainPhysics(); + ~TerrainPhysics(); + + void Init(Physics::PUserPtr p, int w, int h, const void* pData, float heightScale = 0.01f); + void Done(); + + void EnableDebugDraw(bool b); + bool IsDebugDrawEnabled() const { return _debugDraw; } + }; + VERUS_TYPEDEFS(TerrainPhysics); + + class TerrainLOD + { + public: + Vector _vIB; + int _side = 0; + int _vertCount = 0; + int _indexCount = 0; + int _firstIndex = 0; + + void Init(int sidePoly, int step, bool addEdgeTess); + void InitGeo(short* pV, UINT16* pI, int vertexOffset, bool addEdgeTess); + }; + VERUS_TYPEDEFS(TerrainLOD); + + class TerrainPatch + { + public: + struct TBN { - tangent, - binormal, - normal + char _normals0[16 * 16][3]; + char _normals1[8 * 8][3]; + char _normals2[4 * 4][3]; + char _normals3[2 * 2][3]; + char _normals4[1 * 1][3]; }; + VERUS_TYPEDEFS(TBN); - class TerrainPhysics - { - LocalPtr _pShape; - Physics::LocalRigidBody _pRigidBody; - bool _debugDraw = false; + PTBN _pTBN = nullptr; + UINT16 _ijCoord[2]; + char _layerForChannel[4]; + int _distToHeadSq = 0; + short _patchHeight = 0; + char _quadtreeLOD = 0; + char _usedChannelCount = 1; + short _height[16 * 16]; + char _mainLayer[16 * 16]; - public: - TerrainPhysics(); - ~TerrainPhysics(); + TerrainPatch(); + void BindTBN(PTBN p); + void InitFlat(short height, int mainLayer); + void UpdateNormals(Terrain* p, int lod); + int GetSplatChannelForLayer(int layer) const; + }; + VERUS_TYPEDEFS(TerrainPatch); - void Init(Physics::PUserPtr p, int w, int h, const void* pData, float heightScale = 0.01f); - void Done(); - - void EnableDebugDraw(bool b); - bool IsDebugDrawEnabled() const { return _debugDraw; } - }; - VERUS_TYPEDEFS(TerrainPhysics); - - class TerrainLOD - { - public: - Vector _vIB; - int _side = 0; - int _vertCount = 0; - int _indexCount = 0; - int _firstIndex = 0; - - void Init(int sidePoly, int step, bool addEdgeTess); - void InitGeo(short* pV, UINT16* pI, int vertexOffset, bool addEdgeTess); - }; - VERUS_TYPEDEFS(TerrainLOD); - - class TerrainPatch - { - public: - struct TBN - { - char _normals0[16 * 16][3]; - char _normals1[8 * 8][3]; - char _normals2[4 * 4][3]; - char _normals3[2 * 2][3]; - char _normals4[1 * 1][3]; - }; - VERUS_TYPEDEFS(TBN); - - PTBN _pTBN = nullptr; - UINT16 _ijCoord[2]; - char _layerForChannel[4]; - int _distToHeadSq = 0; - short _patchHeight = 0; - char _quadtreeLOD = 0; - char _usedChannelCount = 1; - short _height[16 * 16]; - char _mainLayer[16 * 16]; - - TerrainPatch(); - void BindTBN(PTBN p); - void InitFlat(short height, int mainLayer); - void UpdateNormals(Terrain* p, int lod); - int GetSplatChannelForLayer(int layer) const; - }; - VERUS_TYPEDEFS(TerrainPatch); - - class Terrain : public Object, public Math::QuadtreeIntegralDelegate, public Physics::UserPtr - { - public: + class Terrain : public Object, public Math::QuadtreeIntegralDelegate, public Physics::UserPtr + { + public: #include "../Shaders/DS_Terrain.inc.hlsl" #include "../Shaders/SimpleTerrain.inc.hlsl" - enum SHADER - { - SHADER_MAIN, - SHADER_SIMPLE, - SHADER_COUNT - }; - - enum PIPE - { - PIPE_LIST, - PIPE_STRIP, - PIPE_TESS, - - PIPE_DEPTH_LIST, - PIPE_DEPTH_STRIP, - PIPE_DEPTH_TESS, - - PIPE_WIREFRAME_LIST, - PIPE_WIREFRAME_STRIP, - PIPE_SIMPLE_ENV_MAP_LIST, - PIPE_SIMPLE_ENV_MAP_STRIP, - PIPE_SIMPLE_PLANAR_REF_LIST, - PIPE_SIMPLE_PLANAR_REF_STRIP, - PIPE_SIMPLE_UNDERWATER_LIST, - PIPE_SIMPLE_UNDERWATER_STRIP, - PIPE_COUNT - }; - - enum TEX - { - TEX_HEIGHTMAP, - TEX_NORMALS, - TEX_BLEND, - TEX_LAYERS, - TEX_LAYERS_N, - TEX_LAYERS_X, - TEX_MAIN_LAYER, - TEX_COUNT - }; - - static const int s_maxLayers = 32; - - struct PerInstanceData - { - short _posPatch[4]; - short _layers[4]; - }; - - struct LayerData - { - float _detailStrength = 0.1f; - float _roughStrength = 0.1f; - }; - - protected: - static CGI::ShaderPwns s_shader; - static UB_TerrainVS s_ubTerrainVS; - static UB_TerrainFS s_ubTerrainFS; - static UB_SimpleTerrainVS s_ubSimpleTerrainVS; - static UB_SimpleTerrainFS s_ubSimpleTerrainFS; - - CGI::GeometryPwn _geo; - CGI::PipelinePwns _pipe; - CGI::TexturePwns _tex; - Vector _vPatches; - Vector _vPatchTBNs; - Vector _vSortedPatchIndices; - Vector _vRandomPatchIndices; - Vector _vInstanceBuffer; - Vector _vLayerUrls; - Vector _vHeightBuffer; - Vector _vHeightmapSubresData; - Vector _vNormalsSubresData; - Vector _vBlendBuffer; - Vector _vMainLayerSubresData; - float _quadtreeFatten = 0.5f; - int _mapSide = 0; - int _mapShift = 0; - int _vertCount = 0; - int _indexCount = 0; - int _instanceCount = 0; - int _visiblePatchCount = 0; - int _visibleSortedPatchCount = 0; - int _visibleRandomPatchCount = 0; - CGI::CSHandle _cshVS; - CGI::CSHandle _cshFS; - CGI::CSHandle _cshSimpleVS; - CGI::CSHandle _cshSimpleFS; - TerrainLOD _lods[5]; // Level of detail data for (16x16, 8x8, 4x4, 2x2, 1x1). - LayerData _layerData[s_maxLayers]; - TerrainPhysics _physics; - Math::QuadtreeIntegral _quadtree; - - public: - float _lamScale = 1.9f; - float _lamBias = -0.9f; - - struct Desc - { - CSZ _heightmapUrl = nullptr; - float _heightmapScale = 1; - float _heightmapBias = 0; - int _mapSide = 256; - int _layer = 0; - short _height = 0; - short _debugHills = 0; - - Desc() {} - }; - VERUS_TYPEDEFS(Desc); - - struct DrawDesc - { - bool _allowTess = false; - bool _wireframe = false; - - void Reset() - { - *this = DrawDesc(); - } - }; - VERUS_TYPEDEFS(DrawDesc); - - Terrain(); - virtual ~Terrain(); - - static void InitStatic(); - static void DoneStatic(); - - void Init(RcDesc desc = Desc()); - void InitByWater(); - void Done(); - - void ResetInstanceCount(); - void Layout(); - void SortVisible(); - void Draw(RcDrawDesc dd = DrawDesc()); - void DrawSimple(DrawSimpleMode mode); - - virtual int UserPtr_GetType() override; - - int GetMapSide() const { return _mapSide; } - - RTerrainPatch GetPatch(int index) { return _vPatches[index]; } - - // Quadtree: - Math::RQuadtreeIntegral GetQuadtree() { return _quadtree; } - virtual void QuadtreeIntegral_OnElementDetected(const short ij[2], RcPoint3 center) override; - virtual void QuadtreeIntegral_GetHeights(const short ij[2], float height[2]) override; - void FattenQuadtreeNodesBy(float x); - - // Height: - static constexpr float ConvertHeight(short h) { return h * 0.01f; } - static constexpr int ConvertHeight(float h) { return static_cast(h * 100); } - float GetHeightAt(const float xz[2]) const; - float GetHeightAt(RcPoint3 pos) const; - float GetHeightAt(const int ij[2], int lod = 0, short* pRaw = nullptr) const; - void SetHeightAt(const int ij[2], short h); - void UpdateHeightBuffer(); - - // Normals: - const char* GetNormalAt(const int ij[2], int lod = 0, TerrainTBN tbn = TerrainTBN::normal) const; - Matrix3 GetBasisAt(const int ij[2]) const; - - // Layers: - void InsertLayerUrl(int layer, CSZ url); - void DeleteAllLayerUrls(); - void GetLayerUrls(Vector& v); - void LoadLayersFromFile(CSZ url = nullptr); - void LoadLayerTextures(); - int GetMainLayerAt(const int ij[2]) const; - void UpdateMainLayerAt(const int ij[2]); - - float GetDetailStrength(int layer) const { return _layerData[layer]._detailStrength; } - float GetRoughStrength(int layer) const { return _layerData[layer]._roughStrength; } - void SetDetailStrength(int layer, float x) { _layerData[layer]._detailStrength = x; } - void SetRoughStrength(int layer, float x) { _layerData[layer]._roughStrength = x; } - - // Textures: - void UpdateHeightmapTexture(); - CGI::TexturePtr GetHeightmapTexture() const; - void UpdateNormalsTexture(); - CGI::TexturePtr GetNormalsTexture() const; - void UpdateBlendTexture(); - CGI::TexturePtr GetBlendTexture() const; - void UpdateMainLayerTexture(); - CGI::TexturePtr GetMainLayerTexture() const; - void ComputeOcclusion(); - void UpdateOcclusion(Forest* pForest); - void OnHeightModified(); - - // Physics: - void AddNewRigidBody(); - RTerrainPhysics GetPhysics() { return _physics; } - - void Serialize(IO::RSeekableStream stream); - void Deserialize(IO::RStream stream); + enum SHADER + { + SHADER_MAIN, + SHADER_SIMPLE, + SHADER_COUNT }; - VERUS_TYPEDEFS(Terrain); - } + + enum PIPE + { + PIPE_LIST, + PIPE_STRIP, + PIPE_TESS, + + PIPE_DEPTH_LIST, + PIPE_DEPTH_STRIP, + PIPE_DEPTH_TESS, + + PIPE_WIREFRAME_LIST, + PIPE_WIREFRAME_STRIP, + PIPE_SIMPLE_ENV_MAP_LIST, + PIPE_SIMPLE_ENV_MAP_STRIP, + PIPE_SIMPLE_PLANAR_REF_LIST, + PIPE_SIMPLE_PLANAR_REF_STRIP, + PIPE_SIMPLE_UNDERWATER_LIST, + PIPE_SIMPLE_UNDERWATER_STRIP, + PIPE_COUNT + }; + + enum TEX + { + TEX_HEIGHTMAP, + TEX_NORMALS, + TEX_BLEND, + TEX_LAYERS, + TEX_LAYERS_N, + TEX_LAYERS_X, + TEX_MAIN_LAYER, + TEX_COUNT + }; + + static const int s_maxLayers = 32; + + struct PerInstanceData + { + short _posPatch[4]; + short _layers[4]; + }; + + struct LayerData + { + float _detailStrength = 0.1f; + float _roughStrength = 0.1f; + }; + + protected: + static CGI::ShaderPwns s_shader; + static UB_TerrainVS s_ubTerrainVS; + static UB_TerrainFS s_ubTerrainFS; + static UB_SimpleTerrainVS s_ubSimpleTerrainVS; + static UB_SimpleTerrainFS s_ubSimpleTerrainFS; + + CGI::GeometryPwn _geo; + CGI::PipelinePwns _pipe; + CGI::TexturePwns _tex; + Vector _vPatches; + Vector _vPatchTBNs; + Vector _vSortedPatchIndices; + Vector _vRandomPatchIndices; + Vector _vInstanceBuffer; + Vector _vLayerUrls; + Vector _vHeightBuffer; + Vector _vHeightmapSubresData; + Vector _vNormalsSubresData; + Vector _vBlendBuffer; + Vector _vMainLayerSubresData; + float _quadtreeFatten = 0.5f; + int _mapSide = 0; + int _mapShift = 0; + int _vertCount = 0; + int _indexCount = 0; + int _instanceCount = 0; + int _visiblePatchCount = 0; + int _visibleSortedPatchCount = 0; + int _visibleRandomPatchCount = 0; + CGI::CSHandle _cshVS; + CGI::CSHandle _cshFS; + CGI::CSHandle _cshSimpleVS; + CGI::CSHandle _cshSimpleFS; + TerrainLOD _lods[5]; // Level of detail data for (16x16, 8x8, 4x4, 2x2, 1x1). + LayerData _layerData[s_maxLayers]; + TerrainPhysics _physics; + Math::QuadtreeIntegral _quadtree; + + public: + float _lamScale = 1.9f; + float _lamBias = -0.9f; + + struct Desc + { + CSZ _heightmapUrl = nullptr; + float _heightmapScale = 1; + float _heightmapBias = 0; + int _mapSide = 256; + int _layer = 0; + short _height = 0; + short _debugHills = 0; + + Desc() {} + }; + VERUS_TYPEDEFS(Desc); + + struct DrawDesc + { + bool _allowTess = false; + bool _wireframe = false; + + void Reset() + { + *this = DrawDesc(); + } + }; + VERUS_TYPEDEFS(DrawDesc); + + Terrain(); + virtual ~Terrain(); + + static void InitStatic(); + static void DoneStatic(); + + void Init(RcDesc desc = Desc()); + void InitByWater(); + void Done(); + + void ResetInstanceCount(); + void Layout(); + void SortVisible(); + void Draw(RcDrawDesc dd = DrawDesc()); + void DrawSimple(DrawSimpleMode mode); + + virtual int UserPtr_GetType() override; + + int GetMapSide() const { return _mapSide; } + + RTerrainPatch GetPatch(int index) { return _vPatches[index]; } + + // Quadtree: + Math::RQuadtreeIntegral GetQuadtree() { return _quadtree; } + virtual void QuadtreeIntegral_OnElementDetected(const short ij[2], RcPoint3 center) override; + virtual void QuadtreeIntegral_GetHeights(const short ij[2], float height[2]) override; + void FattenQuadtreeNodesBy(float x); + + // Height: + static constexpr float ConvertHeight(short h) { return h * 0.01f; } + static constexpr int ConvertHeight(float h) { return static_cast(h * 100); } + float GetHeightAt(const float xz[2]) const; + float GetHeightAt(RcPoint3 pos) const; + float GetHeightAt(const int ij[2], int lod = 0, short* pRaw = nullptr) const; + void SetHeightAt(const int ij[2], short h); + void UpdateHeightBuffer(); + + // Normals: + const char* GetNormalAt(const int ij[2], int lod = 0, TerrainTBN tbn = TerrainTBN::normal) const; + Matrix3 GetBasisAt(const int ij[2]) const; + + // Layers: + void InsertLayerUrl(int layer, CSZ url); + void DeleteAllLayerUrls(); + void GetLayerUrls(Vector& v); + void LoadLayersFromFile(CSZ url = nullptr); + void LoadLayerTextures(); + int GetMainLayerAt(const int ij[2]) const; + void UpdateMainLayerAt(const int ij[2]); + + float GetDetailStrength(int layer) const { return _layerData[layer]._detailStrength; } + float GetRoughStrength(int layer) const { return _layerData[layer]._roughStrength; } + void SetDetailStrength(int layer, float x) { _layerData[layer]._detailStrength = x; } + void SetRoughStrength(int layer, float x) { _layerData[layer]._roughStrength = x; } + + // Textures: + void UpdateHeightmapTexture(); + CGI::TexturePtr GetHeightmapTexture() const; + void UpdateNormalsTexture(); + CGI::TexturePtr GetNormalsTexture() const; + void UpdateBlendTexture(); + CGI::TexturePtr GetBlendTexture() const; + void UpdateMainLayerTexture(); + CGI::TexturePtr GetMainLayerTexture() const; + void ComputeOcclusion(); + void UpdateOcclusion(Forest* pForest); + void OnHeightModified(); + + // Physics: + void AddNewRigidBody(); + RTerrainPhysics GetPhysics() { return _physics; } + + void Serialize(IO::RSeekableStream stream); + void Deserialize(IO::RStream stream); + }; + VERUS_TYPEDEFS(Terrain); } diff --git a/Verus/src/World/Water.h b/Verus/src/World/Water.h index 69a52e8..5a92ab5 100644 --- a/Verus/src/World/Water.h +++ b/Verus/src/World/Water.h @@ -1,120 +1,117 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class Water : public Singleton, public Object { - class Water : public Singleton, public Object - { - public: + public: #include "../Shaders/Water.inc.hlsl" #include "../Shaders/WaterGen.inc.hlsl" - enum SHADER - { - SHADER_MAIN, - SHADER_GEN, - SHADER_COUNT - }; - - enum PIPE - { - PIPE_MAIN, - PIPE_GEN_HEIGHTMAP, - PIPE_GEN_NORMALS, - PIPE_COUNT - }; - - enum TEX - { - TEX_FOAM, - TEX_SOURCE_HEIGHTMAP, - TEX_GEN_HEIGHTMAP, - TEX_GEN_NORMALS, - TEX_REFLECTION, - TEX_REFLECTION_DEPTH, - TEX_COUNT - }; - - private: - static const int s_maxHarmonics = 4; - - struct Vertex - { - glm::vec4 _pos; - }; - - static UB_WaterVS s_ubWaterVS; - static UB_WaterFS s_ubWaterFS; - static UB_Gen s_ubGen; - static UB_GenHeightmapFS s_ubGenHeightmapFS; - static UB_GenNormalsFS s_ubGenNormalsFS; - - Vector3 _diffuseColorShallow = Vector3(0.01f, 0.2f, 0.25f); - Vector3 _diffuseColorDeep = Vector3(0.005f, 0.015f, 0.025f); - PTerrain _pTerrain = nullptr; - CGI::GeometryPwn _geo; - CGI::ShaderPwns _shader; - CGI::PipelinePwns _pipe; - CGI::TexturePwns _tex; - CGI::CSHandle _cshWaterVS; - CGI::CSHandle _cshWaterFS; - CGI::RPHandle _rphGenHeightmap; - CGI::FBHandle _fbhGenHeightmap; - CGI::CSHandle _cshGenHeightmap; - CGI::RPHandle _rphGenNormals; - CGI::FBHandle _fbhGenNormals; - CGI::CSHandle _cshGenNormals; - CGI::RPHandle _rphReflection; - CGI::FBHandle _fbhReflection; - MainCamera _headCamera; - PCamera _pPrevPassCamera = nullptr; - PMainCamera _pPrevHeadCamera = nullptr; - const int _genSide = 1024; - int _gridWidth = 128; - int _gridHeight = 512; - int _indexCount = 0; - const float _patchSide = 64; - const float _fogDensity = 0.02f; - float _phase = 0; - float _wavePhase = 0; - float _amplitudes[s_maxHarmonics]; - - public: - Water(); - ~Water(); - - void Init(RTerrain terrain); - void Done(); - - void Update(); - void Draw(); - - void OnSwapChainResized(); - - CGI::RPHandle GetRenderPassHandle() const { return _rphReflection; } - void BeginPlanarReflection(CGI::PBaseCommandBuffer pCB = nullptr); - void EndPlanarReflection(CGI::PBaseCommandBuffer pCB = nullptr); - - void GenerateTextures(); - VERUS_P(void GenerateHeightmapTexture()); - VERUS_P(void GenerateNormalsTexture()); - - // Caustics are highlights on ocean floor. - CGI::TexturePtr GetCausticsTexture() const; - - VERUS_P(void CreateWaterPlane()); - - static float PhillipsSpectrum(float k); - - bool IsUnderwater() const; - bool IsUnderwater(RcPoint3 eyePos) const; - - RcVector3 GetDiffuseColorShallow() const { return _diffuseColorShallow; } - RcVector3 GetDiffuseColorDeep() const { return _diffuseColorDeep; } - float GetFogDensity() const { return _fogDensity; } + enum SHADER + { + SHADER_MAIN, + SHADER_GEN, + SHADER_COUNT }; - VERUS_TYPEDEFS(Water); - } + + enum PIPE + { + PIPE_MAIN, + PIPE_GEN_HEIGHTMAP, + PIPE_GEN_NORMALS, + PIPE_COUNT + }; + + enum TEX + { + TEX_FOAM, + TEX_SOURCE_HEIGHTMAP, + TEX_GEN_HEIGHTMAP, + TEX_GEN_NORMALS, + TEX_REFLECTION, + TEX_REFLECTION_DEPTH, + TEX_COUNT + }; + + private: + static const int s_maxHarmonics = 4; + + struct Vertex + { + glm::vec4 _pos; + }; + + static UB_WaterVS s_ubWaterVS; + static UB_WaterFS s_ubWaterFS; + static UB_Gen s_ubGen; + static UB_GenHeightmapFS s_ubGenHeightmapFS; + static UB_GenNormalsFS s_ubGenNormalsFS; + + Vector3 _diffuseColorShallow = Vector3(0.01f, 0.2f, 0.25f); + Vector3 _diffuseColorDeep = Vector3(0.005f, 0.015f, 0.025f); + PTerrain _pTerrain = nullptr; + CGI::GeometryPwn _geo; + CGI::ShaderPwns _shader; + CGI::PipelinePwns _pipe; + CGI::TexturePwns _tex; + CGI::CSHandle _cshWaterVS; + CGI::CSHandle _cshWaterFS; + CGI::RPHandle _rphGenHeightmap; + CGI::FBHandle _fbhGenHeightmap; + CGI::CSHandle _cshGenHeightmap; + CGI::RPHandle _rphGenNormals; + CGI::FBHandle _fbhGenNormals; + CGI::CSHandle _cshGenNormals; + CGI::RPHandle _rphReflection; + CGI::FBHandle _fbhReflection; + MainCamera _headCamera; + PCamera _pPrevPassCamera = nullptr; + PMainCamera _pPrevHeadCamera = nullptr; + const int _genSide = 1024; + int _gridWidth = 128; + int _gridHeight = 512; + int _indexCount = 0; + const float _patchSide = 64; + const float _fogDensity = 0.02f; + float _phase = 0; + float _wavePhase = 0; + float _amplitudes[s_maxHarmonics]; + + public: + Water(); + ~Water(); + + void Init(RTerrain terrain); + void Done(); + + void Update(); + void Draw(); + + void OnSwapChainResized(); + + CGI::RPHandle GetRenderPassHandle() const { return _rphReflection; } + void BeginPlanarReflection(CGI::PBaseCommandBuffer pCB = nullptr); + void EndPlanarReflection(CGI::PBaseCommandBuffer pCB = nullptr); + + void GenerateTextures(); + VERUS_P(void GenerateHeightmapTexture()); + VERUS_P(void GenerateNormalsTexture()); + + // Caustics are highlights on ocean floor. + CGI::TexturePtr GetCausticsTexture() const; + + VERUS_P(void CreateWaterPlane()); + + static float PhillipsSpectrum(float k); + + bool IsUnderwater() const; + bool IsUnderwater(RcPoint3 eyePos) const; + + RcVector3 GetDiffuseColorShallow() const { return _diffuseColorShallow; } + RcVector3 GetDiffuseColorDeep() const { return _diffuseColorDeep; } + float GetFogDensity() const { return _fogDensity; } + }; + VERUS_TYPEDEFS(Water); } diff --git a/Verus/src/World/World.h b/Verus/src/World/World.h index 9ab5183..785c05e 100644 --- a/Verus/src/World/World.h +++ b/Verus/src/World/World.h @@ -7,48 +7,45 @@ # pragma message("VERUS_WORLD_FORCE_FLAGS is defined") #endif -namespace verus +namespace verus::World { - namespace World + enum class DrawDepth : int { - enum class DrawDepth : int - { - no, - yes, - automatic - }; + no, + yes, + automatic + }; - enum class DrawSimpleMode : int - { - envMap, - planarReflection - }; + enum class DrawSimpleMode : int + { + envMap, + planarReflection + }; - enum class DrawEditorOverlaysFlags : UINT32 - { - none = 0, - bounds = (1 << 0), - extras = (1 << 1), - unbounded = (1 << 2) - }; + enum class DrawEditorOverlaysFlags : UINT32 + { + none = 0, + bounds = (1 << 0), + extras = (1 << 1), + unbounded = (1 << 2) + }; - enum class HierarchyDuplication : UINT32 - { - no = 0, - yes = (1 << 0), - withProbability = (1 << 1), - generated = (1 << 2) - }; + enum class HierarchyDuplication : UINT32 + { + no = 0, + yes = (1 << 0), + withProbability = (1 << 1), + generated = (1 << 2) + }; - class ShadowMapHandle : public BaseHandle - { - public: - static ShadowMapHandle Make(int value) { return BaseHandle::Make(value); } + class ShadowMapHandle : public BaseHandle + { + public: + static ShadowMapHandle Make(int value) { return BaseHandle::Make(value); } - UINT32 GetBlockIndex() const { return Get() >> 16; } - UINT32 GetCellIndex() const { return Get() & 0xFFFF; } - }; - } + UINT32 GetBlockIndex() const { return Get() >> 16; } + UINT32 GetCellIndex() const { return Get() & 0xFFFF; } + }; } #include "Camera.h" diff --git a/Verus/src/World/WorldManager.cpp b/Verus/src/World/WorldManager.cpp index 21567e9..8cf9a9d 100644 --- a/Verus/src/World/WorldManager.cpp +++ b/Verus/src/World/WorldManager.cpp @@ -68,8 +68,8 @@ void WorldManager::Done() void WorldManager::ResetInstanceCount() { - for (auto& x : TStoreModelNodes::_map) - x.second.GetMesh().ResetInstanceCount(); + for (auto& [key, value] : TStoreModelNodes::_map) + value.GetMesh().ResetInstanceCount(); for (auto& x : TStoreTerrainNodes::_list) x.GetTerrain().ResetInstanceCount(); } @@ -82,9 +82,9 @@ void WorldManager::Update() if (!_async_loaded) { bool allModelsLoaded = true; - for (auto& x : TStoreModelNodes::_map) + for (auto& [key, value] : TStoreModelNodes::_map) { - if (!x.second.IsLoaded()) + if (!value.IsLoaded()) { allModelsLoaded = false; break; @@ -415,14 +415,14 @@ void WorldManager::DrawLights() PMesh pMesh = nullptr; auto DrawMesh = [cb](PMesh pMesh) - { - if (pMesh && !pMesh->IsInstanceBufferEmpty(true)) { - pMesh->UpdateStorageBuffer(0); - pMesh->UpdateInstanceBuffer(); - cb->DrawIndexed(pMesh->GetIndexCount(), pMesh->GetInstanceCount(true), 0, 0, pMesh->GetMarkedInstance()); - } - }; + if (pMesh && !pMesh->IsInstanceBufferEmpty(true)) + { + pMesh->UpdateStorageBuffer(0); + pMesh->UpdateInstanceBuffer(); + cb->DrawIndexed(pMesh->GetIndexCount(), pMesh->GetInstanceCount(true), 0, 0, pMesh->GetMarkedInstance()); + } + }; const int begin = FindOffsetFor(NodeType::light); const int end = begin + _visibleCountPerType[+NodeType::light]; @@ -515,14 +515,14 @@ void WorldManager::DrawAmbient() PMesh pMesh = nullptr; auto DrawMesh = [cb](PMesh pMesh) - { - if (pMesh && !pMesh->IsInstanceBufferEmpty(true)) { - pMesh->UpdateStorageBuffer(0); - pMesh->UpdateInstanceBuffer(); - cb->DrawIndexed(pMesh->GetIndexCount(), pMesh->GetInstanceCount(true), 0, 0, pMesh->GetMarkedInstance()); - } - }; + if (pMesh && !pMesh->IsInstanceBufferEmpty(true)) + { + pMesh->UpdateStorageBuffer(0); + pMesh->UpdateInstanceBuffer(); + cb->DrawIndexed(pMesh->GetIndexCount(), pMesh->GetInstanceCount(true), 0, 0, pMesh->GetMarkedInstance()); + } + }; const int begin = FindOffsetFor(NodeType::ambient); const int end = begin + _visibleCountPerType[+NodeType::ambient]; @@ -629,8 +629,8 @@ void WorldManager::DrawProjectNodes() void WorldManager::DrawTransparent() { - for (auto& x : TStoreParticlesNodes::_map) - x.second.Draw(); + for (auto& [key, value] : TStoreParticlesNodes::_map) + value.Draw(); } void WorldManager::DrawSelectedBounds() diff --git a/Verus/src/World/WorldManager.h b/Verus/src/World/WorldManager.h index cb94165..62cf2be 100644 --- a/Verus/src/World/WorldManager.h +++ b/Verus/src/World/WorldManager.h @@ -1,539 +1,536 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // Although references are considered to be safer, prefer using PBaseNode over RBaseNode, because: + // * You can pass nullptr to GetIndexOf and get the correct index value for nullptr (-1). + // * No need to dereference the deleted node when calling BroadcastOnNodeDeleted(), which is UB in C++. + // * In many algorithms nullptr can appear naturally and the code will look cleaner without extra checks. + // * this is prettier than *this. + typedef StoreUnique TStoreModelNodes; + typedef StoreUnique TStoreParticlesNodes; + typedef Store TStoreBaseNodes; + typedef Store TStoreAmbientNodes; + typedef Store TStoreBlockNodes; + typedef Store TStoreBlockChainNodes; + typedef Store TStoreControlPointNodes; + typedef Store TStoreEmitterNodes; + typedef Store TStoreInstanceNodes; + typedef Store TStoreLightNodes; + typedef Store TStorePathNodes; + typedef Store TStorePhysicsNodes; + typedef Store TStorePrefabNodes; + typedef Store TStoreProjectNodes; + typedef Store TStoreShakerNodes; + typedef Store TStoreSoundNodes; + typedef Store TStoreTerrainNodes; + class WorldManager : public Singleton, public Object, public Math::OctreeDelegate, + private TStoreModelNodes, private TStoreParticlesNodes, + private TStoreBaseNodes, private TStoreAmbientNodes, private TStoreBlockNodes, + private TStoreBlockChainNodes, private TStoreControlPointNodes, private TStoreEmitterNodes, + private TStoreInstanceNodes, private TStoreLightNodes, private TStorePathNodes, + private TStorePhysicsNodes, private TStorePrefabNodes, private TStoreProjectNodes, + private TStoreShakerNodes, private TStoreSoundNodes, private TStoreTerrainNodes { - // Although references are considered to be safer, prefer using PBaseNode over RBaseNode, because: - // * You can pass nullptr to GetIndexOf and get the correct index value for nullptr (-1). - // * No need to dereference the deleted node when calling BroadcastOnNodeDeleted(), which is UB in C++. - // * In many algorithms nullptr can appear naturally and the code will look cleaner without extra checks. - // * this is prettier than *this. - typedef StoreUnique TStoreModelNodes; - typedef StoreUnique TStoreParticlesNodes; - typedef Store TStoreBaseNodes; - typedef Store TStoreAmbientNodes; - typedef Store TStoreBlockNodes; - typedef Store TStoreBlockChainNodes; - typedef Store TStoreControlPointNodes; - typedef Store TStoreEmitterNodes; - typedef Store TStoreInstanceNodes; - typedef Store TStoreLightNodes; - typedef Store TStorePathNodes; - typedef Store TStorePhysicsNodes; - typedef Store TStorePrefabNodes; - typedef Store TStoreProjectNodes; - typedef Store TStoreShakerNodes; - typedef Store TStoreSoundNodes; - typedef Store TStoreTerrainNodes; - class WorldManager : public Singleton, public Object, public Math::OctreeDelegate, - private TStoreModelNodes, private TStoreParticlesNodes, - private TStoreBaseNodes, private TStoreAmbientNodes, private TStoreBlockNodes, - private TStoreBlockChainNodes, private TStoreControlPointNodes, private TStoreEmitterNodes, - private TStoreInstanceNodes, private TStoreLightNodes, private TStorePathNodes, - private TStorePhysicsNodes, private TStorePrefabNodes, private TStoreProjectNodes, - private TStoreShakerNodes, private TStoreSoundNodes, private TStoreTerrainNodes - { #include "../Shaders/DS.inc.hlsl" #include "../Shaders/DS_AmbientNode.inc.hlsl" - Math::Octree _octree; - LocalPtr _pPickingShape; - PCamera _pPassCamera = nullptr; // Render pass camera for getting view and projection matrices. - PMainCamera _pHeadCamera = nullptr; // Head camera which is located between the eyes. - PMainCamera _pViewCamera = nullptr; // Current view camera which is valid only inside DrawView method (eye camera). - PLightNode _pSmbpStatic = nullptr; - PLightNode _pSmbpDynamic[8]; - Vector _vNodes; - Vector _vVisibleNodes; - Random _random; - int _visibleCount = 0; - int _visibleCountPerType[+NodeType::count]; - int _worldSide = 0; - int _recursionDepth = 0; - int _smbpDynamicCount = 0; - int _smbpDynamicMax = 0; - float _pickingShapeHalfExtent = 0.05f; - float _lightsReserveShadowDist = 100; - float _lightsFreeShadowDist = 150; - bool _async_loaded = false; + Math::Octree _octree; + LocalPtr _pPickingShape; + PCamera _pPassCamera = nullptr; // Render pass camera for getting view and projection matrices. + PMainCamera _pHeadCamera = nullptr; // Head camera which is located between the eyes. + PMainCamera _pViewCamera = nullptr; // Current view camera which is valid only inside DrawView method (eye camera). + PLightNode _pSmbpStatic = nullptr; + PLightNode _pSmbpDynamic[8]; + Vector _vNodes; + Vector _vVisibleNodes; + Random _random; + int _visibleCount = 0; + int _visibleCountPerType[+NodeType::count]; + int _worldSide = 0; + int _recursionDepth = 0; + int _smbpDynamicCount = 0; + int _smbpDynamicMax = 0; + float _pickingShapeHalfExtent = 0.05f; + float _lightsReserveShadowDist = 100; + float _lightsFreeShadowDist = 150; + bool _async_loaded = false; - public: - struct Desc + public: + struct Desc + { + PMainCamera _pCamera = nullptr; + int _worldSide = 256; + + Desc() {} + }; + VERUS_TYPEDEFS(Desc); + + struct Query + { + PBaseNode _pParent = nullptr; + CSZ _name = nullptr; + CSZ _blockMesh = nullptr; + CSZ _blockMaterial = nullptr; + CSZ _particlesURL = nullptr; + NodeType _type = NodeType::unknown; + int _selected = -1; + + void Reset() { *this = Query(); } + }; + VERUS_TYPEDEFS(Query); + + WorldManager(); + virtual ~WorldManager(); + + void Init(RcDesc desc = Desc()); + void Done(); + + void ResetInstanceCount(); + void Update(); + void UpdateParts(); + void Layout(); + void SortVisible(); + void Draw(); + void DrawSimple(DrawSimpleMode mode); + void DrawTerrainNodes(Terrain::RcDrawDesc dd); + void DrawTerrainNodesSimple(DrawSimpleMode mode); + void DrawLights(); + void DrawAmbient(); + void DrawProjectNodes(); + void DrawTransparent(); + void DrawSelectedBounds(); + void DrawSelectedRelationshipLines(); + void DrawEditorOverlays(DrawEditorOverlaysFlags flags); + + static bool IsDrawingDepth(DrawDepth dd); + + static int GetEditorOverlaysAlpha(int originalAlpha, float distSq, float fadeDistSq); + + // + PLightNode GetSmbpStatic() const { return _pSmbpStatic; } + PLightNode GetSmbpDynamic(int index) const { return _pSmbpDynamic[index]; } + int GetSmbpDynamicCount() const { return _smbpDynamicCount; } + bool IsSmbpDynamic(PcLightNode pLightNode) const; + int GetInfluentialLightsAt(Math::RcSphere sphere, PLightNode lightNodes[], int maxLights = 4, bool forShadow = true, bool incDir = false); + void InfluentialLightsToSmbpDynamic(Math::RcSphere sphere); + // + + // + PCamera GetPassCamera() const { return _pPassCamera; } + PMainCamera GetHeadCamera() const { return _pHeadCamera; } + PMainCamera GetViewCamera() const { return _pViewCamera; } + PCamera SetPassCamera(PCamera p) { return Utils::Swap(_pPassCamera, p); } + PMainCamera SetHeadCamera(PMainCamera p) { return Utils::Swap(_pHeadCamera, p); } + PMainCamera SetViewCamera(PMainCamera p) { return Utils::Swap(_pViewCamera, p); } + void SetAllCameras(PMainCamera p) { _pPassCamera = _pHeadCamera = _pViewCamera = p; } + // + + // Octree (Acceleration Structure): + Math::ROctree GetOctree() { return _octree; } + virtual Continue Octree_OnElementDetected(void* pToken, void* pUser) override; + + bool RayTest(RcPoint3 pointA, RcPoint3 pointB, Physics::Group mask = Physics::Group::all); + bool RayTestEx(RcPoint3 pointA, RcPoint3 pointB, PBlockNodePtr pBlock = nullptr, + PPoint3 pPoint = nullptr, PVector3 pNormal = nullptr, const float* pRadius = nullptr, + Physics::Group mask = Physics::Group::all); + Matrix3 GetBasisAt(RcPoint3 point, Physics::Group mask = Physics::Group::immovable) const; + + btBoxShape* GetPickingShape(); + float GetPickingShapeHalfExtent() const { return _pickingShapeHalfExtent; } + + template + void ForEachNode(const T& fn) + { + const int nodeCount = GetNodeCount(); + VERUS_FOR(i, nodeCount) { - PMainCamera _pCamera = nullptr; - int _worldSide = 256; - - Desc() {} - }; - VERUS_TYPEDEFS(Desc); - - struct Query - { - PBaseNode _pParent = nullptr; - CSZ _name = nullptr; - CSZ _blockMesh = nullptr; - CSZ _blockMaterial = nullptr; - CSZ _particlesURL = nullptr; - NodeType _type = NodeType::unknown; - int _selected = -1; - - void Reset() { *this = Query(); } - }; - VERUS_TYPEDEFS(Query); - - WorldManager(); - virtual ~WorldManager(); - - void Init(RcDesc desc = Desc()); - void Done(); - - void ResetInstanceCount(); - void Update(); - void UpdateParts(); - void Layout(); - void SortVisible(); - void Draw(); - void DrawSimple(DrawSimpleMode mode); - void DrawTerrainNodes(Terrain::RcDrawDesc dd); - void DrawTerrainNodesSimple(DrawSimpleMode mode); - void DrawLights(); - void DrawAmbient(); - void DrawProjectNodes(); - void DrawTransparent(); - void DrawSelectedBounds(); - void DrawSelectedRelationshipLines(); - void DrawEditorOverlays(DrawEditorOverlaysFlags flags); - - static bool IsDrawingDepth(DrawDepth dd); - - static int GetEditorOverlaysAlpha(int originalAlpha, float distSq, float fadeDistSq); - - // - PLightNode GetSmbpStatic() const { return _pSmbpStatic; } - PLightNode GetSmbpDynamic(int index) const { return _pSmbpDynamic[index]; } - int GetSmbpDynamicCount() const { return _smbpDynamicCount; } - bool IsSmbpDynamic(PcLightNode pLightNode) const; - int GetInfluentialLightsAt(Math::RcSphere sphere, PLightNode lightNodes[], int maxLights = 4, bool forShadow = true, bool incDir = false); - void InfluentialLightsToSmbpDynamic(Math::RcSphere sphere); - // - - // - PCamera GetPassCamera() const { return _pPassCamera; } - PMainCamera GetHeadCamera() const { return _pHeadCamera; } - PMainCamera GetViewCamera() const { return _pViewCamera; } - PCamera SetPassCamera(PCamera p) { return Utils::Swap(_pPassCamera, p); } - PMainCamera SetHeadCamera(PMainCamera p) { return Utils::Swap(_pHeadCamera, p); } - PMainCamera SetViewCamera(PMainCamera p) { return Utils::Swap(_pViewCamera, p); } - void SetAllCameras(PMainCamera p) { _pPassCamera = _pHeadCamera = _pViewCamera = p; } - // - - // Octree (Acceleration Structure): - Math::ROctree GetOctree() { return _octree; } - virtual Continue Octree_OnElementDetected(void* pToken, void* pUser) override; - - bool RayTest(RcPoint3 pointA, RcPoint3 pointB, Physics::Group mask = Physics::Group::all); - bool RayTestEx(RcPoint3 pointA, RcPoint3 pointB, PBlockNodePtr pBlock = nullptr, - PPoint3 pPoint = nullptr, PVector3 pNormal = nullptr, const float* pRadius = nullptr, - Physics::Group mask = Physics::Group::all); - Matrix3 GetBasisAt(RcPoint3 point, Physics::Group mask = Physics::Group::immovable) const; - - btBoxShape* GetPickingShape(); - float GetPickingShapeHalfExtent() const { return _pickingShapeHalfExtent; } - - template - void ForEachNode(const T& fn) - { - const int nodeCount = GetNodeCount(); - VERUS_FOR(i, nodeCount) - { - PBaseNode pNode = _vNodes[i]; - const bool hasChildren = (i + 1 < nodeCount) && _vNodes[i + 1]->GetDepth() > pNode->GetDepth(); - if (Continue::no == fn(*pNode, hasChildren)) - return; - } + PBaseNode pNode = _vNodes[i]; + const bool hasChildren = (i + 1 < nodeCount) && _vNodes[i + 1]->GetDepth() > pNode->GetDepth(); + if (Continue::no == fn(*pNode, hasChildren)) + return; } + } - template - void ForEachNode(RcQuery query, const T& fn) - { - auto MatchName = [&query](RBaseNode node) + template + void ForEachNode(RcQuery query, const T& fn) + { + auto MatchName = [&query](RBaseNode node) { return !query._name || node.GetName() == query._name; }; - auto MatchSelected = [&query](RBaseNode node) + auto MatchSelected = [&query](RBaseNode node) { return -1 == query._selected || !!query._selected == node.IsSelected(); }; - auto MatchParent = [&query](RBaseNode node) + auto MatchParent = [&query](RBaseNode node) { return !query._pParent || node.GetParent() == query._pParent; }; - if (NodeType::unknown == query._type || NodeType::block == query._type) - { - VERUS_FOREACH_X(TStoreBlockNodes::TList, TStoreBlockNodes::_list, it) - { - auto& block = *it++; - if ( - MatchName(block) && - MatchSelected(block) && - MatchParent(block) && - (!query._blockMesh || block.GetURL() == query._blockMesh) && - (!query._blockMaterial || block.GetMaterial()->_name == query._blockMaterial)) - if (Continue::no == fn(block)) - return; - } - } - - if (query._blockMesh || query._blockMaterial) - return; - - if (NodeType::unknown == query._type || NodeType::base == query._type) - { - VERUS_FOREACH_X(TStoreBaseNodes::TList, TStoreBaseNodes::_list, it) - { - auto& node = *it++; - if ( - MatchName(node) && - MatchSelected(node) && - MatchParent(node)) - if (Continue::no == fn(node)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::model == query._type) - { - VERUS_FOREACH_X(TStoreModelNodes::TMap, TStoreModelNodes::_map, it) - { - auto& model = it->second; - it++; - if ( - MatchName(model) && - MatchSelected(model) && - MatchParent(model)) - if (Continue::no == fn(model)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::particles == query._type) - { - VERUS_FOREACH_X(TStoreParticlesNodes::TMap, TStoreParticlesNodes::_map, it) - { - auto& particles = it->second; - it++; - if ( - MatchName(particles) && - MatchSelected(particles) && - MatchParent(particles) && - (!query._particlesURL || particles.GetURL() == query._particlesURL)) - if (Continue::no == fn(particles)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::ambient == query._type) - { - VERUS_FOREACH_X(TStoreAmbientNodes::TList, TStoreAmbientNodes::_list, it) - { - auto& ambient = *it++; - if ( - MatchName(ambient) && - MatchSelected(ambient) && - MatchParent(ambient)) - if (Continue::no == fn(ambient)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::blockChain == query._type) - { - VERUS_FOREACH_X(TStoreBlockChainNodes::TList, TStoreBlockChainNodes::_list, it) - { - auto& blockChain = *it++; - if ( - MatchName(blockChain) && - MatchSelected(blockChain) && - MatchParent(blockChain)) - if (Continue::no == fn(blockChain)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::controlPoint == query._type) - { - VERUS_FOREACH_X(TStoreControlPointNodes::TList, TStoreControlPointNodes::_list, it) - { - auto& controlPoint = *it++; - if ( - MatchName(controlPoint) && - MatchSelected(controlPoint) && - MatchParent(controlPoint)) - if (Continue::no == fn(controlPoint)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::emitter == query._type) - { - VERUS_FOREACH_X(TStoreEmitterNodes::TList, TStoreEmitterNodes::_list, it) - { - auto& emitter = *it++; - if ( - MatchName(emitter) && - MatchSelected(emitter) && - MatchParent(emitter) && - (!query._particlesURL || emitter.GetURL() == query._particlesURL)) - if (Continue::no == fn(emitter)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::instance == query._type) - { - VERUS_FOREACH_X(TStoreInstanceNodes::TList, TStoreInstanceNodes::_list, it) - { - auto& instance = *it++; - if ( - MatchName(instance) && - MatchSelected(instance) && - MatchParent(instance)) - if (Continue::no == fn(instance)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::light == query._type) - { - VERUS_FOREACH_X(TStoreLightNodes::TList, TStoreLightNodes::_list, it) - { - auto& light = *it++; - if ( - MatchName(light) && - MatchSelected(light) && - MatchParent(light)) - if (Continue::no == fn(light)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::path == query._type) - { - VERUS_FOREACH_X(TStorePathNodes::TList, TStorePathNodes::_list, it) - { - auto& path = *it++; - if ( - MatchName(path) && - MatchSelected(path) && - MatchParent(path)) - if (Continue::no == fn(path)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::physics == query._type) - { - VERUS_FOREACH_X(TStorePhysicsNodes::TList, TStorePhysicsNodes::_list, it) - { - auto& physics = *it++; - if ( - MatchName(physics) && - MatchSelected(physics) && - MatchParent(physics)) - if (Continue::no == fn(physics)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::prefab == query._type) - { - VERUS_FOREACH_X(TStorePrefabNodes::TList, TStorePrefabNodes::_list, it) - { - auto& prefab = *it++; - if ( - MatchName(prefab) && - MatchSelected(prefab) && - MatchParent(prefab)) - if (Continue::no == fn(prefab)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::project == query._type) - { - VERUS_FOREACH_X(TStoreProjectNodes::TList, TStoreProjectNodes::_list, it) - { - auto& project = *it++; - if ( - MatchName(project) && - MatchSelected(project) && - MatchParent(project)) - if (Continue::no == fn(project)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::shaker == query._type) - { - VERUS_FOREACH_X(TStoreShakerNodes::TList, TStoreShakerNodes::_list, it) - { - auto& shaker = *it++; - if ( - MatchName(shaker) && - MatchSelected(shaker) && - MatchParent(shaker)) - if (Continue::no == fn(shaker)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::sound == query._type) - { - VERUS_FOREACH_X(TStoreSoundNodes::TList, TStoreSoundNodes::_list, it) - { - auto& sound = *it++; - if ( - MatchName(sound) && - MatchSelected(sound) && - MatchParent(sound)) - if (Continue::no == fn(sound)) - return; - } - } - - if (NodeType::unknown == query._type || NodeType::terrain == query._type) - { - VERUS_FOREACH_X(TStoreTerrainNodes::TList, TStoreTerrainNodes::_list, it) - { - auto& terrain = *it++; - if ( - MatchName(terrain) && - MatchSelected(terrain) && - MatchParent(terrain)) - if (Continue::no == fn(terrain)) - return; - } - } - } - - template - void ForEachControlPointOf(PPathNode pPathNode, bool onlyHeads, const T& fn) + if (NodeType::unknown == query._type || NodeType::block == query._type) { - const int nodeCount = GetNodeCount(); - for (int i = GetIndexOf(pPathNode) + 1; i < nodeCount; ++i) + VERUS_FOREACH_X(TStoreBlockNodes::TList, TStoreBlockNodes::_list, it) { - PBaseNode pNode = _vNodes[i]; - if (pNode->GetDepth() <= pPathNode->GetDepth()) - break; - if (NodeType::controlPoint == pNode->GetType()) - { - PControlPointNode pControlPointNode = static_cast(pNode); - if (!onlyHeads || pControlPointNode->IsHeadControlPoint()) - { - if (Continue::no == fn(pControlPointNode)) - return; - } - } + auto& block = *it++; + if ( + MatchName(block) && + MatchSelected(block) && + MatchParent(block) && + (!query._blockMesh || block.GetURL() == query._blockMesh) && + (!query._blockMaterial || block.GetMaterial()->_name == query._blockMaterial)) + if (Continue::no == fn(block)) + return; } } - // - String EnsureUniqueName(CSZ name, PcBaseNode pSkipNode = nullptr); - void SortNodes(); - int FindOffsetFor(NodeType type) const; + if (query._blockMesh || query._blockMaterial) + return; - int GetNodeCount(int* pPerType = nullptr, bool excludeGenerated = false) const; - int GetIndexOf(PcBaseNode pTargetNode, bool excludeGenerated = false) const; - PBaseNode GetNodeByIndex(int index) const; + if (NodeType::unknown == query._type || NodeType::base == query._type) + { + VERUS_FOREACH_X(TStoreBaseNodes::TList, TStoreBaseNodes::_list, it) + { + auto& node = *it++; + if ( + MatchName(node) && + MatchSelected(node) && + MatchParent(node)) + if (Continue::no == fn(node)) + return; + } + } - static bool IsAncestorOf(PcBaseNode pNodeA, PcBaseNode pNodeB); - static bool HasAncestorOfType(NodeType type, PcBaseNode pNode); + if (NodeType::unknown == query._type || NodeType::model == query._type) + { + VERUS_FOREACH_X(TStoreModelNodes::TMap, TStoreModelNodes::_map, it) + { + auto& model = it->second; + it++; + if ( + MatchName(model) && + MatchSelected(model) && + MatchParent(model)) + if (Continue::no == fn(model)) + return; + } + } - bool IsValidNode(PcBaseNode pTargetNode); - void DeleteNode(PBaseNode pTargetNode, bool hierarchy = true); - void DeleteNode(NodeType type, CSZ name, bool hierarchy = true); - void DeleteAllNodes(); + if (NodeType::unknown == query._type || NodeType::particles == query._type) + { + VERUS_FOREACH_X(TStoreParticlesNodes::TMap, TStoreParticlesNodes::_map, it) + { + auto& particles = it->second; + it++; + if ( + MatchName(particles) && + MatchSelected(particles) && + MatchParent(particles) && + (!query._particlesURL || particles.GetURL() == query._particlesURL)) + if (Continue::no == fn(particles)) + return; + } + } - PBaseNode DuplicateNode(PBaseNode pTargetNode, HierarchyDuplication hierarchyDuplication); + if (NodeType::unknown == query._type || NodeType::ambient == query._type) + { + VERUS_FOREACH_X(TStoreAmbientNodes::TList, TStoreAmbientNodes::_list, it) + { + auto& ambient = *it++; + if ( + MatchName(ambient) && + MatchSelected(ambient) && + MatchParent(ambient)) + if (Continue::no == fn(ambient)) + return; + } + } - void EnableAll(); - void EnableSelected(); - void DisableAll(); - void DisableSelected(); + if (NodeType::unknown == query._type || NodeType::blockChain == query._type) + { + VERUS_FOREACH_X(TStoreBlockChainNodes::TList, TStoreBlockChainNodes::_list, it) + { + auto& blockChain = *it++; + if ( + MatchName(blockChain) && + MatchSelected(blockChain) && + MatchParent(blockChain)) + if (Continue::no == fn(blockChain)) + return; + } + } - void SelectAll(); - void SelectAllInsideSphere(Math::RcSphere sphere); - void ClearSelection(); - void InvertSelection(); - int GetSelectedCount(); - void SelectAllChildNodes(PBaseNode pTargetNode); + if (NodeType::unknown == query._type || NodeType::controlPoint == query._type) + { + VERUS_FOREACH_X(TStoreControlPointNodes::TList, TStoreControlPointNodes::_list, it) + { + auto& controlPoint = *it++; + if ( + MatchName(controlPoint) && + MatchSelected(controlPoint) && + MatchParent(controlPoint)) + if (Continue::no == fn(controlPoint)) + return; + } + } - void ResetRigidBodyTransforms(); + if (NodeType::unknown == query._type || NodeType::emitter == query._type) + { + VERUS_FOREACH_X(TStoreEmitterNodes::TList, TStoreEmitterNodes::_list, it) + { + auto& emitter = *it++; + if ( + MatchName(emitter) && + MatchSelected(emitter) && + MatchParent(emitter) && + (!query._particlesURL || emitter.GetURL() == query._particlesURL)) + if (Continue::no == fn(emitter)) + return; + } + } - void GenerateBlockChainNodes(PBlockChainNode pBlockChainNode); - static bool Connect2ControlPoints(PControlPointNode pNodeA, PControlPointNode pNodeB); - void UpdatePrefabInstances(PPrefabNode pPrefabNode, bool sortNodes = true); - void ReplaceSimilarWithInstances(PPrefabNode pPrefabNode); - // + if (NodeType::unknown == query._type || NodeType::instance == query._type) + { + VERUS_FOREACH_X(TStoreInstanceNodes::TList, TStoreInstanceNodes::_list, it) + { + auto& instance = *it++; + if ( + MatchName(instance) && + MatchSelected(instance) && + MatchParent(instance)) + if (Continue::no == fn(instance)) + return; + } + } - PModelNode InsertModelNode(CSZ url); - PModelNode FindModelNode(CSZ url); + if (NodeType::unknown == query._type || NodeType::light == query._type) + { + VERUS_FOREACH_X(TStoreLightNodes::TList, TStoreLightNodes::_list, it) + { + auto& light = *it++; + if ( + MatchName(light) && + MatchSelected(light) && + MatchParent(light)) + if (Continue::no == fn(light)) + return; + } + } - PParticlesNode InsertParticlesNode(CSZ url); - PParticlesNode FindParticlesNode(CSZ url); + if (NodeType::unknown == query._type || NodeType::path == query._type) + { + VERUS_FOREACH_X(TStorePathNodes::TList, TStorePathNodes::_list, it) + { + auto& path = *it++; + if ( + MatchName(path) && + MatchSelected(path) && + MatchParent(path)) + if (Continue::no == fn(path)) + return; + } + } - PBaseNode InsertBaseNode(); + if (NodeType::unknown == query._type || NodeType::physics == query._type) + { + VERUS_FOREACH_X(TStorePhysicsNodes::TList, TStorePhysicsNodes::_list, it) + { + auto& physics = *it++; + if ( + MatchName(physics) && + MatchSelected(physics) && + MatchParent(physics)) + if (Continue::no == fn(physics)) + return; + } + } - PAmbientNode InsertAmbientNode(); + if (NodeType::unknown == query._type || NodeType::prefab == query._type) + { + VERUS_FOREACH_X(TStorePrefabNodes::TList, TStorePrefabNodes::_list, it) + { + auto& prefab = *it++; + if ( + MatchName(prefab) && + MatchSelected(prefab) && + MatchParent(prefab)) + if (Continue::no == fn(prefab)) + return; + } + } - PBlockNode InsertBlockNode(); + if (NodeType::unknown == query._type || NodeType::project == query._type) + { + VERUS_FOREACH_X(TStoreProjectNodes::TList, TStoreProjectNodes::_list, it) + { + auto& project = *it++; + if ( + MatchName(project) && + MatchSelected(project) && + MatchParent(project)) + if (Continue::no == fn(project)) + return; + } + } - PBlockChainNode InsertBlockChainNode(); + if (NodeType::unknown == query._type || NodeType::shaker == query._type) + { + VERUS_FOREACH_X(TStoreShakerNodes::TList, TStoreShakerNodes::_list, it) + { + auto& shaker = *it++; + if ( + MatchName(shaker) && + MatchSelected(shaker) && + MatchParent(shaker)) + if (Continue::no == fn(shaker)) + return; + } + } - PControlPointNode InsertControlPointNode(); + if (NodeType::unknown == query._type || NodeType::sound == query._type) + { + VERUS_FOREACH_X(TStoreSoundNodes::TList, TStoreSoundNodes::_list, it) + { + auto& sound = *it++; + if ( + MatchName(sound) && + MatchSelected(sound) && + MatchParent(sound)) + if (Continue::no == fn(sound)) + return; + } + } - PEmitterNode InsertEmitterNode(); + if (NodeType::unknown == query._type || NodeType::terrain == query._type) + { + VERUS_FOREACH_X(TStoreTerrainNodes::TList, TStoreTerrainNodes::_list, it) + { + auto& terrain = *it++; + if ( + MatchName(terrain) && + MatchSelected(terrain) && + MatchParent(terrain)) + if (Continue::no == fn(terrain)) + return; + } + } + } - PInstanceNode InsertInstanceNode(); + template + void ForEachControlPointOf(PPathNode pPathNode, bool onlyHeads, const T& fn) + { + const int nodeCount = GetNodeCount(); + for (int i = GetIndexOf(pPathNode) + 1; i < nodeCount; ++i) + { + PBaseNode pNode = _vNodes[i]; + if (pNode->GetDepth() <= pPathNode->GetDepth()) + break; + if (NodeType::controlPoint == pNode->GetType()) + { + PControlPointNode pControlPointNode = static_cast(pNode); + if (!onlyHeads || pControlPointNode->IsHeadControlPoint()) + { + if (Continue::no == fn(pControlPointNode)) + return; + } + } + } + } - PLightNode InsertLightNode(); + // + String EnsureUniqueName(CSZ name, PcBaseNode pSkipNode = nullptr); + void SortNodes(); + int FindOffsetFor(NodeType type) const; - PPathNode InsertPathNode(); + int GetNodeCount(int* pPerType = nullptr, bool excludeGenerated = false) const; + int GetIndexOf(PcBaseNode pTargetNode, bool excludeGenerated = false) const; + PBaseNode GetNodeByIndex(int index) const; - PPhysicsNode InsertPhysicsNode(); + static bool IsAncestorOf(PcBaseNode pNodeA, PcBaseNode pNodeB); + static bool HasAncestorOfType(NodeType type, PcBaseNode pNode); - PPrefabNode InsertPrefabNode(); + bool IsValidNode(PcBaseNode pTargetNode); + void DeleteNode(PBaseNode pTargetNode, bool hierarchy = true); + void DeleteNode(NodeType type, CSZ name, bool hierarchy = true); + void DeleteAllNodes(); - PProjectNode InsertProjectNode(); + PBaseNode DuplicateNode(PBaseNode pTargetNode, HierarchyDuplication hierarchyDuplication); - PShakerNode InsertShakerNode(); + void EnableAll(); + void EnableSelected(); + void DisableAll(); + void DisableSelected(); - PSoundNode InsertSoundNode(); + void SelectAll(); + void SelectAllInsideSphere(Math::RcSphere sphere); + void ClearSelection(); + void InvertSelection(); + int GetSelectedCount(); + void SelectAllChildNodes(PBaseNode pTargetNode); - PTerrainNode InsertTerrainNode(); + void ResetRigidBodyTransforms(); - // - void BroadcastOnNodeDeleted(PBaseNode pTargetNode, bool afterEvent, bool hierarchy); - void BroadcastOnNodeDuplicated(PBaseNode pTargetNode, bool afterEvent, PBaseNode pDuplicatedNode, HierarchyDuplication hierarchyDuplication); - void BroadcastOnNodeParentChanged(PBaseNode pTargetNode, bool afterEvent); - void BroadcastOnNodeRigidBodyTransformUpdated(PBaseNode pTargetNode, bool afterEvent); - void BroadcastOnNodeTransformed(PBaseNode pTargetNode, bool afterEvent); - // + void GenerateBlockChainNodes(PBlockChainNode pBlockChainNode); + static bool Connect2ControlPoints(PControlPointNode pNodeA, PControlPointNode pNodeB); + void UpdatePrefabInstances(PPrefabNode pPrefabNode, bool sortNodes = true); + void ReplaceSimilarWithInstances(PPrefabNode pPrefabNode); + // - // - void Serialize(IO::RSeekableStream stream); - void Deserialize(IO::RStream stream); - void Deserialize_LegacyXXX(IO::RStream stream); - static UINT32 NodeTypeToHash(NodeType type); - static NodeType HashToNodeType(UINT32 hash); - // + PModelNode InsertModelNode(CSZ url); + PModelNode FindModelNode(CSZ url); - static UINT32 NodeTypeToColor(NodeType type, int alpha = 255); - static int GetNodeTypePriority(NodeType type); - }; - VERUS_TYPEDEFS(WorldManager); - } + PParticlesNode InsertParticlesNode(CSZ url); + PParticlesNode FindParticlesNode(CSZ url); + + PBaseNode InsertBaseNode(); + + PAmbientNode InsertAmbientNode(); + + PBlockNode InsertBlockNode(); + + PBlockChainNode InsertBlockChainNode(); + + PControlPointNode InsertControlPointNode(); + + PEmitterNode InsertEmitterNode(); + + PInstanceNode InsertInstanceNode(); + + PLightNode InsertLightNode(); + + PPathNode InsertPathNode(); + + PPhysicsNode InsertPhysicsNode(); + + PPrefabNode InsertPrefabNode(); + + PProjectNode InsertProjectNode(); + + PShakerNode InsertShakerNode(); + + PSoundNode InsertSoundNode(); + + PTerrainNode InsertTerrainNode(); + + // + void BroadcastOnNodeDeleted(PBaseNode pTargetNode, bool afterEvent, bool hierarchy); + void BroadcastOnNodeDuplicated(PBaseNode pTargetNode, bool afterEvent, PBaseNode pDuplicatedNode, HierarchyDuplication hierarchyDuplication); + void BroadcastOnNodeParentChanged(PBaseNode pTargetNode, bool afterEvent); + void BroadcastOnNodeRigidBodyTransformUpdated(PBaseNode pTargetNode, bool afterEvent); + void BroadcastOnNodeTransformed(PBaseNode pTargetNode, bool afterEvent); + // + + // + void Serialize(IO::RSeekableStream stream); + void Deserialize(IO::RStream stream); + void Deserialize_LegacyXXX(IO::RStream stream); + static UINT32 NodeTypeToHash(NodeType type); + static NodeType HashToNodeType(UINT32 hash); + // + + static UINT32 NodeTypeToColor(NodeType type, int alpha = 255); + static int GetNodeTypePriority(NodeType type); + }; + VERUS_TYPEDEFS(WorldManager); } diff --git a/Verus/src/World/WorldNodes/AmbientNode.h b/Verus/src/World/WorldNodes/AmbientNode.h index b27008c..ee4654c 100644 --- a/Verus/src/World/WorldNodes/AmbientNode.h +++ b/Verus/src/World/WorldNodes/AmbientNode.h @@ -1,92 +1,89 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class AmbientNode : public BaseNode { - class AmbientNode : public BaseNode + public: + enum class Priority : int { - public: - enum class Priority : int - { - mulSky, - add, - mul - }; - - private: - Transform3 _trToBoxSpace = Transform3::identity(); - Vector4 _color = Vector4(0, 0, 0, 1); - float _wall = 0.5f; - float _cylindrical = 0; - float _spherical = 0; - Priority _priority = Priority::mulSky; - - public: - struct Desc : BaseNode::Desc - { - Desc(CSZ name = nullptr) : BaseNode::Desc(name) {} - }; - VERUS_TYPEDEFS(Desc); - - AmbientNode(); - virtual ~AmbientNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; - - // - virtual void GetEditorCommands(Vector& v) override; - virtual void ExecuteEditorCommand(RcEditorCommand command) override; - // - - virtual void UpdateBounds() override; - - virtual void OnNodeTransformed(PBaseNode pNode, bool afterEvent) override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - Priority GetPriority() const; - void SetPriority(Priority priority); - Vector3 GetColor() const; - void SetColor(RcVector3 color); - float GetIntensity() const; - void SetIntensity(float i); - float GetWall() const; - void SetWall(float wall); - float GetCylindrical() const; - void SetCylindrical(float x); - float GetSpherical() const; - void SetSpherical(float x); - Vector4 GetInstData() const; - - RcTransform3 GetToBoxSpaceTransform() const { return _trToBoxSpace; } - - void FitParentBlock(); - void FillTheRoom(); + mulSky, + add, + mul }; - VERUS_TYPEDEFS(AmbientNode); - class AmbientNodePtr : public Ptr + private: + Transform3 _trToBoxSpace = Transform3::identity(); + Vector4 _color = Vector4(0, 0, 0, 1); + float _wall = 0.5f; + float _cylindrical = 0; + float _spherical = 0; + Priority _priority = Priority::mulSky; + + public: + struct Desc : BaseNode::Desc { - public: - void Init(AmbientNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + Desc(CSZ name = nullptr) : BaseNode::Desc(name) {} }; - VERUS_TYPEDEFS(AmbientNodePtr); + VERUS_TYPEDEFS(Desc); - class AmbientNodePwn : public AmbientNodePtr - { - public: - ~AmbientNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(AmbientNodePwn); - } + AmbientNode(); + virtual ~AmbientNode(); + + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; + + // + virtual void GetEditorCommands(Vector& v) override; + virtual void ExecuteEditorCommand(RcEditorCommand command) override; + // + + virtual void UpdateBounds() override; + + virtual void OnNodeTransformed(PBaseNode pNode, bool afterEvent) override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + Priority GetPriority() const; + void SetPriority(Priority priority); + Vector3 GetColor() const; + void SetColor(RcVector3 color); + float GetIntensity() const; + void SetIntensity(float i); + float GetWall() const; + void SetWall(float wall); + float GetCylindrical() const; + void SetCylindrical(float x); + float GetSpherical() const; + void SetSpherical(float x); + Vector4 GetInstData() const; + + RcTransform3 GetToBoxSpaceTransform() const { return _trToBoxSpace; } + + void FitParentBlock(); + void FillTheRoom(); + }; + VERUS_TYPEDEFS(AmbientNode); + + class AmbientNodePtr : public Ptr + { + public: + void Init(AmbientNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(AmbientNodePtr); + + class AmbientNodePwn : public AmbientNodePtr + { + public: + ~AmbientNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(AmbientNodePwn); } diff --git a/Verus/src/World/WorldNodes/BaseNode.h b/Verus/src/World/WorldNodes/BaseNode.h index 75a56d9..f97d891 100644 --- a/Verus/src/World/WorldNodes/BaseNode.h +++ b/Verus/src/World/WorldNodes/BaseNode.h @@ -1,197 +1,194 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // BaseNode is a base node for all other nodes. + // * has a name + // * can be parent or child + // * has generic properties + // * has transformation + // * has bounds + class BaseNode : public Physics::UserPtr, public Object, public AllocatorAware { - // BaseNode is a base node for all other nodes. - // * has a name - // * can be parent or child - // * has generic properties - // * has transformation - // * has bounds - class BaseNode : public Physics::UserPtr, public Object, public AllocatorAware + protected: + enum class Flags : UINT32 { - protected: - enum class Flags : UINT32 - { - none = 0, - octreeElement = (1 << 0), - octreeBindOnce = (1 << 1), - dynamic = (1 << 2), // Will be bound to the root of octree. - generated = (1 << 3), // Created by some other node. - disabled = (1 << 4), // Draw method will not be called. - selected = (1 << 5), - shadow = (1 << 6), - reserveShadow = (1 << 7), + none = 0, + octreeElement = (1 << 0), + octreeBindOnce = (1 << 1), + dynamic = (1 << 2), // Will be bound to the root of octree. + generated = (1 << 3), // Created by some other node. + disabled = (1 << 4), // Draw method will not be called. + selected = (1 << 5), + shadow = (1 << 6), + reserveShadow = (1 << 7), - readOnlyFlags = (1u << 31), - serializedMask = ~(octreeBindOnce | generated | selected | reserveShadow) - }; - - Transform3 _trLocal = Transform3::identity(); - Transform3 _trGlobal = Transform3::identity(); - Vector3 _uiRotation = Vector3(0); // User-friendly rotation used in editor's UI. - Vector3 _uiScale = Vector3(1, 1, 1); // User-friendly scale used in editor's UI. - Math::Bounds _bounds; - IO::Dictionary _dict; - btRigidBody* _pRigidBody = nullptr; - BaseNode* _pParent = nullptr; - String _name; - NodeType _type = NodeType::base; - Flags _flags = Flags::none; - UINT32 _groups = 0; - int _depth = 0; - - public: - struct Desc - { - CSZ _name = nullptr; - - Desc(CSZ name = nullptr) : _name(name) {} - }; - VERUS_TYPEDEFS(Desc); - - BaseNode(); - virtual ~BaseNode(); - - virtual int UserPtr_GetType() override; - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(BaseNode& node, HierarchyDuplication hierarchyDuplication); - - virtual void Update() {} - virtual void Layout() {} - virtual void Draw() {} - virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags); - void DrawBounds(); - void DrawRelationshipLines(); - - // - virtual void GetEditorCommands(Vector& v); - virtual void ExecuteEditorCommand(RcEditorCommand command); - virtual bool CanAutoSelectParentNode() const; - // - - // - Str GetName() const { return _C(_name); } - void Rename(CSZ name); - NodeType GetType() const { return _type; } - // - - // - int GetDepth() const { return _depth; } - void UpdateDepth(); - - BaseNode* GetParent() const; - bool SetParent(BaseNode* pNode, bool keepLocalTransform = false); - virtual bool CanSetParent(BaseNode* pNode) const { return true; } - // - - // - bool IsOctreeElement(bool strict = false) const; - void SetOctreeElementFlag(bool octreeElement = true); - - bool IsOctreeBindOnce() const; - void SetOctreeBindOnceFlag(bool octreeBindOnce = true); - - bool IsDynamic() const; - void SetDynamicFlag(bool dynamic = true); - - bool IsGenerated() const; - void SetGeneratedFlag(bool generated = true); - - bool IsDisabled() const; - virtual void Disable(bool disable = true); - - bool IsSelected() const; - void Select(bool select = true); - - bool HasShadow() const; - virtual void SetShadowFlag(bool shadow = true); - // - - // - bool IsInGroup(int index) const; - void ToggleGroup(int index); - // - - virtual float GetPropertyByName(CSZ name) const; - virtual void SetPropertyByName(CSZ name, float value); - - IO::RDictionary GetDictionary() { return _dict; } - void SetDictionary(IO::RcDictionary dict) { _dict = dict; }; - - // - Point3 GetPosition(bool local = false) const; - Vector3 GetRotation() const; - Vector3 GetScale() const; - void MoveTo(RcPoint3 pos, bool local = false); - void RotateTo(RcVector3 v); - void ScaleTo(RcVector3 v); - void SetDirection(RcVector3 dir); - - RcTransform3 GetTransform(bool local = false) const; - void SetTransform(RcTransform3 tr, bool local = false); - void OverrideGlobalTransform(RcTransform3 tr); - void RestoreTransform(RcTransform3 trLocal, RcVector3 rot, RcVector3 scale); - void UpdateLocalTransform(bool updateUiValues = true); - void UpdateGlobalTransform(bool updateBounds = true); - void UiToLocalTransform(); - void UiFromLocalTransform(); - virtual void OnLocalTransformUpdated() {} // Can be used to adjust local transform. - // - - Math::RcBounds GetBounds() const { return _bounds; } - virtual void UpdateBounds(); - - // - virtual void AddDefaultPickingBody(); - virtual void RemoveRigidBody(); - void SetCollisionFilter(UINT32 group, UINT32 mask); - void UpdateRigidBodyTransform(); - // - - // - virtual void OnNodeDeleted(BaseNode* pNode, bool afterEvent, bool hierarchy); - virtual void OnNodeDuplicated(BaseNode* pNode, bool afterEvent, BaseNode* pDuplicatedNode, HierarchyDuplication hierarchyDuplication); - virtual void OnNodeParentChanged(BaseNode* pNode, bool afterEvent); - virtual void OnNodeRigidBodyTransformUpdated(BaseNode* pNode, bool afterEvent); - virtual void OnNodeTransformed(BaseNode* pNode, bool afterEvent); - // - - // - virtual void Serialize(IO::RSeekableStream stream); - virtual void Deserialize(IO::RStream stream); - void Deserialize_LegacyXXX(IO::RStream stream); - void Deserialize_LegacyXXXPrefab(IO::RStream stream); - virtual void SerializeXML(pugi::xml_node node); - virtual void DeserializeXML(pugi::xml_node node); - void DeserializeXML_LegacyXXX(pugi::xml_node node); - virtual void OnAllNodesDeserialized() {} - // - - float GetDistToHeadSq() const; + readOnlyFlags = (1u << 31), + serializedMask = ~(octreeBindOnce | generated | selected | reserveShadow) }; - VERUS_TYPEDEFS(BaseNode); - class BaseNodePtr : public Ptr + Transform3 _trLocal = Transform3::identity(); + Transform3 _trGlobal = Transform3::identity(); + Vector3 _uiRotation = Vector3(0); // User-friendly rotation used in editor's UI. + Vector3 _uiScale = Vector3(1, 1, 1); // User-friendly scale used in editor's UI. + Math::Bounds _bounds; + IO::Dictionary _dict; + btRigidBody* _pRigidBody = nullptr; + BaseNode* _pParent = nullptr; + String _name; + NodeType _type = NodeType::base; + Flags _flags = Flags::none; + UINT32 _groups = 0; + int _depth = 0; + + public: + struct Desc { - public: - void Init(BaseNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(BaseNodePtr); + CSZ _name = nullptr; - class BaseNodePwn : public BaseNodePtr - { - public: - ~BaseNodePwn() { Done(); } - void Done(); + Desc(CSZ name = nullptr) : _name(name) {} }; - VERUS_TYPEDEFS(BaseNodePwn); - } + VERUS_TYPEDEFS(Desc); + + BaseNode(); + virtual ~BaseNode(); + + virtual int UserPtr_GetType() override; + + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(BaseNode& node, HierarchyDuplication hierarchyDuplication); + + virtual void Update() {} + virtual void Layout() {} + virtual void Draw() {} + virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags); + void DrawBounds(); + void DrawRelationshipLines(); + + // + virtual void GetEditorCommands(Vector& v); + virtual void ExecuteEditorCommand(RcEditorCommand command); + virtual bool CanAutoSelectParentNode() const; + // + + // + Str GetName() const { return _C(_name); } + void Rename(CSZ name); + NodeType GetType() const { return _type; } + // + + // + int GetDepth() const { return _depth; } + void UpdateDepth(); + + BaseNode* GetParent() const; + bool SetParent(BaseNode* pNode, bool keepLocalTransform = false); + virtual bool CanSetParent(BaseNode* pNode) const { return true; } + // + + // + bool IsOctreeElement(bool strict = false) const; + void SetOctreeElementFlag(bool octreeElement = true); + + bool IsOctreeBindOnce() const; + void SetOctreeBindOnceFlag(bool octreeBindOnce = true); + + bool IsDynamic() const; + void SetDynamicFlag(bool dynamic = true); + + bool IsGenerated() const; + void SetGeneratedFlag(bool generated = true); + + bool IsDisabled() const; + virtual void Disable(bool disable = true); + + bool IsSelected() const; + void Select(bool select = true); + + bool HasShadow() const; + virtual void SetShadowFlag(bool shadow = true); + // + + // + bool IsInGroup(int index) const; + void ToggleGroup(int index); + // + + virtual float GetPropertyByName(CSZ name) const; + virtual void SetPropertyByName(CSZ name, float value); + + IO::RDictionary GetDictionary() { return _dict; } + void SetDictionary(IO::RcDictionary dict) { _dict = dict; }; + + // + Point3 GetPosition(bool local = false) const; + Vector3 GetRotation() const; + Vector3 GetScale() const; + void MoveTo(RcPoint3 pos, bool local = false); + void RotateTo(RcVector3 v); + void ScaleTo(RcVector3 v); + void SetDirection(RcVector3 dir); + + RcTransform3 GetTransform(bool local = false) const; + void SetTransform(RcTransform3 tr, bool local = false); + void OverrideGlobalTransform(RcTransform3 tr); + void RestoreTransform(RcTransform3 trLocal, RcVector3 rot, RcVector3 scale); + void UpdateLocalTransform(bool updateUiValues = true); + void UpdateGlobalTransform(bool updateBounds = true); + void UiToLocalTransform(); + void UiFromLocalTransform(); + virtual void OnLocalTransformUpdated() {} // Can be used to adjust local transform. + // + + Math::RcBounds GetBounds() const { return _bounds; } + virtual void UpdateBounds(); + + // + virtual void AddDefaultPickingBody(); + virtual void RemoveRigidBody(); + void SetCollisionFilter(UINT32 group, UINT32 mask); + void UpdateRigidBodyTransform(); + // + + // + virtual void OnNodeDeleted(BaseNode* pNode, bool afterEvent, bool hierarchy); + virtual void OnNodeDuplicated(BaseNode* pNode, bool afterEvent, BaseNode* pDuplicatedNode, HierarchyDuplication hierarchyDuplication); + virtual void OnNodeParentChanged(BaseNode* pNode, bool afterEvent); + virtual void OnNodeRigidBodyTransformUpdated(BaseNode* pNode, bool afterEvent); + virtual void OnNodeTransformed(BaseNode* pNode, bool afterEvent); + // + + // + virtual void Serialize(IO::RSeekableStream stream); + virtual void Deserialize(IO::RStream stream); + void Deserialize_LegacyXXX(IO::RStream stream); + void Deserialize_LegacyXXXPrefab(IO::RStream stream); + virtual void SerializeXML(pugi::xml_node node); + virtual void DeserializeXML(pugi::xml_node node); + void DeserializeXML_LegacyXXX(pugi::xml_node node); + virtual void OnAllNodesDeserialized() {} + // + + float GetDistToHeadSq() const; + }; + VERUS_TYPEDEFS(BaseNode); + + class BaseNodePtr : public Ptr + { + public: + void Init(BaseNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(BaseNodePtr); + + class BaseNodePwn : public BaseNodePtr + { + public: + ~BaseNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(BaseNodePwn); } diff --git a/Verus/src/World/WorldNodes/BlockChainNode.h b/Verus/src/World/WorldNodes/BlockChainNode.h index fd3b779..f9318ce 100644 --- a/Verus/src/World/WorldNodes/BlockChainNode.h +++ b/Verus/src/World/WorldNodes/BlockChainNode.h @@ -1,92 +1,89 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class BlockChainNode : public BaseNode { - class BlockChainNode : public BaseNode + public: + struct SourceModel { - public: - struct SourceModel - { - Vector _vSlots; - ModelNodePtr _modelNode; - String _arguments; - float _length = 0; - bool _noPhysicsNode = false; - bool _noShadow = false; + Vector _vSlots; + ModelNodePtr _modelNode; + String _arguments; + float _length = 0; + bool _noPhysicsNode = false; + bool _noShadow = false; - bool IsAssignedToSlot(int slot) const; - }; - VERUS_TYPEDEFS(SourceModel); - - private: - Vector _vSourceModels; - bool _async_generatedNodes = false; - - public: - struct Desc : BaseNode::Desc - { - PBaseNode _pPathNode = nullptr; - - Desc(PBaseNode pPathNode = nullptr) : _pPathNode(pPathNode) {} - }; - VERUS_TYPEDEFS(Desc); - - BlockChainNode(); - virtual ~BlockChainNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void Update() override; - - virtual void GetEditorCommands(Vector& v) override; - virtual void ExecuteEditorCommand(RcEditorCommand command) override; - - virtual bool CanSetParent(PBaseNode pNode) const override; - - virtual void OnNodeDeleted(PBaseNode pNode, bool afterEvent, bool hierarchy) override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - bool BindSourceModel(PModelNode pModelNode); - bool UnbindSourceModel(PModelNode pModelNode); - int GetSourceModelCount() const; - PcSourceModel GetSourceModelForSlot(int slot) const; - ModelNodePtr GetModelNodeForSlot(int slot) const; - - template - void ForEachSourceModel(const T& fn) - { - for (auto& x : _vSourceModels) - fn(x); - } - - float GetLengthForSlot(int slot) const; - - void ParseArguments(); + bool IsAssignedToSlot(int slot) const; }; - VERUS_TYPEDEFS(BlockChainNode); + VERUS_TYPEDEFS(SourceModel); - class BlockChainNodePtr : public Ptr + private: + Vector _vSourceModels; + bool _async_generatedNodes = false; + + public: + struct Desc : BaseNode::Desc { - public: - void Init(BlockChainNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(BlockChainNodePtr); + PBaseNode _pPathNode = nullptr; - class BlockChainNodePwn : public BlockChainNodePtr - { - public: - ~BlockChainNodePwn() { Done(); } - void Done(); + Desc(PBaseNode pPathNode = nullptr) : _pPathNode(pPathNode) {} }; - VERUS_TYPEDEFS(BlockChainNodePwn); - } + VERUS_TYPEDEFS(Desc); + + BlockChainNode(); + virtual ~BlockChainNode(); + + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void Update() override; + + virtual void GetEditorCommands(Vector& v) override; + virtual void ExecuteEditorCommand(RcEditorCommand command) override; + + virtual bool CanSetParent(PBaseNode pNode) const override; + + virtual void OnNodeDeleted(PBaseNode pNode, bool afterEvent, bool hierarchy) override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + bool BindSourceModel(PModelNode pModelNode); + bool UnbindSourceModel(PModelNode pModelNode); + int GetSourceModelCount() const; + PcSourceModel GetSourceModelForSlot(int slot) const; + ModelNodePtr GetModelNodeForSlot(int slot) const; + + template + void ForEachSourceModel(const T& fn) + { + for (auto& x : _vSourceModels) + fn(x); + } + + float GetLengthForSlot(int slot) const; + + void ParseArguments(); + }; + VERUS_TYPEDEFS(BlockChainNode); + + class BlockChainNodePtr : public Ptr + { + public: + void Init(BlockChainNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(BlockChainNodePtr); + + class BlockChainNodePwn : public BlockChainNodePtr + { + public: + ~BlockChainNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(BlockChainNodePwn); } diff --git a/Verus/src/World/WorldNodes/BlockNode.h b/Verus/src/World/WorldNodes/BlockNode.h index 046f4bb..9ea0a14 100644 --- a/Verus/src/World/WorldNodes/BlockNode.h +++ b/Verus/src/World/WorldNodes/BlockNode.h @@ -1,79 +1,76 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // BlockNode is like an instance of a ModelNode. + // Most blocks form the world's so called static or immovable geometry. + // * references model + // * references material + // * can have it's own material or just reuse model's material + class BlockNode : public BaseNode { - // BlockNode is like an instance of a ModelNode. - // Most blocks form the world's so called static or immovable geometry. - // * references model - // * references material - // * can have it's own material or just reuse model's material - class BlockNode : public BaseNode + Vector4 _userColor = Vector4(0); + ModelNodePwn _modelNode; + MaterialPwn _material; + int _materialIndex = 0; + bool _async_loadedModel = false; + + public: + struct Desc : BaseNode::Desc { - Vector4 _userColor = Vector4(0); - ModelNodePwn _modelNode; - MaterialPwn _material; - int _materialIndex = 0; - bool _async_loadedModel = false; - - public: - struct Desc : BaseNode::Desc - { - CSZ _modelURL = nullptr; - CSZ _materialURL = nullptr; - }; - VERUS_TYPEDEFS(Desc); - - BlockNode(); - virtual ~BlockNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void Update() override; - - virtual void UpdateBounds() override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - void Deserialize_LegacyXXX(IO::RStream stream); - void LoadExtra_LegacyXXX(SZ xml); - - // - bool IsModelLoaded() const { return _modelNode->IsLoaded(); } - bool IsMaterialLoaded() const { return _material->IsLoaded(); } - void LoadMaterial(CSZ url); - void RemoveMaterial(); - Str GetURL() const { return _modelNode->GetURL(); } - - ModelNodePtr GetModelNode() { return _modelNode; } - MaterialPtr GetMaterial(bool orModelMat = true); - int GetMaterialIndex() const { return _materialIndex; } - // - - RcVector4 GetColor() { return _userColor; } - void SetColor(RcVector4 color) { _userColor = color; } + CSZ _modelURL = nullptr; + CSZ _materialURL = nullptr; }; - VERUS_TYPEDEFS(BlockNode); + VERUS_TYPEDEFS(Desc); - class BlockNodePtr : public Ptr - { - public: - void Init(BlockNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(BlockNodePtr); + BlockNode(); + virtual ~BlockNode(); - class BlockNodePwn : public BlockNodePtr - { - public: - ~BlockNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(BlockNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void Update() override; + + virtual void UpdateBounds() override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + void Deserialize_LegacyXXX(IO::RStream stream); + void LoadExtra_LegacyXXX(SZ xml); + + // + bool IsModelLoaded() const { return _modelNode->IsLoaded(); } + bool IsMaterialLoaded() const { return _material->IsLoaded(); } + void LoadMaterial(CSZ url); + void RemoveMaterial(); + Str GetURL() const { return _modelNode->GetURL(); } + + ModelNodePtr GetModelNode() { return _modelNode; } + MaterialPtr GetMaterial(bool orModelMat = true); + int GetMaterialIndex() const { return _materialIndex; } + // + + RcVector4 GetColor() { return _userColor; } + void SetColor(RcVector4 color) { _userColor = color; } + }; + VERUS_TYPEDEFS(BlockNode); + + class BlockNodePtr : public Ptr + { + public: + void Init(BlockNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(BlockNodePtr); + + class BlockNodePwn : public BlockNodePtr + { + public: + ~BlockNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(BlockNodePwn); } diff --git a/Verus/src/World/WorldNodes/ControlPointNode.h b/Verus/src/World/WorldNodes/ControlPointNode.h index 278c283..e0bb2ff 100644 --- a/Verus/src/World/WorldNodes/ControlPointNode.h +++ b/Verus/src/World/WorldNodes/ControlPointNode.h @@ -1,98 +1,95 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // ControlPointNode is a child of PathNode, that defines the shape of the path. + // * can be connected to other control points + // * can form smooth or straight segment + class ControlPointNode : public BaseNode { - // ControlPointNode is a child of PathNode, that defines the shape of the path. - // * can be connected to other control points - // * can form smooth or straight segment - class ControlPointNode : public BaseNode + ControlPointNode* _pPrev = nullptr; + ControlPointNode* _pNext = nullptr; + float _segmentLength = 0; + bool _smoothSegment = true; + bool _markedAsHead = false; + + public: + struct Desc : BaseNode::Desc { - ControlPointNode* _pPrev = nullptr; - ControlPointNode* _pNext = nullptr; - float _segmentLength = 0; - bool _smoothSegment = true; - bool _markedAsHead = false; + PBaseNode _pPathNode = nullptr; - public: - struct Desc : BaseNode::Desc - { - PBaseNode _pPathNode = nullptr; - - Desc(PBaseNode pPathNode = nullptr) : _pPathNode(pPathNode) {} - }; - VERUS_TYPEDEFS(Desc); - - ControlPointNode(); - virtual ~ControlPointNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; - - virtual void GetEditorCommands(Vector& v) override; - virtual bool CanAutoSelectParentNode() const override; - - virtual bool CanSetParent(PBaseNode pNode) const override; - - virtual void OnNodeDeleted(PBaseNode pNode, bool afterEvent, bool hierarchy) override; - virtual void OnNodeParentChanged(PBaseNode pNode, bool afterEvent) override; - virtual void OnNodeTransformed(PBaseNode pNode, bool afterEvent) override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - virtual void OnAllNodesDeserialized() override; - - PBaseNode GetPathNode() const; - - ControlPointNode* GetPreviousControlPoint() const { return _pPrev; } - ControlPointNode* GetNextControlPoint() const { return _pNext; } - void SetPreviousControlPoint(ControlPointNode* p) { _pPrev = p; } - void SetNextControlPoint(ControlPointNode* p) { _pNext = p; UpdateSegmentLength(); } - - void InsertControlPoint(ControlPointNode* pTargetNode, PcPoint3 pPos = nullptr); - - bool DisconnectPreviousControlPoint(); - bool DisconnectNextControlPoint(); - - bool IsHeadControlPoint() const; - bool IsTailControlPoint() const; - bool IsIsolatedControlPoint() const; - - float GetSegmentLength() const { return _segmentLength; } - void UpdateSegmentLength(); - void GetSegmentData(glm::vec3 pos4[4], float len3[3]) const; - void GetSegmentTangents(glm::vec3 pos4[4], float len3[3], glm::vec3 tan2[2]) const; - - bool IsSmoothSegment() const { return _smoothSegment; } - void SetSmoothSegment(bool smooth) { _smoothSegment = smooth; } - - bool IsMarkedAsHead() const { return _markedAsHead; } - void MarkAsHead(bool head) { _markedAsHead = head; } - - bool ComputePositionAt(float distance, RPoint3 pos, PVector3 pDir = nullptr, bool extrapolate = false) const; + Desc(PBaseNode pPathNode = nullptr) : _pPathNode(pPathNode) {} }; - VERUS_TYPEDEFS(ControlPointNode); + VERUS_TYPEDEFS(Desc); - class ControlPointNodePtr : public Ptr - { - public: - void Init(ControlPointNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(ControlPointNodePtr); + ControlPointNode(); + virtual ~ControlPointNode(); - class ControlPointNodePwn : public ControlPointNodePtr - { - public: - ~ControlPointNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(ControlPointNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; + + virtual void GetEditorCommands(Vector& v) override; + virtual bool CanAutoSelectParentNode() const override; + + virtual bool CanSetParent(PBaseNode pNode) const override; + + virtual void OnNodeDeleted(PBaseNode pNode, bool afterEvent, bool hierarchy) override; + virtual void OnNodeParentChanged(PBaseNode pNode, bool afterEvent) override; + virtual void OnNodeTransformed(PBaseNode pNode, bool afterEvent) override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + virtual void OnAllNodesDeserialized() override; + + PBaseNode GetPathNode() const; + + ControlPointNode* GetPreviousControlPoint() const { return _pPrev; } + ControlPointNode* GetNextControlPoint() const { return _pNext; } + void SetPreviousControlPoint(ControlPointNode* p) { _pPrev = p; } + void SetNextControlPoint(ControlPointNode* p) { _pNext = p; UpdateSegmentLength(); } + + void InsertControlPoint(ControlPointNode* pTargetNode, PcPoint3 pPos = nullptr); + + bool DisconnectPreviousControlPoint(); + bool DisconnectNextControlPoint(); + + bool IsHeadControlPoint() const; + bool IsTailControlPoint() const; + bool IsIsolatedControlPoint() const; + + float GetSegmentLength() const { return _segmentLength; } + void UpdateSegmentLength(); + void GetSegmentData(glm::vec3 pos4[4], float len3[3]) const; + void GetSegmentTangents(glm::vec3 pos4[4], float len3[3], glm::vec3 tan2[2]) const; + + bool IsSmoothSegment() const { return _smoothSegment; } + void SetSmoothSegment(bool smooth) { _smoothSegment = smooth; } + + bool IsMarkedAsHead() const { return _markedAsHead; } + void MarkAsHead(bool head) { _markedAsHead = head; } + + bool ComputePositionAt(float distance, RPoint3 pos, PVector3 pDir = nullptr, bool extrapolate = false) const; + }; + VERUS_TYPEDEFS(ControlPointNode); + + class ControlPointNodePtr : public Ptr + { + public: + void Init(ControlPointNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(ControlPointNodePtr); + + class ControlPointNodePwn : public ControlPointNodePtr + { + public: + ~ControlPointNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(ControlPointNodePwn); } diff --git a/Verus/src/World/WorldNodes/EmitterNode.h b/Verus/src/World/WorldNodes/EmitterNode.h index a4e7254..f7da998 100644 --- a/Verus/src/World/WorldNodes/EmitterNode.h +++ b/Verus/src/World/WorldNodes/EmitterNode.h @@ -1,75 +1,72 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // EmitterNode is like an instance of a ParticlesNode. + // Emitters define areas of the world where particles will appear. + // * references particles node + // * can adjust particles by changing color, offset, etc. + class EmitterNode : public BaseNode { - // EmitterNode is like an instance of a ParticlesNode. - // Emitters define areas of the world where particles will appear. - // * references particles node - // * can adjust particles by changing color, offset, etc. - class EmitterNode : public BaseNode + Vector4 _flowColor = Vector4::Replicate(1); + Vector3 _flowOffset = Vector3(0); + ParticlesNodePwn _particlesNode; + float _flow = 0; + float _flowScale = 1; + + public: + struct Desc : BaseNode::Desc { - Vector4 _flowColor = Vector4::Replicate(1); - Vector3 _flowOffset = Vector3(0); - ParticlesNodePwn _particlesNode; - float _flow = 0; - float _flowScale = 1; + CSZ _url = nullptr; - public: - struct Desc : BaseNode::Desc - { - CSZ _url = nullptr; - - Desc(CSZ url = nullptr) : _url(url) {} - }; - VERUS_TYPEDEFS(Desc); - - EmitterNode(); - virtual ~EmitterNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void Update() override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - void Deserialize_LegacyXXX(IO::RStream stream); - void DeserializeXML_LegacyXXX(pugi::xml_node node); - - // - Str GetURL() const { return _particlesNode->GetParticles().GetURL(); } - - ParticlesNodePtr GetParticlesNode() { return _particlesNode; } - // - - RcVector4 GetFlowColor() { return _flowColor; } - void SetFlowColor(RcVector4 flowColor) { _flowColor = flowColor; } - RcVector3 GetFlowOffset() { return _flowOffset; } - void SetFlowOffset(RcVector3 flowOffset) { _flowOffset = flowOffset; } - float GetFlowScale() const { return _flowScale; } - void SetFlowScale(float flowScale) { _flowScale = flowScale; } + Desc(CSZ url = nullptr) : _url(url) {} }; - VERUS_TYPEDEFS(EmitterNode); + VERUS_TYPEDEFS(Desc); - class EmitterNodePtr : public Ptr - { - public: - void Init(EmitterNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(EmitterNodePtr); + EmitterNode(); + virtual ~EmitterNode(); - class EmitterNodePwn : public EmitterNodePtr - { - public: - ~EmitterNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(EmitterNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void Update() override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + void Deserialize_LegacyXXX(IO::RStream stream); + void DeserializeXML_LegacyXXX(pugi::xml_node node); + + // + Str GetURL() const { return _particlesNode->GetParticles().GetURL(); } + + ParticlesNodePtr GetParticlesNode() { return _particlesNode; } + // + + RcVector4 GetFlowColor() { return _flowColor; } + void SetFlowColor(RcVector4 flowColor) { _flowColor = flowColor; } + RcVector3 GetFlowOffset() { return _flowOffset; } + void SetFlowOffset(RcVector3 flowOffset) { _flowOffset = flowOffset; } + float GetFlowScale() const { return _flowScale; } + void SetFlowScale(float flowScale) { _flowScale = flowScale; } + }; + VERUS_TYPEDEFS(EmitterNode); + + class EmitterNodePtr : public Ptr + { + public: + void Init(EmitterNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(EmitterNodePtr); + + class EmitterNodePwn : public EmitterNodePtr + { + public: + ~EmitterNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(EmitterNodePwn); } diff --git a/Verus/src/World/WorldNodes/InstanceNode.h b/Verus/src/World/WorldNodes/InstanceNode.h index 576b750..9f98cd8 100644 --- a/Verus/src/World/WorldNodes/InstanceNode.h +++ b/Verus/src/World/WorldNodes/InstanceNode.h @@ -1,54 +1,51 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // InstanceNode can duplicate child nodes of PrefabNode. + // * references prefab + class InstanceNode : public BaseNode { - // InstanceNode can duplicate child nodes of PrefabNode. - // * references prefab - class InstanceNode : public BaseNode + PBaseNode _pPrefabNode = nullptr; + + public: + struct Desc : BaseNode::Desc { PBaseNode _pPrefabNode = nullptr; - public: - struct Desc : BaseNode::Desc - { - PBaseNode _pPrefabNode = nullptr; - - Desc(PBaseNode pPrefabNode = nullptr) : _pPrefabNode(pPrefabNode) {} - }; - VERUS_TYPEDEFS(Desc); - - InstanceNode(); - virtual ~InstanceNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - PBaseNode GetPrefabNode() const { return _pPrefabNode; } + Desc(PBaseNode pPrefabNode = nullptr) : _pPrefabNode(pPrefabNode) {} }; - VERUS_TYPEDEFS(InstanceNode); + VERUS_TYPEDEFS(Desc); - class InstanceNodePtr : public Ptr - { - public: - void Init(InstanceNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(InstanceNodePtr); + InstanceNode(); + virtual ~InstanceNode(); - class InstanceNodePwn : public InstanceNodePtr - { - public: - ~InstanceNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(InstanceNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + PBaseNode GetPrefabNode() const { return _pPrefabNode; } + }; + VERUS_TYPEDEFS(InstanceNode); + + class InstanceNodePtr : public Ptr + { + public: + void Init(InstanceNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(InstanceNodePtr); + + class InstanceNodePwn : public InstanceNodePtr + { + public: + ~InstanceNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(InstanceNodePwn); } diff --git a/Verus/src/World/WorldNodes/LightNode.h b/Verus/src/World/WorldNodes/LightNode.h index 3723b13..08fbe6c 100644 --- a/Verus/src/World/WorldNodes/LightNode.h +++ b/Verus/src/World/WorldNodes/LightNode.h @@ -1,124 +1,121 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class LightData { - class LightData + public: + Vector4 _color = Vector4(1, 1, 1, 1000); + Vector3 _dir = Vector3(0, 0, 1); + CGI::LightType _lightType = CGI::LightType::omni; + float _radius = 10; + float _coneIn = cos(Math::ToRadians(20)); + float _coneOut = cos(Math::ToRadians(30)); + }; + VERUS_TYPEDEFS(LightData); + + // LightNode defines a light source. + // LightNode's scale is tied to the radius. + // * has different light parameters, like color, radius, etc. + class LightNode : public BaseNode + { + Matrix4 _matShadow = Matrix4::identity(); + LightData _data; + ShadowMapHandle _shadowMapHandle; + float _cachedInfluence = 0; + bool _shadowMapUpdateRequired = false; + bool _async_loadedMesh = false; + + public: + struct Desc : BaseNode::Desc { - public: - Vector4 _color = Vector4(1, 1, 1, 1000); - Vector3 _dir = Vector3(0, 0, 1); - CGI::LightType _lightType = CGI::LightType::omni; - float _radius = 10; - float _coneIn = cos(Math::ToRadians(20)); - float _coneOut = cos(Math::ToRadians(30)); + LightData _data; + bool _dynamic = false; }; - VERUS_TYPEDEFS(LightData); + VERUS_TYPEDEFS(Desc); - // LightNode defines a light source. - // LightNode's scale is tied to the radius. - // * has different light parameters, like color, radius, etc. - class LightNode : public BaseNode - { - Matrix4 _matShadow = Matrix4::identity(); - LightData _data; - ShadowMapHandle _shadowMapHandle; - float _cachedInfluence = 0; - bool _shadowMapUpdateRequired = false; - bool _async_loadedMesh = false; + LightNode(); + virtual ~LightNode(); - public: - struct Desc : BaseNode::Desc - { - LightData _data; - bool _dynamic = false; - }; - VERUS_TYPEDEFS(Desc); + void Init(RcDesc desc); + void Done(); - LightNode(); - virtual ~LightNode(); + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - void Init(RcDesc desc); - void Done(); + virtual void Update() override; + virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + // + virtual void SetShadowFlag(bool shadow = true) override; + bool CanReserveShadow() const; + void SetReserveShadowFlag(bool reserveShadow); + // - virtual void Update() override; - virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; + virtual float GetPropertyByName(CSZ name) const override; + virtual void SetPropertyByName(CSZ name, float value) override; - // - virtual void SetShadowFlag(bool shadow = true) override; - bool CanReserveShadow() const; - void SetReserveShadowFlag(bool reserveShadow); - // + Vector3 ComputeScale(); + virtual void OnLocalTransformUpdated() override; - virtual float GetPropertyByName(CSZ name) const override; - virtual void SetPropertyByName(CSZ name, float value) override; + virtual void UpdateBounds() override; - Vector3 ComputeScale(); - virtual void OnLocalTransformUpdated() override; + virtual void OnNodeTransformed(PBaseNode pNode, bool afterEvent) override; - virtual void UpdateBounds() override; + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + void Deserialize_LegacyXXX(IO::RStream stream); + void DeserializeXML_LegacyXXX(pugi::xml_node node); - virtual void OnNodeTransformed(PBaseNode pNode, bool afterEvent) override; + CGI::LightType GetLightType() const; + void SetLightType(CGI::LightType type); + RcVector4 GetColor() const; + void SetColor(RcVector4 color); + float GetIntensity() const; + void SetIntensity(float i); + float GetRadius() const; + void SetRadius(float r); + float GetConeIn() const; + void SetConeIn(float coneIn); + float GetConeOut() const; + void SetConeOut(float coneOut); + Vector4 GetInstData() const; + float ComputeLampRadius() const; - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - void Deserialize_LegacyXXX(IO::RStream stream); - void DeserializeXML_LegacyXXX(pugi::xml_node node); + // + ShadowMapHandle GetShadowMapHandle() const { return _shadowMapHandle; } + void UpdateShadowMapHandle(bool freeCell = false); + bool CanRequestShadowMapUpdate() const; + void RequestShadowMapUpdate(bool mustBeStatic = true); + bool IsShadowMapUpdateRequired() const; + void OnShadowMapUpdated(); + bool CanBeSmbpStatic() const; + bool CanBeSmbpDynamic() const; - CGI::LightType GetLightType() const; - void SetLightType(CGI::LightType type); - RcVector4 GetColor() const; - void SetColor(RcVector4 color); - float GetIntensity() const; - void SetIntensity(float i); - float GetRadius() const; - void SetRadius(float r); - float GetConeIn() const; - void SetConeIn(float coneIn); - float GetConeOut() const; - void SetConeOut(float coneOut); - Vector4 GetInstData() const; - float ComputeLampRadius() const; + void SetupShadowMapCamera(RCamera camera); - // - ShadowMapHandle GetShadowMapHandle() const { return _shadowMapHandle; } - void UpdateShadowMapHandle(bool freeCell = false); - bool CanRequestShadowMapUpdate() const; - void RequestShadowMapUpdate(bool mustBeStatic = true); - bool IsShadowMapUpdateRequired() const; - void OnShadowMapUpdated(); - bool CanBeSmbpStatic() const; - bool CanBeSmbpDynamic() const; + RcMatrix4 GetShadowMatrix() const; + Matrix4 GetShadowMatrixForDS() const; + // - void SetupShadowMapCamera(RCamera camera); + float GetInfluenceAt(Math::RcSphere sphere); + float GetCachedInfluence() const { return _cachedInfluence; } + }; + VERUS_TYPEDEFS(LightNode); - RcMatrix4 GetShadowMatrix() const; - Matrix4 GetShadowMatrixForDS() const; - // + class LightNodePtr : public Ptr + { + public: + void Init(LightNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(LightNodePtr); - float GetInfluenceAt(Math::RcSphere sphere); - float GetCachedInfluence() const { return _cachedInfluence; } - }; - VERUS_TYPEDEFS(LightNode); - - class LightNodePtr : public Ptr - { - public: - void Init(LightNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(LightNodePtr); - - class LightNodePwn : public LightNodePtr - { - public: - ~LightNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(LightNodePwn); - } + class LightNodePwn : public LightNodePtr + { + public: + ~LightNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(LightNodePwn); } diff --git a/Verus/src/World/WorldNodes/ModelNode.h b/Verus/src/World/WorldNodes/ModelNode.h index cd3c960..bcfffe5 100644 --- a/Verus/src/World/WorldNodes/ModelNode.h +++ b/Verus/src/World/WorldNodes/ModelNode.h @@ -1,80 +1,77 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // ModelNode stores mesh and material (aka model), which can be used by a BlockNode. + // * has a mesh + // * has a material + class ModelNode : public BaseNode { - // ModelNode stores mesh and material (aka model), which can be used by a BlockNode. - // * has a mesh - // * has a material - class ModelNode : public BaseNode + Mesh _mesh; + MaterialPwn _material; + int _refCount = 0; + + public: + struct Desc : BaseNode::Desc { - Mesh _mesh; - MaterialPwn _material; - int _refCount = 0; + CSZ _url = nullptr; + CSZ _materialURL = nullptr; + int _instanceCapacity = 1000; - public: - struct Desc : BaseNode::Desc - { - CSZ _url = nullptr; - CSZ _materialURL = nullptr; - int _instanceCapacity = 1000; - - Desc(CSZ url = nullptr) : _url(url) {} - }; - VERUS_TYPEDEFS(Desc); - - ModelNode(); - virtual ~ModelNode(); - - void AddRef() { _refCount++; } - int GetRefCount() const { return _refCount; } - - void Init(RcDesc desc); - bool Done(); - - virtual void GetEditorCommands(Vector& v) override; - - virtual bool CanSetParent(PBaseNode pNode) const override; - - virtual void AddDefaultPickingBody() override {} - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - void Deserialize_LegacyXXX(IO::RStream stream, CSZ url); - - // - bool IsLoaded() const { return _mesh.IsLoaded(); } - void LoadMaterial(CSZ url); - Str GetURL() const { return _mesh.GetURL(); } - - RMesh GetMesh() { return _mesh; } - MaterialPtr GetMaterial() { return _material; } - // - - void BindPipeline(CGI::CommandBufferPtr cb); - void BindPipelineSimple(DrawSimpleMode mode, CGI::CommandBufferPtr cb); - void BindGeo(CGI::CommandBufferPtr cb); - void MarkInstance(); - void PushInstance(RcTransform3 matW, RcVector4 instData); - void Draw(CGI::CommandBufferPtr cb); + Desc(CSZ url = nullptr) : _url(url) {} }; - VERUS_TYPEDEFS(ModelNode); + VERUS_TYPEDEFS(Desc); - class ModelNodePtr : public Ptr - { - public: - void Init(ModelNode::RcDesc desc); - }; - VERUS_TYPEDEFS(ModelNodePtr); + ModelNode(); + virtual ~ModelNode(); - class ModelNodePwn : public ModelNodePtr - { - public: - ~ModelNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(ModelNodePwn); - } + void AddRef() { _refCount++; } + int GetRefCount() const { return _refCount; } + + void Init(RcDesc desc); + bool Done(); + + virtual void GetEditorCommands(Vector& v) override; + + virtual bool CanSetParent(PBaseNode pNode) const override; + + virtual void AddDefaultPickingBody() override {} + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + void Deserialize_LegacyXXX(IO::RStream stream, CSZ url); + + // + bool IsLoaded() const { return _mesh.IsLoaded(); } + void LoadMaterial(CSZ url); + Str GetURL() const { return _mesh.GetURL(); } + + RMesh GetMesh() { return _mesh; } + MaterialPtr GetMaterial() { return _material; } + // + + void BindPipeline(CGI::CommandBufferPtr cb); + void BindPipelineSimple(DrawSimpleMode mode, CGI::CommandBufferPtr cb); + void BindGeo(CGI::CommandBufferPtr cb); + void MarkInstance(); + void PushInstance(RcTransform3 matW, RcVector4 instData); + void Draw(CGI::CommandBufferPtr cb); + }; + VERUS_TYPEDEFS(ModelNode); + + class ModelNodePtr : public Ptr + { + public: + void Init(ModelNode::RcDesc desc); + }; + VERUS_TYPEDEFS(ModelNodePtr); + + class ModelNodePwn : public ModelNodePtr + { + public: + ~ModelNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(ModelNodePwn); } diff --git a/Verus/src/World/WorldNodes/ParticlesNode.h b/Verus/src/World/WorldNodes/ParticlesNode.h index 345d495..8006180 100644 --- a/Verus/src/World/WorldNodes/ParticlesNode.h +++ b/Verus/src/World/WorldNodes/ParticlesNode.h @@ -1,68 +1,65 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // ParticlesNode stores particles, which can be used by EmitterNode. + // * has particles + class ParticlesNode : public BaseNode { - // ParticlesNode stores particles, which can be used by EmitterNode. - // * has particles - class ParticlesNode : public BaseNode + Effects::Particles _particles; + int _refCount = 0; + + public: + struct Desc : BaseNode::Desc { - Effects::Particles _particles; - int _refCount = 0; + CSZ _url = nullptr; - public: - struct Desc : BaseNode::Desc - { - CSZ _url = nullptr; - - Desc(CSZ url = nullptr) : _url(url) {} - }; - VERUS_TYPEDEFS(Desc); - - ParticlesNode(); - virtual ~ParticlesNode(); - - void AddRef() { _refCount++; } - int GetRefCount() const { return _refCount; } - - void Init(RcDesc desc); - bool Done(); - - virtual void Update() override; - virtual void Draw() override; - - virtual void GetEditorCommands(Vector& v) override; - - virtual bool CanSetParent(PBaseNode pNode) const override; - - virtual void AddDefaultPickingBody() override {} - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - // - Str GetURL() const { return _particles.GetURL(); } - - Effects::RParticles GetParticles() { return _particles; } - // + Desc(CSZ url = nullptr) : _url(url) {} }; - VERUS_TYPEDEFS(ParticlesNode); + VERUS_TYPEDEFS(Desc); - class ParticlesNodePtr : public Ptr - { - public: - void Init(ParticlesNode::RcDesc desc); - }; - VERUS_TYPEDEFS(ParticlesNodePtr); + ParticlesNode(); + virtual ~ParticlesNode(); - class ParticlesNodePwn : public ParticlesNodePtr - { - public: - ~ParticlesNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(ParticlesNodePwn); - } + void AddRef() { _refCount++; } + int GetRefCount() const { return _refCount; } + + void Init(RcDesc desc); + bool Done(); + + virtual void Update() override; + virtual void Draw() override; + + virtual void GetEditorCommands(Vector& v) override; + + virtual bool CanSetParent(PBaseNode pNode) const override; + + virtual void AddDefaultPickingBody() override {} + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + // + Str GetURL() const { return _particles.GetURL(); } + + Effects::RParticles GetParticles() { return _particles; } + // + }; + VERUS_TYPEDEFS(ParticlesNode); + + class ParticlesNodePtr : public Ptr + { + public: + void Init(ParticlesNode::RcDesc desc); + }; + VERUS_TYPEDEFS(ParticlesNodePtr); + + class ParticlesNodePwn : public ParticlesNodePtr + { + public: + ~ParticlesNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(ParticlesNodePwn); } diff --git a/Verus/src/World/WorldNodes/PathNode.h b/Verus/src/World/WorldNodes/PathNode.h index db7dee4..3633184 100644 --- a/Verus/src/World/WorldNodes/PathNode.h +++ b/Verus/src/World/WorldNodes/PathNode.h @@ -1,50 +1,47 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // PathNode defines a curve or multiple curves, which can be used for different purposes. + // * can have child ControlPointNodes, which define the shape of the curve. + class PathNode : public BaseNode { - // PathNode defines a curve or multiple curves, which can be used for different purposes. - // * can have child ControlPointNodes, which define the shape of the curve. - class PathNode : public BaseNode + public: + struct Desc : BaseNode::Desc { - public: - struct Desc : BaseNode::Desc - { - Desc(CSZ name = nullptr) : BaseNode::Desc(name) {} - }; - VERUS_TYPEDEFS(Desc); - - PathNode(); - virtual ~PathNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void GetEditorCommands(Vector& v) override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; + Desc(CSZ name = nullptr) : BaseNode::Desc(name) {} }; - VERUS_TYPEDEFS(PathNode); + VERUS_TYPEDEFS(Desc); - class PathNodePtr : public Ptr - { - public: - void Init(PathNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(PathNodePtr); + PathNode(); + virtual ~PathNode(); - class PathNodePwn : public PathNodePtr - { - public: - ~PathNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(PathNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void GetEditorCommands(Vector& v) override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + }; + VERUS_TYPEDEFS(PathNode); + + class PathNodePtr : public Ptr + { + public: + void Init(PathNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(PathNodePtr); + + class PathNodePwn : public PathNodePtr + { + public: + ~PathNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(PathNodePwn); } diff --git a/Verus/src/World/WorldNodes/PhysicsNode.h b/Verus/src/World/WorldNodes/PhysicsNode.h index d6a1cbd..54f943f 100644 --- a/Verus/src/World/WorldNodes/PhysicsNode.h +++ b/Verus/src/World/WorldNodes/PhysicsNode.h @@ -1,149 +1,146 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // PhysicsNode adds rigid bodies to the physics engine. + // * can be static, dynamic or kinematic + // * can have a basic shape or can take it's shape from block node or load it from file + // * has some physical parameters like friction and restitution + class PhysicsNode : public BaseNode { - // PhysicsNode adds rigid bodies to the physics engine. - // * can be static, dynamic or kinematic - // * can have a basic shape or can take it's shape from block node or load it from file - // * has some physical parameters like friction and restitution - class PhysicsNode : public BaseNode + public: + enum class ShapeType : int { - public: - enum class ShapeType : int - { - parentBlock, - fromFile, - box, - capsule, - cone, - cylinder, - sphere - }; - - enum class BodyType : int - { - staticBody, - dynamicBody, - kinematicBody - }; - - private: - Vector3 _size = Vector3::Replicate(1); - Physics::LocalRigidBody _pLocalRigidBody; - String _shapeURL; - btCollisionShape* _pCollisionShape = nullptr; - ShapeType _shapeType = ShapeType::parentBlock; - BodyType _bodyType = BodyType::staticBody; - float _mass = 1; - float _friction = 0.5f; - float _restitution = 0.5f; - float _linearDamping = 0; - float _angularDamping = 0; - UINT32 _collisionFilterGroup = +(Physics::Group::immovable | Physics::Group::node); - UINT32 _collisionFilterMask = +Physics::Group::all; - bool _async_loadedModel = false; - - public: - struct Desc : BaseNode::Desc - { - Desc(CSZ name = nullptr) : BaseNode::Desc(name) {} - }; - VERUS_TYPEDEFS(Desc); - - PhysicsNode(); - virtual ~PhysicsNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void Update() override; - virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; - - // - virtual void GetEditorCommands(Vector& v) override; - virtual void ExecuteEditorCommand(RcEditorCommand command) override; - virtual bool CanAutoSelectParentNode() const override; - // - - virtual void Disable(bool disable) override; - - // - bool IsInCollisionGroup(int index) const; - void ToggleCollisionGroup(int index); - bool IsInCollisionMask(int index) const; - void ToggleCollisionMask(int index); - // - - virtual void UpdateBounds() override; - - // - virtual void AddDefaultPickingBody() override {} - virtual void RemoveRigidBody() override; - void AddNewRigidBody(btCollisionShape* pShape, bool updateBounds = true); - void ResetRigidBodyTransform(); - // - - // - virtual void OnNodeParentChanged(PBaseNode pNode, bool afterEvent) override; - virtual void OnNodeRigidBodyTransformUpdated(PBaseNode pNode, bool afterEvent) override; - // - - // - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - // - - // - ShapeType GetShapeType() const { return _shapeType; } - void SetShapeType(ShapeType shapeType); - void CreateCollisionShape(); - void LoadCollisionShape(CSZ url); - Str GetCollisionShapeURL() const { return _C(_shapeURL); } - // - - BodyType GetBodyType() const { return _bodyType; } - void SetBodyType(BodyType bodyType); - - RcVector3 GetSize() const { return _size; } - void Resize(RcVector3 size); - void FitParentBlock(); - - float GetMass() const { return _mass; } - void SetMass(float mass) { _mass = Math::Max(0.f, mass); } - - float GetFriction() const { return _friction; } - void SetFriction(float friction); - - float GetRestitution() const { return _restitution; } - void SetRestitution(float restitution); - - float GetLinearDamping() const { return _linearDamping; } - void SetLinearDamping(float linearDamping); - - float GetAngularDamping() const { return _angularDamping; } - void SetAngularDamping(float angularDamping); + parentBlock, + fromFile, + box, + capsule, + cone, + cylinder, + sphere }; - VERUS_TYPEDEFS(PhysicsNode); - class PhysicsNodePtr : public Ptr + enum class BodyType : int { - public: - void Init(PhysicsNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + staticBody, + dynamicBody, + kinematicBody }; - VERUS_TYPEDEFS(PhysicsNodePtr); - class PhysicsNodePwn : public PhysicsNodePtr + private: + Vector3 _size = Vector3::Replicate(1); + Physics::LocalRigidBody _pLocalRigidBody; + String _shapeURL; + btCollisionShape* _pCollisionShape = nullptr; + ShapeType _shapeType = ShapeType::parentBlock; + BodyType _bodyType = BodyType::staticBody; + float _mass = 1; + float _friction = 0.5f; + float _restitution = 0.5f; + float _linearDamping = 0; + float _angularDamping = 0; + UINT32 _collisionFilterGroup = +(Physics::Group::immovable | Physics::Group::node); + UINT32 _collisionFilterMask = +Physics::Group::all; + bool _async_loadedModel = false; + + public: + struct Desc : BaseNode::Desc { - public: - ~PhysicsNodePwn() { Done(); } - void Done(); + Desc(CSZ name = nullptr) : BaseNode::Desc(name) {} }; - VERUS_TYPEDEFS(PhysicsNodePwn); - } + VERUS_TYPEDEFS(Desc); + + PhysicsNode(); + virtual ~PhysicsNode(); + + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void Update() override; + virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; + + // + virtual void GetEditorCommands(Vector& v) override; + virtual void ExecuteEditorCommand(RcEditorCommand command) override; + virtual bool CanAutoSelectParentNode() const override; + // + + virtual void Disable(bool disable) override; + + // + bool IsInCollisionGroup(int index) const; + void ToggleCollisionGroup(int index); + bool IsInCollisionMask(int index) const; + void ToggleCollisionMask(int index); + // + + virtual void UpdateBounds() override; + + // + virtual void AddDefaultPickingBody() override {} + virtual void RemoveRigidBody() override; + void AddNewRigidBody(btCollisionShape* pShape, bool updateBounds = true); + void ResetRigidBodyTransform(); + // + + // + virtual void OnNodeParentChanged(PBaseNode pNode, bool afterEvent) override; + virtual void OnNodeRigidBodyTransformUpdated(PBaseNode pNode, bool afterEvent) override; + // + + // + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + // + + // + ShapeType GetShapeType() const { return _shapeType; } + void SetShapeType(ShapeType shapeType); + void CreateCollisionShape(); + void LoadCollisionShape(CSZ url); + Str GetCollisionShapeURL() const { return _C(_shapeURL); } + // + + BodyType GetBodyType() const { return _bodyType; } + void SetBodyType(BodyType bodyType); + + RcVector3 GetSize() const { return _size; } + void Resize(RcVector3 size); + void FitParentBlock(); + + float GetMass() const { return _mass; } + void SetMass(float mass) { _mass = Math::Max(0.f, mass); } + + float GetFriction() const { return _friction; } + void SetFriction(float friction); + + float GetRestitution() const { return _restitution; } + void SetRestitution(float restitution); + + float GetLinearDamping() const { return _linearDamping; } + void SetLinearDamping(float linearDamping); + + float GetAngularDamping() const { return _angularDamping; } + void SetAngularDamping(float angularDamping); + }; + VERUS_TYPEDEFS(PhysicsNode); + + class PhysicsNodePtr : public Ptr + { + public: + void Init(PhysicsNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(PhysicsNodePtr); + + class PhysicsNodePwn : public PhysicsNodePtr + { + public: + ~PhysicsNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(PhysicsNodePwn); } diff --git a/Verus/src/World/WorldNodes/PrefabNode.h b/Verus/src/World/WorldNodes/PrefabNode.h index e2ffb21..c74d31c 100644 --- a/Verus/src/World/WorldNodes/PrefabNode.h +++ b/Verus/src/World/WorldNodes/PrefabNode.h @@ -1,60 +1,57 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // PrefabNode can create and update InstanceNodes, which can duplicate child nodes of PrefabNode. + // * child nodes can have "PrefabDupP" property, which controls whether they will get duplicated + // * has seed, which affects the "PrefabDupP" property + class PrefabNode : public BaseNode { - // PrefabNode can create and update InstanceNodes, which can duplicate child nodes of PrefabNode. - // * child nodes can have "PrefabDupP" property, which controls whether they will get duplicated - // * has seed, which affects the "PrefabDupP" property - class PrefabNode : public BaseNode + UINT16 _seed = 0; + + public: + struct Desc : BaseNode::Desc { - UINT16 _seed = 0; - - public: - struct Desc : BaseNode::Desc - { - Desc(CSZ name = nullptr) : BaseNode::Desc(name) {} - }; - VERUS_TYPEDEFS(Desc); - - PrefabNode(); - virtual ~PrefabNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void GetEditorCommands(Vector& v) override; - - virtual bool CanSetParent(PBaseNode pNode) const override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - void DeleteAllInstances(); - - UINT16 GetSeed() const { return _seed; } - void SetSeed(UINT16 seed) { _seed = seed; } + Desc(CSZ name = nullptr) : BaseNode::Desc(name) {} }; - VERUS_TYPEDEFS(PrefabNode); + VERUS_TYPEDEFS(Desc); - class PrefabNodePtr : public Ptr - { - public: - void Init(PrefabNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(PrefabNodePtr); + PrefabNode(); + virtual ~PrefabNode(); - class PrefabNodePwn : public PrefabNodePtr - { - public: - ~PrefabNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(PrefabNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void GetEditorCommands(Vector& v) override; + + virtual bool CanSetParent(PBaseNode pNode) const override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + void DeleteAllInstances(); + + UINT16 GetSeed() const { return _seed; } + void SetSeed(UINT16 seed) { _seed = seed; } + }; + VERUS_TYPEDEFS(PrefabNode); + + class PrefabNodePtr : public Ptr + { + public: + void Init(PrefabNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(PrefabNodePtr); + + class PrefabNodePwn : public PrefabNodePtr + { + public: + ~PrefabNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(PrefabNodePwn); } diff --git a/Verus/src/World/WorldNodes/ProjectNode.h b/Verus/src/World/WorldNodes/ProjectNode.h index 7c6b14b..d9a8073 100644 --- a/Verus/src/World/WorldNodes/ProjectNode.h +++ b/Verus/src/World/WorldNodes/ProjectNode.h @@ -1,72 +1,69 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + class ProjectNode : public BaseNode { - class ProjectNode : public BaseNode + Transform3 _trToBoxSpace = Transform3::identity(); + Vector4 _levels = Vector4::Replicate(1000); + String _url; + TexturePwn _tex; + CGI::CSHandle _csh; + + public: + struct Desc : BaseNode::Desc { - Transform3 _trToBoxSpace = Transform3::identity(); - Vector4 _levels = Vector4::Replicate(1000); - String _url; - TexturePwn _tex; - CGI::CSHandle _csh; + CSZ _url = nullptr; - public: - struct Desc : BaseNode::Desc - { - CSZ _url = nullptr; - - Desc(CSZ url = nullptr) : _url(url) {} - }; - VERUS_TYPEDEFS(Desc); - - ProjectNode(); - virtual ~ProjectNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void Update() override; - virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; - - virtual void UpdateBounds() override; - - virtual void OnNodeTransformed(PBaseNode pNode, bool afterEvent) override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - // - void LoadTexture(CSZ url); - void RemoveTexture(); - Str GetURL() const { return _C(_url); } - CGI::CSHandle GetComplexSetHandle() const { return _csh; } - // - - RcVector4 GetLevels() const { return _levels; } - void SetLevels(RcVector4 levels) { _levels = levels; } - RcTransform3 GetToBoxSpaceTransform() const { return _trToBoxSpace; } + Desc(CSZ url = nullptr) : _url(url) {} }; - VERUS_TYPEDEFS(ProjectNode); + VERUS_TYPEDEFS(Desc); - class ProjectNodePtr : public Ptr - { - public: - void Init(ProjectNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(ProjectNodePtr); + ProjectNode(); + virtual ~ProjectNode(); - class ProjectNodePwn : public ProjectNodePtr - { - public: - ~ProjectNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(ProjectNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void Update() override; + virtual void DrawEditorOverlays(DrawEditorOverlaysFlags flags) override; + + virtual void UpdateBounds() override; + + virtual void OnNodeTransformed(PBaseNode pNode, bool afterEvent) override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + // + void LoadTexture(CSZ url); + void RemoveTexture(); + Str GetURL() const { return _C(_url); } + CGI::CSHandle GetComplexSetHandle() const { return _csh; } + // + + RcVector4 GetLevels() const { return _levels; } + void SetLevels(RcVector4 levels) { _levels = levels; } + RcTransform3 GetToBoxSpaceTransform() const { return _trToBoxSpace; } + }; + VERUS_TYPEDEFS(ProjectNode); + + class ProjectNodePtr : public Ptr + { + public: + void Init(ProjectNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(ProjectNodePtr); + + class ProjectNodePwn : public ProjectNodePtr + { + public: + ~ProjectNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(ProjectNodePwn); } diff --git a/Verus/src/World/WorldNodes/ShakerNode.h b/Verus/src/World/WorldNodes/ShakerNode.h index 261d7bf..60f24ad 100644 --- a/Verus/src/World/WorldNodes/ShakerNode.h +++ b/Verus/src/World/WorldNodes/ShakerNode.h @@ -1,71 +1,68 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // ShakerNode can add dynamic noise to some properties of parent node. + // * property must be accessible with GetPropertyByName of BaseNode + class ShakerNode : public BaseNode { - // ShakerNode can add dynamic noise to some properties of parent node. - // * property must be accessible with GetPropertyByName of BaseNode - class ShakerNode : public BaseNode + Anim::Shaker _shaker; + String _propertyName; + float _initialValue = 0; + + public: + struct Desc : BaseNode::Desc { - Anim::Shaker _shaker; - String _propertyName; - float _initialValue = 0; + CSZ _url = nullptr; - public: - struct Desc : BaseNode::Desc - { - CSZ _url = nullptr; - - Desc(CSZ url = nullptr) : _url(url) {} - }; - VERUS_TYPEDEFS(Desc); - - ShakerNode(); - virtual ~ShakerNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void Update() override; - - virtual void GetEditorCommands(Vector& v) override; - virtual void ExecuteEditorCommand(RcEditorCommand command) override; - - virtual void Disable(bool disable) override; - - virtual void OnNodeParentChanged(PBaseNode pNode, bool afterEvent) override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - Anim::RShaker GetShaker() { return _shaker; } - - Str GetPropertyName() const { return _C(_propertyName); } - void SetPropertyName(CSZ name); - - void UpdateInitialValue(); - void ApplyInitialValue(); + Desc(CSZ url = nullptr) : _url(url) {} }; - VERUS_TYPEDEFS(ShakerNode); + VERUS_TYPEDEFS(Desc); - class ShakerNodePtr : public Ptr - { - public: - void Init(ShakerNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(ShakerNodePtr); + ShakerNode(); + virtual ~ShakerNode(); - class ShakerNodePwn : public ShakerNodePtr - { - public: - ~ShakerNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(ShakerNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void Update() override; + + virtual void GetEditorCommands(Vector& v) override; + virtual void ExecuteEditorCommand(RcEditorCommand command) override; + + virtual void Disable(bool disable) override; + + virtual void OnNodeParentChanged(PBaseNode pNode, bool afterEvent) override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + Anim::RShaker GetShaker() { return _shaker; } + + Str GetPropertyName() const { return _C(_propertyName); } + void SetPropertyName(CSZ name); + + void UpdateInitialValue(); + void ApplyInitialValue(); + }; + VERUS_TYPEDEFS(ShakerNode); + + class ShakerNodePtr : public Ptr + { + public: + void Init(ShakerNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(ShakerNodePtr); + + class ShakerNodePwn : public ShakerNodePtr + { + public: + ~ShakerNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(ShakerNodePwn); } diff --git a/Verus/src/World/WorldNodes/SoundNode.h b/Verus/src/World/WorldNodes/SoundNode.h index 8e7bf6d..e48bb36 100644 --- a/Verus/src/World/WorldNodes/SoundNode.h +++ b/Verus/src/World/WorldNodes/SoundNode.h @@ -1,84 +1,81 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // SoundNode adds sound to some area of the world. + // * can control some sound parameters like gain and looping + class SoundNode : public BaseNode { - // SoundNode adds sound to some area of the world. - // * can control some sound parameters like gain and looping - class SoundNode : public BaseNode + Audio::SoundPwn _sound; + Audio::SourcePtr _soundSource; + float _gain = 0.8f; + float _pitch = 1; + bool _looping = true; + + public: + struct Desc : BaseNode::Desc { - Audio::SoundPwn _sound; - Audio::SourcePtr _soundSource; - float _gain = 0.8f; - float _pitch = 1; - bool _looping = true; + CSZ _url = nullptr; + float _gain = 0.8f; + float _pitch = 1; + bool _looping = true; - public: - struct Desc : BaseNode::Desc - { - CSZ _url = nullptr; - float _gain = 0.8f; - float _pitch = 1; - bool _looping = true; - - Desc(CSZ url = nullptr) : _url(url) {} - }; - VERUS_TYPEDEFS(Desc); - - SoundNode(); - virtual ~SoundNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; - - virtual void Update() override; - - virtual void Disable(bool disable) override; - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - // - bool IsLoaded() const { return _sound && _sound->IsLoaded(); } - void Load(CSZ url); - Str GetURL() const { return _sound ? _sound->GetURL() : ""; } - - Audio::SoundPtr GetSound() const { return _sound; } - Audio::SourcePtr GetSoundSource() const { return _soundSource; } - // - - float GetGain() const { return _gain; } - void SetGain(float gain); - - float GetPitch() const { return _pitch; } - void SetPitch(float pitch); - - bool IsLooping() const { return _looping; } - void SetLooping(bool b = true); - - void Play(); - void Stop(); + Desc(CSZ url = nullptr) : _url(url) {} }; - VERUS_TYPEDEFS(SoundNode); + VERUS_TYPEDEFS(Desc); - class SoundNodePtr : public Ptr - { - public: - void Init(SoundNode::RcDesc desc); - void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); - }; - VERUS_TYPEDEFS(SoundNodePtr); + SoundNode(); + virtual ~SoundNode(); - class SoundNodePwn : public SoundNodePtr - { - public: - ~SoundNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(SoundNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication) override; + + virtual void Update() override; + + virtual void Disable(bool disable) override; + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + // + bool IsLoaded() const { return _sound && _sound->IsLoaded(); } + void Load(CSZ url); + Str GetURL() const { return _sound ? _sound->GetURL() : ""; } + + Audio::SoundPtr GetSound() const { return _sound; } + Audio::SourcePtr GetSoundSource() const { return _soundSource; } + // + + float GetGain() const { return _gain; } + void SetGain(float gain); + + float GetPitch() const { return _pitch; } + void SetPitch(float pitch); + + bool IsLooping() const { return _looping; } + void SetLooping(bool b = true); + + void Play(); + void Stop(); + }; + VERUS_TYPEDEFS(SoundNode); + + class SoundNodePtr : public Ptr + { + public: + void Init(SoundNode::RcDesc desc); + void Duplicate(RBaseNode node, HierarchyDuplication hierarchyDuplication); + }; + VERUS_TYPEDEFS(SoundNodePtr); + + class SoundNodePwn : public SoundNodePtr + { + public: + ~SoundNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(SoundNodePwn); } diff --git a/Verus/src/World/WorldNodes/TerrainNode.h b/Verus/src/World/WorldNodes/TerrainNode.h index 3c62faa..b4a9ae2 100644 --- a/Verus/src/World/WorldNodes/TerrainNode.h +++ b/Verus/src/World/WorldNodes/TerrainNode.h @@ -1,56 +1,53 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // TerrainNode adds terrain. + class TerrainNode : public BaseNode { - // TerrainNode adds terrain. - class TerrainNode : public BaseNode + EditorTerrain _terrain; + + public: + struct Desc : BaseNode::Desc { - EditorTerrain _terrain; - - public: - struct Desc : BaseNode::Desc - { - Terrain::Desc _terrainDesc; - }; - VERUS_TYPEDEFS(Desc); - - TerrainNode(); - virtual ~TerrainNode(); - - void Init(RcDesc desc); - void Done(); - - virtual void Layout() override; - virtual void Draw() override; - - virtual void AddDefaultPickingBody() override {} - - virtual void Serialize(IO::RSeekableStream stream) override; - virtual void Deserialize(IO::RStream stream) override; - - // - RTerrain GetTerrain() { return _terrain; } - REditorTerrain GetEditorTerrain() { return _terrain; } - // + Terrain::Desc _terrainDesc; }; - VERUS_TYPEDEFS(TerrainNode); + VERUS_TYPEDEFS(Desc); - class TerrainNodePtr : public Ptr - { - public: - void Init(TerrainNode::RcDesc desc); - }; - VERUS_TYPEDEFS(TerrainNodePtr); + TerrainNode(); + virtual ~TerrainNode(); - class TerrainNodePwn : public TerrainNodePtr - { - public: - ~TerrainNodePwn() { Done(); } - void Done(); - }; - VERUS_TYPEDEFS(TerrainNodePwn); - } + void Init(RcDesc desc); + void Done(); + + virtual void Layout() override; + virtual void Draw() override; + + virtual void AddDefaultPickingBody() override {} + + virtual void Serialize(IO::RSeekableStream stream) override; + virtual void Deserialize(IO::RStream stream) override; + + // + RTerrain GetTerrain() { return _terrain; } + REditorTerrain GetEditorTerrain() { return _terrain; } + // + }; + VERUS_TYPEDEFS(TerrainNode); + + class TerrainNodePtr : public Ptr + { + public: + void Init(TerrainNode::RcDesc desc); + }; + VERUS_TYPEDEFS(TerrainNodePtr); + + class TerrainNodePwn : public TerrainNodePtr + { + public: + ~TerrainNodePwn() { Done(); } + void Done(); + }; + VERUS_TYPEDEFS(TerrainNodePwn); } diff --git a/Verus/src/World/WorldNodes/Types.h b/Verus/src/World/WorldNodes/Types.h index 2ca2334..76af9e7 100644 --- a/Verus/src/World/WorldNodes/Types.h +++ b/Verus/src/World/WorldNodes/Types.h @@ -1,42 +1,39 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + enum class NodeType : int { - enum class NodeType : int - { - unknown, + unknown, - base, + base, - model, - particles, + model, + particles, - ambient, - block, - blockChain, - controlPoint, - emitter, - instance, - light, - path, - physics, - prefab, - project, - shaker, - sound, - terrain, + ambient, + block, + blockChain, + controlPoint, + emitter, + instance, + light, + path, + physics, + prefab, + project, + shaker, + sound, + terrain, - trigger, + trigger, - site, + site, - character, - vehicle, + character, + vehicle, - count - }; - } + count + }; } diff --git a/Verus/src/World/WorldNodes/WorldNodes.h b/Verus/src/World/WorldNodes/WorldNodes.h index 9ea7675..0ab2faa 100644 --- a/Verus/src/World/WorldNodes/WorldNodes.h +++ b/Verus/src/World/WorldNodes/WorldNodes.h @@ -1,54 +1,51 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + enum class EditorCommandCode : int { - enum class EditorCommandCode : int - { - custom, - separator, - node_delete, - node_deleteHierarchy, - node_duplicate, - node_duplicateHierarchy, - node_goTo, - node_updateLocalTransform, - node_resetLocalTransform, - node_resetLocalTransformKeepGlobal, - node_pointAt, - node_moveTo, - node_special_fitParentBlock, - node_special_fillTheRoom, - model_insertBlockNode, - model_insertBlockAndPhysicsNodes, - model_selectAllBlocks, - particles_insertEmitterNode, - particles_insertEmitterAndSoundNodes, - particles_selectAllEmitters, - blockChain_generateNodes, - controlPoint_insertControlPoint, - path_insertBlockChain, - path_insertControlPoint, - physics_loadShapeFromFile, - physics_quickDynamicBox, - physics_quickStaticParentBlock, - prefab_insertInstanceNode, - prefab_updateInstances, - prefab_replaceSimilarWithInstances, - shaker_presetForIntensity - }; + custom, + separator, + node_delete, + node_deleteHierarchy, + node_duplicate, + node_duplicateHierarchy, + node_goTo, + node_updateLocalTransform, + node_resetLocalTransform, + node_resetLocalTransformKeepGlobal, + node_pointAt, + node_moveTo, + node_special_fitParentBlock, + node_special_fillTheRoom, + model_insertBlockNode, + model_insertBlockAndPhysicsNodes, + model_selectAllBlocks, + particles_insertEmitterNode, + particles_insertEmitterAndSoundNodes, + particles_selectAllEmitters, + blockChain_generateNodes, + controlPoint_insertControlPoint, + path_insertBlockChain, + path_insertControlPoint, + physics_loadShapeFromFile, + physics_quickDynamicBox, + physics_quickStaticParentBlock, + prefab_insertInstanceNode, + prefab_updateInstances, + prefab_replaceSimilarWithInstances, + shaker_presetForIntensity + }; - struct EditorCommand - { - CSZ _text = nullptr; - EditorCommandCode _code = EditorCommandCode::custom; + struct EditorCommand + { + CSZ _text = nullptr; + EditorCommandCode _code = EditorCommandCode::custom; - EditorCommand(CSZ text = nullptr, EditorCommandCode code = EditorCommandCode::custom) : _text(text), _code(code) {} - }; - VERUS_TYPEDEFS(EditorCommand); - } + EditorCommand(CSZ text = nullptr, EditorCommandCode code = EditorCommandCode::custom) : _text(text), _code(code) {} + }; + VERUS_TYPEDEFS(EditorCommand); } #include "Types.h" diff --git a/Verus/src/World/WorldUtils.h b/Verus/src/World/WorldUtils.h index b2d1e08..b93db60 100644 --- a/Verus/src/World/WorldUtils.h +++ b/Verus/src/World/WorldUtils.h @@ -1,53 +1,50 @@ // Copyright (C) 2021-2022, Dmitry Maluev (dmaluev@gmail.com). All rights reserved. #pragma once -namespace verus +namespace verus::World { - namespace World + // Managed by DeferredShading: + class DeferredShadingMeshes { - // Managed by DeferredShading: - class DeferredShadingMeshes + Mesh _meshDir; + Mesh _meshOmni; + Mesh _meshSpot; + Mesh _meshBox; + + public: + RMesh Get(CGI::LightType type) { - Mesh _meshDir; - Mesh _meshOmni; - Mesh _meshSpot; - Mesh _meshBox; - - public: - RMesh Get(CGI::LightType type) + switch (type) { - switch (type) - { - case CGI::LightType::omni: return _meshOmni; - case CGI::LightType::spot: return _meshSpot; - } - return _meshDir; + case CGI::LightType::omni: return _meshOmni; + case CGI::LightType::spot: return _meshSpot; } - RMesh GetBox() - { - return _meshBox; - } - }; - VERUS_TYPEDEFS(DeferredShadingMeshes); - - class WorldUtils : public Singleton, public Object + return _meshDir; + } + RMesh GetBox() { - private: - DeferredShadingMeshes _deferredShadingMeshes; - bool _editorMode = false; + return _meshBox; + } + }; + VERUS_TYPEDEFS(DeferredShadingMeshes); - public: - WorldUtils(); - ~WorldUtils(); + class WorldUtils : public Singleton, public Object + { + private: + DeferredShadingMeshes _deferredShadingMeshes; + bool _editorMode = false; - void Init(); - void Done(); + public: + WorldUtils(); + ~WorldUtils(); - RDeferredShadingMeshes GetDeferredShadingMeshes() { return _deferredShadingMeshes; } + void Init(); + void Done(); - bool IsEditorMode() const { return _editorMode; } - void SetEditorMode(bool b = true) { _editorMode = b; } - }; - VERUS_TYPEDEFS(WorldUtils); - } + RDeferredShadingMeshes GetDeferredShadingMeshes() { return _deferredShadingMeshes; } + + bool IsEditorMode() const { return _editorMode; } + void SetEditorMode(bool b = true) { _editorMode = b; } + }; + VERUS_TYPEDEFS(WorldUtils); } diff --git a/VulkanShaderCompiler/VulkanShaderCompiler.vcxproj b/VulkanShaderCompiler/VulkanShaderCompiler.vcxproj index b1a5124..f58ed6b 100644 --- a/VulkanShaderCompiler/VulkanShaderCompiler.vcxproj +++ b/VulkanShaderCompiler/VulkanShaderCompiler.vcxproj @@ -11,24 +11,24 @@ - 16.0 + 17.0 Win32Proj {1EA5F5D1-9138-406D-871B-3CD75343E14C} VulkanShaderCompiler - 10.0.20348.0 + 10.0.22000.0 DynamicLibrary false - v142 + v143 true Unicode DynamicLibrary false - v142 + v143 true Unicode @@ -46,12 +46,6 @@ - - false - - - false - Level3 @@ -63,6 +57,7 @@ Use pch.h Fast + stdcpp20 Windows @@ -83,6 +78,7 @@ Use pch.h Fast + stdcpp20 Windows