diff --git a/CMakeLists.txt b/CMakeLists.txt index f6c8884..e7a3d84 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,7 @@ # and include sub-projects here. # cmake_minimum_required (VERSION 3.8) +set(CMAKE_CXX_STANDARD 20) # Enable Hot Reload for MSVC compilers if supported. if (POLICY CMP0141) diff --git a/README.md b/README.md index 87797e4..7ea68a5 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ The project is still under development and the next updates will focus on the following tasks: - [x] Finish basic classes -- [x] Code refactoring and cleaning +- [ ] Code refactoring and cleaning - [ ] 3D support - [ ] Implementation of missing classes and functions - [ ] Content Pipeline diff --git a/framework/CMakeLists.txt b/framework/CMakeLists.txt index f762ab0..f337f0c 100644 --- a/framework/CMakeLists.txt +++ b/framework/CMakeLists.txt @@ -41,7 +41,7 @@ add_library (Xn65 STATIC "platform-dx/displaymode.cpp" "platform-dx/init.cpp" "platform-dx/buffer.cpp" -"platform-dx/audioengine.cpp" ) +"platform-dx/audioengine.cpp" "graphics/gresource.cpp" "platform-dx/effect.cpp") if (CMAKE_VERSION VERSION_GREATER 3.12) set_property(TARGET Xn65 PROPERTY CXX_STANDARD 20) @@ -52,6 +52,7 @@ endif() find_package(directxtk CONFIG REQUIRED) target_link_libraries( - Xn65 D3d11.lib dxgi.lib dxguid.lib d3dcompiler.lib Microsoft::DirectXTK + Xn65 D3d11.lib dxgi.lib dxguid.lib d3dcompiler.lib Microsoft::DirectXTK dxguid.lib "${PROJECT_INCLUDES_DIR}/libmspack/mspack.lib" + "${PROJECT_INCLUDES_DIR}/effects11/Effects11.lib" ) diff --git a/framework/content/manager.cpp b/framework/content/manager.cpp index 350c8e3..c20cb6d 100644 --- a/framework/content/manager.cpp +++ b/framework/content/manager.cpp @@ -3,7 +3,7 @@ namespace xna { sptr ContentManager::OpenStream(String const& assetName) const { const String filePath = _rootDirectory + "\\" + assetName + contentExtension; - const auto stream = New(filePath, FileMode::Open); + const auto stream = snew(filePath, FileMode::Open); if (stream->IsClosed()) return nullptr; diff --git a/framework/content/typereadermanager.cpp b/framework/content/typereadermanager.cpp index cb5277b..5ab9d76 100644 --- a/framework/content/typereadermanager.cpp +++ b/framework/content/typereadermanager.cpp @@ -157,7 +157,7 @@ namespace xna { void ContentTypeReaderManager::initMaps() { if (targetTypeToReader.empty() && readerTypeToReader.empty()) { - auto typeReader = New(); + auto typeReader = snew(); auto contentTypeReader = reinterpret_pointer_cast(typeReader); targetTypeToReader.insert({ typeof(), contentTypeReader}); diff --git a/framework/graphics/gresource.cpp b/framework/graphics/gresource.cpp new file mode 100644 index 0000000..5219809 --- /dev/null +++ b/framework/graphics/gresource.cpp @@ -0,0 +1,18 @@ +#include "xna/graphics/gresource.hpp" + +namespace xna { + GraphicsResource::GraphicsResource(sptr const& device) : m_device(device) {} + + sptr GraphicsResource::Device() const { + return m_device; + } + + bool GraphicsResource::Bind(sptr const& device) { + if (!device || device == m_device) + return false; + + m_device = device; + + return true; + } +} \ No newline at end of file diff --git a/framework/platform-dx/adapter.cpp b/framework/platform-dx/adapter.cpp index 964bf66..8dcd0b0 100644 --- a/framework/platform-dx/adapter.cpp +++ b/framework/platform-dx/adapter.cpp @@ -1,32 +1,26 @@ #include "xna/graphics/adapter.hpp" #include "xna/graphics/displaymode.hpp" -#include "xna/platform-dx/headers.hpp" -#include "xna/platform-dx/helpers.hpp" -#include "xna/platform-dx/implementations.hpp" #include "xna/game/gdevicemanager.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { static size_t getDisplayModesCount(IDXGIAdapter* adapter); static uptr createDisplayModeCollection(std::vector const& source); GraphicsAdapter::GraphicsAdapter() { - impl = uNew(); - } - - GraphicsAdapter::~GraphicsAdapter() { - impl = nullptr; + impl = unew(); } uptr GraphicsAdapter::DefaultAdapter() { IDXGIFactory1* pFactory = nullptr; if FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&pFactory)) - return nullptr; + Exception::Throw(ExMessage::CreateComponent); IDXGIAdapter1* pAdapter = nullptr; if (pFactory->EnumAdapters1(0, &pAdapter) != DXGI_ERROR_NOT_FOUND) { - auto adp = uNew(); + auto adp = unew(); adp->impl->_index = 0; adp->impl->dxadapter = pAdapter; @@ -40,39 +34,17 @@ namespace xna { return nullptr; } - void GraphicsAdapter::Adapters(std::vector>& adapters){ - IDXGIFactory1* pFactory = nullptr; - - if FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&pFactory)) - return; - - IDXGIAdapter1* pAdapter = nullptr; - UINT count = 0; - - for (; pFactory->EnumAdapters1(count, &pAdapter) != DXGI_ERROR_NOT_FOUND; ++count) { - auto adp = New(); - - adp->impl->_index = count; - adp->impl->dxadapter = pAdapter; - - adapters.push_back(adp); - } - - pFactory->Release(); - pFactory = nullptr; - } - void GraphicsAdapter::Adapters(std::vector>& adapters) { IDXGIFactory1* pFactory = nullptr; if FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&pFactory)) - return; + Exception::Throw(ExMessage::CreateComponent); IDXGIAdapter1* pAdapter = nullptr; UINT count = 0; for (; pFactory->EnumAdapters1(count, &pAdapter) != DXGI_ERROR_NOT_FOUND; ++count) { - auto adp = uNew(); + auto adp = unew(); adp->impl->_index = count; adp->impl->dxadapter = pAdapter; @@ -182,7 +154,7 @@ namespace xna { if (impl->dxadapter->EnumOutputs(0, &pOutput) != DXGI_ERROR_NOT_FOUND) { for (size_t f = 0; f < SURFACE_FORMAT_COUNT; ++f) { const auto currentSurface = static_cast(f); - DXGI_FORMAT format = DxHelpers::ConvertSurfaceToDXGIFORMAT(currentSurface); + DXGI_FORMAT format = DxHelpers::SurfaceFormatToDx(currentSurface); UINT numModes = 0; pOutput->GetDisplayModeList(format, 0, &numModes, nullptr); @@ -213,14 +185,14 @@ namespace xna { UINT bufferOffset = 0; if (impl->dxadapter->EnumOutputs(0, &pOutput) != DXGI_ERROR_NOT_FOUND) { - DXGI_FORMAT format = DxHelpers::ConvertSurfaceToDXGIFORMAT(surfaceFormat); + DXGI_FORMAT format = DxHelpers::SurfaceFormatToDx(surfaceFormat); UINT numModes = 0; pOutput->GetDisplayModeList(format, 0, &numModes, nullptr); if (numModes == 0) - return uNew(); + return unew(); std::vector buffer(numModes); pOutput->GetDisplayModeList(format, 0, &numModes, buffer.data()); @@ -231,7 +203,7 @@ namespace xna { return createDisplayModeCollection(buffer); } - return uNew(); + return unew(); } sptr GraphicsAdapter::CurrentDisplayMode() { @@ -275,7 +247,7 @@ namespace xna { if (adapter->EnumOutputs(0, &pOutput) != DXGI_ERROR_NOT_FOUND) { for (size_t f = 0; f < SURFACE_FORMAT_COUNT; ++f) { const auto currentSurface = static_cast(f); - DXGI_FORMAT format = DxHelpers::ConvertSurfaceToDXGIFORMAT(currentSurface); + DXGI_FORMAT format = DxHelpers::SurfaceFormatToDx(currentSurface); UINT num = 0; pOutput->GetDisplayModeList(format, 0, &num, nullptr); @@ -291,7 +263,7 @@ namespace xna { } static uptr createDisplayModeCollection(std::vector const& source) { - auto collection = uNew(); + auto collection = unew(); DisplayMode currentDisplayMode; std::vector> displayList; sptr pDisplay = nullptr; @@ -308,7 +280,7 @@ namespace xna { pDisplay->impl->Descriptions.push_back(description); } else { - pDisplay = New(); + pDisplay = snew(); pDisplay->Width = modedesc.Width; pDisplay->Height = modedesc.Height; pDisplay->Format = DxHelpers::ConvertDXGIFORMATToSurface(modedesc.Format); diff --git a/framework/platform-dx/audioengine.cpp b/framework/platform-dx/audioengine.cpp index 4e5cbce..fe6b877 100644 --- a/framework/platform-dx/audioengine.cpp +++ b/framework/platform-dx/audioengine.cpp @@ -1,4 +1,4 @@ -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { void AudioEngine::Initialize() { diff --git a/framework/platform-dx/blendstate.cpp b/framework/platform-dx/blendstate.cpp index d4ce0a3..bc9f84c 100644 --- a/framework/platform-dx/blendstate.cpp +++ b/framework/platform-dx/blendstate.cpp @@ -1,28 +1,104 @@ #include "xna/graphics/blendstate.hpp" #include "xna/graphics/gresource.hpp" -#include "xna/platform-dx/headers.hpp" -#include "xna/platform-dx/helpers.hpp" -#include "xna/graphics/blendstate.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { - BlendState::BlendState() : GraphicsResource(nullptr) { - impl = uNew(); - } + BlendState::BlendState() : BlendState(nullptr) {} BlendState::BlendState(sptr const& device) : GraphicsResource(device) { - impl = uNew(); + impl = unew(); + impl->dxDescription.AlphaToCoverageEnable = false; + impl->dxDescription.IndependentBlendEnable = false; + impl->dxDescription.RenderTarget[0].BlendEnable = true; + impl->dxDescription.RenderTarget[0].SrcBlend = DxHelpers::ConvertBlend(Blend::One); + impl->dxDescription.RenderTarget[0].DestBlend = DxHelpers::ConvertBlend(Blend::One); + impl->dxDescription.RenderTarget[0].BlendOp = DxHelpers::ConvertOperation(BlendFunction::Add); + impl->dxDescription.RenderTarget[0].SrcBlendAlpha = DxHelpers::ConvertBlend(Blend::One); + impl->dxDescription.RenderTarget[0].DestBlendAlpha = DxHelpers::ConvertBlend(Blend::One); + impl->dxDescription.RenderTarget[0].BlendOpAlpha = DxHelpers::ConvertOperation(BlendFunction::Add); + impl->dxDescription.RenderTarget[0].RenderTargetWriteMask = DxHelpers::ConvertColorWrite(ColorWriteChannels::All); } - BlendState::~BlendState() { - impl = nullptr; + BlendFunction BlendState::AlphaBlendFunction() const { + return DxHelpers::ConvertOperationDx(impl->dxDescription.RenderTarget[0].BlendOpAlpha); } - bool BlendState::Initialize(xna_error_ptr_arg) + void BlendState::AlphaBlendFunction(BlendFunction value) { + impl->dxDescription.RenderTarget[0].BlendOpAlpha = DxHelpers::ConvertOperation(value); + } + + Blend BlendState::AlphaDestinationBlend() const { + return DxHelpers::ConvertBlendDx(impl->dxDescription.RenderTarget[0].DestBlendAlpha); + } + + void BlendState::AlphaDestinationBlend(Blend value) { + impl->dxDescription.RenderTarget[0].DestBlendAlpha = DxHelpers::ConvertBlend(value); + } + + Blend BlendState::AlphaSourceBlend() const { + return DxHelpers::ConvertBlendDx(impl->dxDescription.RenderTarget[0].SrcBlendAlpha); + } + + void BlendState::AlphaSourceBlend(Blend value) { + impl->dxDescription.RenderTarget[0].SrcBlendAlpha = DxHelpers::ConvertBlend(value); + } + + BlendFunction BlendState::ColorBlendFunction() const { + return DxHelpers::ConvertOperationDx(impl->dxDescription.RenderTarget[0].BlendOp); + } + + void BlendState::ColorBlendFunction(BlendFunction value) { + impl->dxDescription.RenderTarget[0].BlendOp = DxHelpers::ConvertOperation(value); + } + + Blend BlendState::ColorDestinationBlend() const { + return DxHelpers::ConvertBlendDx(impl->dxDescription.RenderTarget[0].DestBlend); + } + + void BlendState::ColorDestinationBlend(Blend value) { + impl->dxDescription.RenderTarget[0].DestBlend = DxHelpers::ConvertBlend(value); + } + + Blend BlendState::ColorSourceBlend() const { + return DxHelpers::ConvertBlendDx(impl->dxDescription.RenderTarget[0].SrcBlend); + } + + void BlendState::ColorSourceBlend(Blend value) { + impl->dxDescription.RenderTarget[0].SrcBlend = DxHelpers::ConvertBlend(value); + } + + Color BlendState::BlendFactor() const { + auto color = Color( + impl->blendFactor[0], + impl->blendFactor[1], + impl->blendFactor[2], + impl->blendFactor[3] + ); + + return color; + } + + void BlendState::BlendFactor(Color const& value) { + auto v4 = value.ToVector4(); + + impl->blendFactor[0] = v4.X; + impl->blendFactor[1] = v4.Y; + impl->blendFactor[2] = v4.Z; + impl->blendFactor[3] = v4.W; + } + + Int BlendState::MultiSampleMask() const { + return static_cast(impl->sampleMask); + } + + void BlendState::MultiSampleMast(Int value) { + impl->sampleMask = static_cast(value); + } + + bool BlendState::Initialize() { if (!m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->dxBlendState) { @@ -35,30 +111,27 @@ namespace xna { &impl->dxBlendState); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; } - bool BlendState::Apply(xna_error_ptr_arg) { + bool BlendState::Apply() { if (!m_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::ApplyComponent); } if (!impl->dxBlendState) { - xna_error_apply(err, XnaErrorCode::UNINTIALIZED_RESOURCE); - return false; + Exception::Throw(ExMessage::UnintializedComponent); } - - m_device->impl->_context->OMSetBlendState( - impl->dxBlendState, - impl->blendFactor, + + m_device->impl->_context->OMSetBlendState( + impl->dxBlendState, + impl->blendFactor, impl->sampleMask); - return true; + return true; } void BlendState::AlphaToCoverageEnable(bool value) { @@ -83,17 +156,17 @@ namespace xna { } uptr BlendState::Opaque() { - auto blendState = uNew(); + auto blendState = unew(); blendState->impl->dxDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; - blendState->impl->dxDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; - blendState->impl->dxDescription.RenderTarget[0].DestBlend = D3D11_BLEND_DEST_ALPHA; + blendState->impl->dxDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + blendState->impl->dxDescription.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; blendState->impl->dxDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; return blendState; } uptr BlendState::AlphaBlend() { - auto blendState = std::unique_ptr(new BlendState()); + auto blendState = unew(); blendState->impl->dxDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendState->impl->dxDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendState->impl->dxDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; @@ -103,7 +176,7 @@ namespace xna { } uptr BlendState::Additive() { - auto blendState = std::unique_ptr(new BlendState()); + auto blendState = unew(); blendState->impl->dxDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendState->impl->dxDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA; blendState->impl->dxDescription.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; @@ -113,7 +186,7 @@ namespace xna { } uptr BlendState::NonPremultiplied() { - auto blendState = std::unique_ptr(new BlendState()); + auto blendState = unew(); blendState->impl->dxDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendState->impl->dxDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA; blendState->impl->dxDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; diff --git a/framework/platform-dx/buffer.cpp b/framework/platform-dx/buffer.cpp index c3e5c5a..938aced 100644 --- a/framework/platform-dx/buffer.cpp +++ b/framework/platform-dx/buffer.cpp @@ -1,26 +1,24 @@ #include "xna/graphics/buffer.hpp" #include "xna/common/numerics.hpp" -#include "xna/platform-dx/headers.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { ConstantBuffer::ConstantBuffer() : GraphicsResource(nullptr){ - impl = uNew(); + impl = unew(); } ConstantBuffer::ConstantBuffer(sptr const& device) : GraphicsResource(device){ - impl = uNew(); + impl = unew(); } ConstantBuffer::~ConstantBuffer() { impl = nullptr; } - bool ConstantBuffer::Initialize(xna_error_ptr_arg) + bool ConstantBuffer::Initialize() { if (!m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->_buffer) { @@ -34,29 +32,27 @@ namespace xna { &impl->_buffer); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; } DataBuffer::DataBuffer() : GraphicsResource(nullptr) { - impl = uNew(); + impl = unew(); } DataBuffer::DataBuffer(sptr const& device) : GraphicsResource(device) { - impl = uNew(); + impl = unew(); } DataBuffer::~DataBuffer() { impl = nullptr; } - bool DataBuffer::Initialize(xna_error_ptr_arg) { + bool DataBuffer::Initialize() { if (!m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->_blob) { @@ -68,21 +64,20 @@ namespace xna { } IndexBuffer::IndexBuffer() : GraphicsResource(nullptr) { - impl = uNew(); + impl = unew(); } IndexBuffer::IndexBuffer(sptr const& device) : GraphicsResource(device) { - impl = uNew(); + impl = unew(); } IndexBuffer::~IndexBuffer() { impl = nullptr; } - bool IndexBuffer::Apply(xna_error_ptr_arg) { + bool IndexBuffer::Apply() { if (!m_device || !m_device->impl->_context || !impl || !impl->dxBuffer) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::ApplyComponent); } m_device->impl->_context->IASetIndexBuffer(impl->dxBuffer, DXGI_FORMAT_R16_UINT, 0); @@ -91,26 +86,24 @@ namespace xna { } VertexBuffer::VertexBuffer() : GraphicsResource(nullptr) { - impl = uNew(); + impl = unew(); } VertexBuffer::VertexBuffer(sptr const& device) : GraphicsResource(device) { - impl = uNew(); + impl = unew(); } VertexBuffer::~VertexBuffer() { impl = nullptr; } - bool VertexBuffer::Apply(xna_error_ptr_arg) { + bool VertexBuffer::Apply() { if (!impl || !m_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::ApplyComponent); } if (!impl->dxBuffer) { - xna_error_apply(err, XnaErrorCode::UNINTIALIZED_RESOURCE); - return false; + Exception::Throw(ExMessage::UnintializedComponent); } UINT stride = impl->size; @@ -122,21 +115,20 @@ namespace xna { } VertexInputLayout::VertexInputLayout() : GraphicsResource(nullptr) { - impl = uNew(); + impl = unew(); } VertexInputLayout::VertexInputLayout(sptr const& device) : GraphicsResource(device) { - impl = uNew(); + impl = unew(); } VertexInputLayout::~VertexInputLayout() { impl = nullptr; } - bool VertexInputLayout::Initialize(DataBuffer& blob, xna_error_ptr_arg) { + bool VertexInputLayout::Initialize(DataBuffer& blob) { if (!impl || !m_device || !m_device->impl->_device || !blob.impl->_blob) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->_inputLayout) { @@ -152,8 +144,7 @@ namespace xna { &impl->_inputLayout); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; diff --git a/framework/platform-dx/depthstencilstate.cpp b/framework/platform-dx/depthstencilstate.cpp index 9d8f573..d1245bb 100644 --- a/framework/platform-dx/depthstencilstate.cpp +++ b/framework/platform-dx/depthstencilstate.cpp @@ -1,6 +1,5 @@ #include "xna/graphics/depthstencilstate.hpp" -#include "xna/platform-dx/headers.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { static D3D11_DEPTH_STENCIL_DESC defaultDesc() { @@ -19,32 +18,27 @@ namespace xna { _description.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; _description.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; - _description.StencilReadMask = 0; - _description.StencilWriteMask = 0; - _description.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; + _description.StencilReadMask = IntMaxValue; + _description.StencilWriteMask = IntMaxValue; + _description.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; return _description; } DepthStencilState::DepthStencilState() : GraphicsResource(nullptr) { - impl = uNew(); + impl = unew(); impl->dxDescription = defaultDesc(); } DepthStencilState::DepthStencilState(sptr const& device) : GraphicsResource(device) { - impl = uNew(); + impl = unew(); impl->dxDescription = defaultDesc(); - } + } - DepthStencilState::~DepthStencilState() { - impl = nullptr; - } - - bool DepthStencilState::Initialize(xna_error_ptr_arg) + bool DepthStencilState::Initialize() { if (!m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->dxDepthStencil) { @@ -57,23 +51,20 @@ namespace xna { &impl->dxDepthStencil); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; } - bool DepthStencilState::Apply(xna_error_ptr_arg) + bool DepthStencilState::Apply() { if (!m_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InvalidOperation); } if (!impl->dxDepthStencil) { - xna_error_apply(err, XnaErrorCode::UNINTIALIZED_RESOURCE); - return false; + Exception::Throw(ExMessage::UnintializedComponent); } m_device->impl->_context->OMSetDepthStencilState(impl->dxDepthStencil, 0); @@ -82,7 +73,7 @@ namespace xna { } uptr DepthStencilState::None() { - auto stencil = uNew(); + auto stencil = unew(); stencil->impl->dxDescription.DepthEnable = false; stencil->impl->dxDescription.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; @@ -90,7 +81,7 @@ namespace xna { } uptr DepthStencilState::Default() { - auto stencil = uNew(); + auto stencil = unew(); stencil->impl->dxDescription.DepthEnable = true; stencil->impl->dxDescription.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; @@ -98,31 +89,31 @@ namespace xna { } uptr DepthStencilState::DepthRead() { - auto stencil = uNew(); + auto stencil = unew(); stencil->impl->dxDescription.DepthEnable = true; stencil->impl->dxDescription.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; return stencil; } - void DepthStencilState::DepthEnabled(bool value) { + void DepthStencilState::DepthBufferEnable(bool value) { impl->dxDescription.DepthEnable = value; } - void DepthStencilState::DepthWriteEnabled(bool value) { + void DepthStencilState::DepthBufferWriteEnable(bool value) { impl->dxDescription.DepthWriteMask = static_cast(value); } - void DepthStencilState::DepthCompareFunction(ComparisonFunction value) { + void DepthStencilState::DepthBufferFunction(ComparisonFunction value) { const auto _value = static_cast(value) + 1; impl->dxDescription.DepthFunc = static_cast(_value); } - void DepthStencilState::StencilEnabled(bool value) { + void DepthStencilState::StencilEnable(bool value) { impl->dxDescription.StencilEnable = value; } - void DepthStencilState::StencilReadMask(int value) { + void DepthStencilState::StencilMask(int value) { impl->dxDescription.StencilReadMask = static_cast(value); } @@ -130,64 +121,64 @@ namespace xna { impl->dxDescription.StencilWriteMask = static_cast(value); } - void DepthStencilState::StencilFrontFacePass(StencilOperation value) { + void DepthStencilState::StencilPass(StencilOperation value) { const auto _value = static_cast(value) + 1; impl->dxDescription.FrontFace.StencilPassOp = static_cast(_value); } - void DepthStencilState::StencilFrontFaceFail(StencilOperation value) { + void DepthStencilState::StencilFail(StencilOperation value) { const auto _value = static_cast(value) + 1; impl->dxDescription.FrontFace.StencilFailOp = static_cast(_value); } - void DepthStencilState::StencilFrontFaceDepthFail(StencilOperation value) { + void DepthStencilState::StencilDepthBufferFail(StencilOperation value) { const auto _value = static_cast(value) + 1; impl->dxDescription.FrontFace.StencilDepthFailOp = static_cast(_value); } - void DepthStencilState::StencilFrontFaceCompare(ComparisonFunction value) { + void DepthStencilState::StencilFunction(ComparisonFunction value) { const auto _value = static_cast(value) + 1; impl->dxDescription.FrontFace.StencilFunc = static_cast(_value); } - void DepthStencilState::StencilBackFacePass(StencilOperation value) { + void DepthStencilState::CounterClockwiseStencilPass(StencilOperation value) { const auto _value = static_cast(value) + 1; impl->dxDescription.BackFace.StencilPassOp = static_cast(_value); } - void DepthStencilState::StencilBackFaceFail(StencilOperation value) { + void DepthStencilState::CounterClockwiseStencilFail(StencilOperation value) { const auto _value = static_cast(value) + 1; impl->dxDescription.BackFace.StencilFailOp = static_cast(_value); } - void DepthStencilState::StencilBackFaceDepthFail(StencilOperation value) { + void DepthStencilState::CounterClockwiseStencilDepthBufferFail(StencilOperation value) { const auto _value = static_cast(value) + 1; impl->dxDescription.BackFace.StencilDepthFailOp = static_cast(_value); } - void DepthStencilState::StencilBackFaceCompare(ComparisonFunction value) { + void DepthStencilState::CounterClockwiseStencilFunction(ComparisonFunction value) { const auto _value = static_cast(value) + 1; impl->dxDescription.BackFace.StencilFunc = static_cast(_value); } - bool DepthStencilState::DepthEnabled() const { + bool DepthStencilState::DepthBufferEnable() const { return impl->dxDescription.DepthEnable; } - bool DepthStencilState::DepthWriteEnabled() const { + bool DepthStencilState::DepthBufferWriteEnable() const { return static_cast(impl->dxDescription.DepthWriteMask); } - ComparisonFunction DepthStencilState::DepthCompareFunction() const { + ComparisonFunction DepthStencilState::DepthBufferFunction() const { const auto _value = static_cast(impl->dxDescription.DepthFunc) - 1; return static_cast(_value); } - bool DepthStencilState::StencilEnabled() const { + bool DepthStencilState::StencilEnable() const { return impl->dxDescription.StencilEnable; } - Int DepthStencilState::StencilReadMask() const { + Int DepthStencilState::StencilMask() const { return static_cast(impl->dxDescription.StencilReadMask); } @@ -195,42 +186,42 @@ namespace xna { return static_cast(impl->dxDescription.StencilWriteMask); } - StencilOperation DepthStencilState::StencilFrontFacePass() const { + StencilOperation DepthStencilState::StencilPass() const { const auto _value = static_cast(impl->dxDescription.FrontFace.StencilPassOp) - 1; return static_cast(_value); } - StencilOperation DepthStencilState::StencilFrontFaceFail() const { + StencilOperation DepthStencilState::StencilFail() const { const auto _value = static_cast(impl->dxDescription.FrontFace.StencilFailOp) - 1; return static_cast(_value); } - StencilOperation DepthStencilState::StencilFrontFaceDepthFail() const { + StencilOperation DepthStencilState::StencilDepthBufferFail() const { const auto _value = static_cast(impl->dxDescription.FrontFace.StencilDepthFailOp) - 1; return static_cast(_value); } - ComparisonFunction DepthStencilState::StencilFrontFaceCompare() const { + ComparisonFunction DepthStencilState::StencilFunction() const { const auto _value = static_cast(impl->dxDescription.FrontFace.StencilFunc) - 1; return static_cast(_value); } - StencilOperation DepthStencilState::StencilBackFacePass() const { + StencilOperation DepthStencilState::CounterClockwiseStencilPass() const { const auto _value = static_cast(impl->dxDescription.BackFace.StencilPassOp) - 1; return static_cast(_value); } - StencilOperation DepthStencilState::StencilBackFaceFail() const { + StencilOperation DepthStencilState::CounterClockwiseStencilFail() const { const auto _value = static_cast(impl->dxDescription.BackFace.StencilFailOp) - 1; return static_cast(_value); } - StencilOperation DepthStencilState::StencilBackFaceDepthFail() const { + StencilOperation DepthStencilState::CounterClockwiseStencilDepthBufferFail() const { const auto _value = static_cast(impl->dxDescription.BackFace.StencilDepthFailOp) - 1; return static_cast(_value); } - ComparisonFunction DepthStencilState::StencilBackFaceCompare() const { + ComparisonFunction DepthStencilState::CounterClockwiseStencilFunction() const { const auto _value = static_cast(impl->dxDescription.BackFace.StencilFunc) - 1; return static_cast(_value); } diff --git a/framework/platform-dx/device.cpp b/framework/platform-dx/device.cpp index 3619c6d..a0ac169 100644 --- a/framework/platform-dx/device.cpp +++ b/framework/platform-dx/device.cpp @@ -1,8 +1,8 @@ -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" #include "xna/game/gdevicemanager.hpp" namespace xna { - void reset(GraphicsDevice::PlatformImplementation& impl) + static void reset(GraphicsDevice::PlatformImplementation& impl) { if (impl._device) { impl._device->Release(); @@ -18,19 +18,13 @@ namespace xna { impl._factory->Release(); impl._factory = nullptr; } - - impl._blendState = nullptr; - impl._swapChain = nullptr; - impl._renderTarget2D = nullptr; } - bool createDevice(GraphicsDevice::PlatformImplementation& impl) { + static void createDevice(GraphicsDevice::PlatformImplementation& impl) { auto createDeviceFlags = 0; #if _DEBUG createDeviceFlags = D3D11_CREATE_DEVICE_FLAG::D3D11_CREATE_DEVICE_DEBUG; #endif - - auto hr = D3D11CreateDevice( impl._adapter->impl->dxadapter, D3D_DRIVER_TYPE_UNKNOWN, @@ -56,10 +50,11 @@ namespace xna { D3D11_SDK_VERSION, &impl._device, &impl._featureLevel, - &impl._context); + &impl._context); + + if FAILED(hr) + Exception::Throw(ExMessage::CreateComponent); } - - return SUCCEEDED(hr); } GraphicsDevice::GraphicsDevice() { @@ -75,52 +70,52 @@ namespace xna { impl = unew(); impl->_adapter = info.Adapter; + impl->_gameWindow = info.Window; impl->_presentationParameters = info.Parameters; impl->_adapter->CurrentDisplayMode( impl->_presentationParameters->BackBufferFormat, impl->_presentationParameters->BackBufferWidth, impl->_presentationParameters->BackBufferHeight); - } + } - GraphicsDevice::~GraphicsDevice() { - impl = nullptr; - } + bool GraphicsDevice::Initialize() { + auto _this = shared_from_this(); - bool GraphicsDevice::Initialize(GameWindow& gameWindow) { if (!impl) impl = uptr(); reset(*impl); - - auto _this = shared_from_this(); - if (!createDevice(*impl)) - return false; + createDevice(*impl); auto hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&impl->_factory); - if (FAILED(hr)) - return false; + + if FAILED(hr) + Exception::Throw(ExMessage::CreateComponent); - const auto bounds = gameWindow.ClientBounds(); + const auto bounds = impl->_gameWindow->ClientBounds(); impl->_viewport = xna::Viewport(0.0F, 0.0F, static_cast(bounds.Width), static_cast(bounds.Height), 0.0F, 1.F); - COLORREF color = gameWindow.impl->Color(); + COLORREF color = impl->_gameWindow->impl->Color(); impl->_backgroundColor[0] = GetRValue(color) / 255.0f; impl->_backgroundColor[1] = GetGValue(color) / 255.0f; impl->_backgroundColor[2] = GetBValue(color) / 255.0f; impl->_backgroundColor[3] = 1.0f; - impl->_swapChain = New(_this); + impl->_swapChain = snew(_this); impl->_swapChain->Initialize(); - hr = impl->_factory->MakeWindowAssociation(gameWindow.impl->WindowHandle(), DXGI_MWA_NO_ALT_ENTER); - if (FAILED(hr)) return false; + hr = impl->_factory->MakeWindowAssociation(impl->_gameWindow->impl->WindowHandle(), DXGI_MWA_NO_ALT_ENTER); + + if (FAILED(hr)) + Exception::Throw(ExMessage::MakeWindowAssociation); - impl->_renderTarget2D = New(_this); + impl->_renderTarget2D = snew(_this); + if (!impl->_renderTarget2D->Initialize()) return false; @@ -136,9 +131,7 @@ namespace xna { impl->_context->RSSetViewports(1, &view); - impl->_blendState = BlendState::NonPremultiplied(); - impl->_blendState->Bind(_this); - impl->_blendState->Apply(); + impl->InitializeAndApplyStates(_this); return true; } @@ -177,13 +170,7 @@ namespace xna { if (!impl) return nullptr; return impl->_adapter; - } - - void GraphicsDevice::Adapter(sptr const& adapter) { - if (!impl) return; - - impl->_adapter = adapter; - } + } xna::Viewport GraphicsDevice::Viewport() const { if (!impl) return {}; @@ -202,4 +189,41 @@ namespace xna { impl->_usevsync = use; } + + + sptr GraphicsDevice::BlendState() const { + return impl->_blendState; + } + + void GraphicsDevice::BlendState(sptr const& value) { + impl->_blendState = value; + } + + sptr GraphicsDevice::DepthStencilState() const { + return impl->_depthStencilState; + } + + void GraphicsDevice::DepthStencilState(sptr const& value) { + impl->_depthStencilState = value; + } + + sptr GraphicsDevice::RasterizerState() const { + return impl->_rasterizerState; + } + + void GraphicsDevice::RasterizerState(sptr const& value) { + impl->_rasterizerState = value; + } + + sptr GraphicsDevice::SamplerStates() const { + return impl->_samplerStates; + } + + Int GraphicsDevice::MultiSampleMask() const { + return impl->_multiSampleMask; + } + + void GraphicsDevice::MultiSampleMask(Int value) { + impl->_multiSampleMask = value; + } } \ No newline at end of file diff --git a/framework/platform-dx/displaymode.cpp b/framework/platform-dx/displaymode.cpp index a80659f..d749fc6 100644 --- a/framework/platform-dx/displaymode.cpp +++ b/framework/platform-dx/displaymode.cpp @@ -1,14 +1,10 @@ -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" #include "xna/graphics/displaymode.hpp" namespace xna { DisplayMode::DisplayMode() { - impl = uNew(); - } - - DisplayMode::~DisplayMode() { - impl = nullptr; - } + impl = unew(); + } size_t DisplayModeCollection::SurfaceCount(SurfaceFormat format) const { diff --git a/framework/platform-dx/effect.cpp b/framework/platform-dx/effect.cpp new file mode 100644 index 0000000..6a5c797 --- /dev/null +++ b/framework/platform-dx/effect.cpp @@ -0,0 +1,781 @@ +#include "xna/graphics/effect.hpp" +#include "xna/platform-dx/dx.hpp" + +namespace xna { + Effect::Effect(sptr const& device, std::vector const& effectCode) : + GraphicsResource(device) { + + if (!device) + throw std::invalid_argument("Effect::Effect: invalid argument (device)."); + + impl = unew(); + + const auto result = D3DX11CreateEffectFromMemory( + //void* pData, + effectCode.data(), + //SIZE_T DataLength, + effectCode.size(), + //UINT FXFlags, + 0, + //ID3D11Device * pDevice, + device->impl->_device, + //ID3DX11Effect * *ppEffect + &impl->dxEffect + ); + + if FAILED(result) + throw std::runtime_error("Effect::Effect: Unable to create an effect with memory data."); + } + + PEffectTechnique Effect::CurrentTechnique() const { + D3DX11_EFFECT_DESC desc; + impl->dxEffect->GetDesc(&desc); + + auto tech = impl->dxEffect->GetTechniqueByIndex(0); + + auto technique = snew(); + technique->impl->dxContext = m_device->impl->_context; + technique->impl->dxContext->AddRef(); + + tech->Release(); + tech = nullptr; + + return technique; + } + + EffectAnnotation::EffectAnnotation() { + impl = unew(); + } + + Int EffectAnnotation::ColumCount() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::ColumCount: error getting D3DX11_EFFECT_TYPE_DESC"); + + return static_cast(desc.Columns); + } + + String EffectAnnotation::Name() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::Name: error getting D3DX11_EFFECT_TYPE_DESC"); + + return String(desc.TypeName); + } + + EffectParameterClass EffectAnnotation::ParameterClass() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::ParameterClass: error getting D3DX11_EFFECT_TYPE_DESC"); + + switch (desc.Class) + { + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_MATRIX_COLUMNS: + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_MATRIX_ROWS: + return EffectParameterClass::Matrix; + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_OBJECT: + return EffectParameterClass::Object; + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_SCALAR: + return EffectParameterClass::Scalar; + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_STRUCT: + return EffectParameterClass::Struct; + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_VECTOR: + return EffectParameterClass::Vector; + default: + throw std::runtime_error("EffectAnnotation::ParameterClass: invalid EffectParameterClass."); + } + } + + Int EffectAnnotation::RowCount() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::RowCount: error getting D3DX11_EFFECT_TYPE_DESC"); + + return static_cast(desc.Rows); + } + + String EffectAnnotation::Semantic() const { + auto type = impl->dxVariable->GetType(); + auto semantic = type->GetMemberSemantic(0); + + type->Release(); + type = nullptr; + + return std::string(semantic); + } + + bool EffectAnnotation::GetValueBoolean() const { + auto scalar = impl->dxVariable->AsScalar(); + + bool value; + auto hr = scalar->GetBool(&value); + + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::GetValueBoolean: Unable to get boolean value."); + + return value; + } + + Int EffectAnnotation::GetValueInt32() const { + auto scalar = impl->dxVariable->AsScalar(); + + int value; + auto hr = scalar->GetInt(&value); + + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::GetValueInt32: Unable to get interger value."); + + return static_cast(value); + } + + Matrix EffectAnnotation::GetValueMatrix() const { + auto matrix = impl->dxVariable->AsMatrix(); + + float values[16]; + auto hr = matrix->GetMatrix(values); + matrix->Release(); + matrix = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::GetValueMatrix: Unable to get matrix value."); + + Matrix m; + m.M11 = values[0]; + m.M12 = values[1]; + m.M13 = values[2]; + m.M14 = values[3]; + m.M21 = values[4]; + m.M22 = values[5]; + m.M23 = values[6]; + m.M24 = values[7]; + m.M31 = values[8]; + m.M32 = values[9]; + m.M33 = values[10]; + m.M34 = values[11]; + m.M41 = values[12]; + m.M42 = values[13]; + m.M43 = values[14]; + m.M44 = values[15]; + + return m; + } + + float EffectAnnotation::GetValueSingle() const { + auto scalar = impl->dxVariable->AsScalar(); + + float value; + auto hr = scalar->GetFloat(&value); + + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::GetValueSingle: Unable to get float value."); + + return value; + } + + String EffectAnnotation::GetValueString() const { + auto str = impl->dxVariable->AsString(); + + LPCSTR data; + const auto hr = str->GetString(&data); + + str->Release(); + str = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::GetValueString: Unable to get string value."); + + return String(data); + } + + Vector2 EffectAnnotation::GetValueVector2() const { + auto scalar = impl->dxVariable->AsScalar(); + + float values[2]; + auto hr = scalar->GetFloatArray(values, 0, 2); + + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::GetValueVector2: Unable to get Vector2 value."); + + Vector2 v; + v.X = values[0]; + v.Y = values[1]; + + return v; + } + + Vector3 EffectAnnotation::GetValueVector3() const { + auto scalar = impl->dxVariable->AsScalar(); + + float values[3]; + auto hr = scalar->GetFloatArray(values, 0, 3); + + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::GetValueVector3: Unable to get Vector3 value."); + + Vector3 v; + v.X = values[0]; + v.Y = values[1]; + v.Z = values[2]; + + return v; + } + + Vector4 EffectAnnotation::GetValueVector4() const { + auto scalar = impl->dxVariable->AsScalar(); + + float values[4]; + auto hr = scalar->GetFloatArray(values, 0, 4); + + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectAnnotation::GetValueVector4: Unable to get Vector4 value."); + + Vector4 v; + v.X = values[0]; + v.Y = values[1]; + v.Z = values[2]; + v.W = values[3]; + + return v; + } + + EffectPass::EffectPass() { + impl = unew(); + } + + String EffectPass::Name() const { + if (!impl->dxPass) + throw std::runtime_error("EffectPass::Name: The class was not initialized correctly"); + + D3DX11_PASS_DESC desc{}; + impl->dxPass->GetDesc(&desc); + + return String(desc.Name); + } + + PEffectAnnotationCollection EffectPass::Annotations() const { + if (!impl->dxPass) + throw std::runtime_error("EffectPass::Annotations: The class was not initialized correctly"); + + D3DX11_PASS_DESC desc{}; + const auto hr = impl->dxPass->GetDesc(&desc); + + if FAILED(hr) + throw std::runtime_error("EffectPass::Annotations: error getting D3DX11_PASS_DESC"); + + auto annotCount = desc.Annotations; + + if (annotCount == 0) + return snew(); + + std::vector list(annotCount); + + for (size_t i = 0; i < annotCount; ++i) { + auto current = impl->dxPass->GetAnnotationByIndex(i); + auto annotation = snew(); + annotation->impl->dxVariable = current; + annotation->impl->dxVariable->AddRef(); + + current->Release(); + current = nullptr; + + list[i] = annotation; + } + + auto collection = snew(list); + return collection; + } + + void EffectPass::Apply() { + if (!impl->dxPass) + throw std::runtime_error("EffectPass::Apply: The class was not initialized correctly"); + + const auto hr = impl->dxPass->Apply(0, impl->dxContext); + + if FAILED(hr) + throw std::runtime_error("EffectPass::Apply: error to call Apply"); + } + + EffectTechnique::EffectTechnique() { + impl = unew(); + } + + String EffectTechnique::Name() const { + D3DX11_TECHNIQUE_DESC desc; + const auto hr = impl->dxTechnique->GetDesc(&desc); + + if FAILED(hr) + throw std::runtime_error("EffectTechnique::Name: error getting D3DX11_TECHNIQUE_DESC"); + + return String(desc.Name); + } + + PEffectAnnotationCollection EffectTechnique::Annotations() const { + D3DX11_TECHNIQUE_DESC desc; + const auto hr = impl->dxTechnique->GetDesc(&desc); + + if FAILED(hr) + throw std::runtime_error("EffectTechnique::Annotations: error getting D3DX11_TECHNIQUE_DESC"); + + auto annotCount = desc.Annotations; + + if (annotCount == 0) + return snew(); + + std::vector list(annotCount); + + for (size_t i = 0; i < annotCount; ++i) { + auto current = impl->dxTechnique->GetAnnotationByIndex(i); + auto annotation = snew(); + annotation->impl->dxVariable = current; + annotation->impl->dxVariable->AddRef(); + + current->Release(); + current = nullptr; + + list[i] = annotation; + } + + auto collection = snew(list); + return collection; + } + + PEffectPassCollection EffectTechnique::Passes() const { + D3DX11_TECHNIQUE_DESC desc; + const auto hr = impl->dxTechnique->GetDesc(&desc); + + if FAILED(hr) + throw std::runtime_error("EffectTechnique::Passes: error getting D3DX11_TECHNIQUE_DESC"); + + auto passCount = desc.Passes; + + if (passCount == 0) + return snew(); + + std::vector list(passCount); + + for (size_t i = 0; i < passCount; ++i) { + auto current = impl->dxTechnique->GetPassByIndex(i); + + auto pass = snew(); + pass->impl->dxPass = current; + pass->impl->dxPass->AddRef(); + + current->Release(); + current = nullptr; + + pass->impl->dxContext = impl->dxContext; + pass->impl->dxContext->AddRef(); + + list[i] = pass; + } + + auto collection = snew(list); + return collection; + } + + EffectParameter::EffectParameter() { + impl = unew(); + } + + PEffectAnnotationCollection EffectParameter::Annotations() const { + D3DX11_EFFECT_VARIABLE_DESC desc; + const auto hr = impl->dxVariable->GetDesc(&desc); + + if FAILED(hr) + throw std::runtime_error("EffectParameter::Annotations: error getting D3DX11_EFFECT_VARIABLE_DESC"); + + auto annotCount = desc.Annotations; + + if (annotCount == 0) + return snew(); + + std::vector list(annotCount); + + for (size_t i = 0; i < annotCount; ++i) { + auto current = impl->dxVariable->GetAnnotationByIndex(i); + auto annotation = snew(); + annotation->impl->dxVariable = current; + annotation->impl->dxVariable->AddRef(); + + current->Release(); + current = nullptr; + + list[i] = annotation; + } + + auto collection = snew(list); + return collection; + } + + Int EffectParameter::ColumnCount() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::ColumnCount: error getting D3DX11_EFFECT_VARIABLE_DESC"); + + return static_cast(desc.Columns); + } + + Int EffectParameter::RowCount() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::RowCount: error getting D3DX11_EFFECT_TYPE_DESC"); + + return static_cast(desc.Rows); + } + + String EffectParameter::Semantic() const { + auto type = impl->dxVariable->GetType(); + auto semantic = type->GetMemberSemantic(0); + + type->Release(); + type = nullptr; + + return std::string(semantic); + } + + EffectParameterType EffectParameter::ParameterType() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::ParameterType: error getting D3DX11_EFFECT_TYPE_DESC"); + + switch (desc.Type) + { + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_BOOL: + return EffectParameterType::Bool; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_INT: + return EffectParameterType::Int32; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_FLOAT: + return EffectParameterType::Single; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_STRING: + return EffectParameterType::String; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_TEXTURE: + return EffectParameterType::Texture; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_TEXTURE1D: + return EffectParameterType::Texture1D; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_TEXTURE2D: + return EffectParameterType::Texture2D; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_TEXTURE3D: + return EffectParameterType::Texture3D; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_TEXTURECUBE: + return EffectParameterType::TextureCube; + case D3D_SHADER_VARIABLE_TYPE::D3D_SVT_VOID: + return EffectParameterType::Void; + default: + throw std::runtime_error("EffectParameter::ParameterType: invalid EffectParameterType."); + } + } + + EffectParameterClass EffectParameter::ParameterClass() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::ParameterClass: error getting D3DX11_EFFECT_TYPE_DESC"); + + switch (desc.Class) + { + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_MATRIX_COLUMNS: + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_MATRIX_ROWS: + return EffectParameterClass::Matrix; + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_OBJECT: + return EffectParameterClass::Object; + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_SCALAR: + return EffectParameterClass::Scalar; + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_STRUCT: + return EffectParameterClass::Struct; + case D3D_SHADER_VARIABLE_CLASS::D3D_SVC_VECTOR: + return EffectParameterClass::Vector; + default: + throw std::runtime_error("EffectParameter::ParameterClass: invalid EffectParameterClass."); + } + } + + String EffectParameter::Name() const { + auto type = impl->dxVariable->GetType(); + D3DX11_EFFECT_TYPE_DESC desc{}; + const auto hr = type->GetDesc(&desc); + + type->Release(); + type = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::Name: error getting D3DX11_EFFECT_TYPE_DESC"); + + return String(desc.TypeName); + } + + sptr EffectParameter::Elements() const { + uint32_t index = 0; + + auto collection = snew(); + + while (true) { + auto el = impl->dxVariable->GetElement(index); + + if (!el) + break; + + auto efparam = snew(); + efparam->impl->dxVariable = el; + efparam->impl->dxVariable->AddRef(); + + el->Release(); + el = nullptr; + } + + + return collection; + } + + sptr EffectParameter::StructureMembers() const { + uint32_t index = 0; + + auto collection = snew(); + + while (true) { + auto member = impl->dxVariable->GetMemberByIndex(index); + + if (!member) + break; + + auto efparam = snew(); + efparam->impl->dxVariable = member; + efparam->impl->dxVariable->AddRef(); + + member->Release(); + member = nullptr; + } + + + return collection; + } + + bool EffectParameter::GetValueBoolean() const { + auto scalar = impl->dxVariable->AsScalar(); + + bool value; + const auto hr = scalar->GetBool(&value); + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::GetValueBoolean: Unable to get boolean value."); + + return value; + } + + std::vector EffectParameter::GetValueBooleanArray(size_t count) const { + auto scalar = impl->dxVariable->AsScalar(); + auto arr = std::make_unique(count); + + const auto hr = scalar->GetBoolArray(arr.get(), 0, count); + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::GetValueBooleanArray: Unable to get boolean value."); + + std::vector data(count); + + for (size_t i = 0; i < count; ++i) { + data[i] = arr[i]; + } + + return data; + } + + Int EffectParameter::GetValueInt32() const { + auto scalar = impl->dxVariable->AsScalar(); + + Int value; + const auto hr = scalar->GetInt(&value); + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::GetValueInt32: Unable to get int value."); + + return value; + } + + std::vector EffectParameter::GetValueInt32Array(size_t count) const { + auto scalar = impl->dxVariable->AsScalar(); + std::vector data(count); + + const auto hr = scalar->GetIntArray(data.data(), 0, count); + scalar->Release(); + scalar = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::GetValueInt32Array: Unable to get int value."); + + return data; + } + + Matrix EffectParameter::GetValueMatrix() const { + auto matrix = impl->dxVariable->AsMatrix(); + float values[16]; + auto hr = matrix->GetMatrix(values); + matrix->Release(); + matrix = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::GetValueIntMatrix: Unable to get matrix value."); + + Matrix m; + m.M11 = values[0]; + m.M12 = values[1]; + m.M13 = values[2]; + m.M14 = values[3]; + m.M21 = values[4]; + m.M22 = values[5]; + m.M23 = values[6]; + m.M24 = values[7]; + m.M31 = values[8]; + m.M32 = values[9]; + m.M33 = values[10]; + m.M34 = values[11]; + m.M41 = values[12]; + m.M42 = values[13]; + m.M43 = values[14]; + m.M44 = values[15]; + + return m; + } + + std::vector EffectParameter::GetValueMatrixArray(size_t count) const { + auto matrix = impl->dxVariable->AsMatrix(); + const auto elements = count * 16; + auto arr = std::make_unique(count * elements); + + auto hr = matrix->GetMatrixArray(arr.get(), 0, elements); + matrix->Release(); + matrix = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::GetValuetMatrixArray: Unable to get matrix value."); + + auto index = 0; + std::vector data(count); + + for (size_t i = 0; i < elements; ++i) { + Matrix m; + m.M11 = arr[i]; + m.M12 = arr[++i]; + m.M13 = arr[++i]; + m.M14 = arr[++i]; + m.M21 = arr[++i]; + m.M22 = arr[++i]; + m.M23 = arr[++i]; + m.M24 = arr[++i]; + m.M31 = arr[++i]; + m.M32 = arr[++i]; + m.M33 = arr[++i]; + m.M34 = arr[++i]; + m.M41 = arr[++i]; + m.M42 = arr[++i]; + m.M43 = arr[++i]; + m.M44 = arr[++i]; + + data[index] = m; + ++index; + } + + return data; + } + + Matrix EffectParameter::GetValueMatrixTranspose() const { + auto matrix = impl->dxVariable->AsMatrix(); + float values[16]; + auto hr = matrix->GetMatrixTranspose(values); + matrix->Release(); + matrix = nullptr; + + if FAILED(hr) + throw std::runtime_error("EffectParameter::GetValueIntMatrix: Unable to get matrix value."); + + Matrix m; + m.M11 = values[0]; + m.M12 = values[1]; + m.M13 = values[2]; + m.M14 = values[3]; + m.M21 = values[4]; + m.M22 = values[5]; + m.M23 = values[6]; + m.M24 = values[7]; + m.M31 = values[8]; + m.M32 = values[9]; + m.M33 = values[10]; + m.M34 = values[11]; + m.M41 = values[12]; + m.M42 = values[13]; + m.M43 = values[14]; + m.M44 = values[15]; + + return m; + } +} \ No newline at end of file diff --git a/framework/platform-dx/game.cpp b/framework/platform-dx/game.cpp index 7c74c26..0c598dc 100644 --- a/framework/platform-dx/game.cpp +++ b/framework/platform-dx/game.cpp @@ -1,27 +1,27 @@ -#include "xna/csharp/type.hpp" -#include "xna/game/time.hpp" -#include "xna/game/component.hpp" -#include "xna/game/servicecontainer.hpp" -#include "xna/platform-dx/implementations.hpp" -#include "xna/game/gdevicemanager.hpp" #include "xna/content/manager.hpp" +#include "xna/csharp/type.hpp" +#include "xna/game/component.hpp" +#include "xna/game/gdevicemanager.hpp" +#include "xna/game/servicecontainer.hpp" +#include "xna/game/time.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { Game::Game() { impl = unew(); - services = New(); + services = snew(); auto iservice = reinterpret_pointer_cast(services); - _contentManager = New(services, ""); + _contentManager = snew(services, ""); _contentManager->_gameServices = iservice; - _gameWindow = New(); + _gameWindow = snew(); _gameWindow->impl->Color(146, 150, 154); _gameWindow->Title("XN65"); _gameWindow->impl->Size( GraphicsDeviceManager::DefaultBackBufferWidth, GraphicsDeviceManager::DefaultBackBufferHeight, false); - _gameComponents = New(); + _gameComponents = snew(); } Game::~Game() { diff --git a/framework/platform-dx/gamepad.cpp b/framework/platform-dx/gamepad.cpp index de6655f..16035f8 100644 --- a/framework/platform-dx/gamepad.cpp +++ b/framework/platform-dx/gamepad.cpp @@ -1,10 +1,9 @@ -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" #include "xna/input/gamepad.hpp" namespace xna { void GamePad::Initialize() { - impl = uNew(); - impl->_dxGamePad = uNew(); + impl = unew(); } GamePadState GamePad::GetState(PlayerIndex index) { diff --git a/framework/platform-dx/gdevicemanager.cpp b/framework/platform-dx/gdevicemanager.cpp index 489fe75..551e724 100644 --- a/framework/platform-dx/gdevicemanager.cpp +++ b/framework/platform-dx/gdevicemanager.cpp @@ -1,7 +1,7 @@ #include "xna/game/gdevicemanager.hpp" #include "xna/graphics/presentparams.hpp" #include "xna/graphics/swapchain.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { GraphicsDeviceManager::GraphicsDeviceManager(sptr const& game) : _game(game) @@ -83,12 +83,11 @@ namespace xna { } bool initDevice(GraphicsDeviceInformation& info, Game& game, sptr& device) - { - auto& window = info.Window; - device = New(info); + { + device = snew(info); - if (!device->Initialize(*window)) { - MessageBox(window->impl->WindowHandle(), "Falha na inicialização do dispositivo gráfico", "XN65", MB_OK); + if (!device->Initialize()) { + MessageBox(info.Window->impl->WindowHandle(), "Falha na inicialização do dispositivo gráfico", "XN65", MB_OK); device = nullptr; return false; } diff --git a/framework/platform-dx/init.cpp b/framework/platform-dx/init.cpp index a7b9c35..0351eba 100644 --- a/framework/platform-dx/init.cpp +++ b/framework/platform-dx/init.cpp @@ -4,7 +4,7 @@ #include "xna/content/readers/audio.hpp" #include "xna/content/typereadermanager.hpp" #include "xna/content/readers/default.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { void Platform::Init() { diff --git a/framework/platform-dx/keyboard.cpp b/framework/platform-dx/keyboard.cpp index c11a070..d373fe5 100644 --- a/framework/platform-dx/keyboard.cpp +++ b/framework/platform-dx/keyboard.cpp @@ -1,5 +1,5 @@ #include "xna/input/keyboard.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { KeyboardState Keyboard::GetState() { @@ -14,8 +14,7 @@ namespace xna { } void Keyboard::Initialize() { - impl = uNew(); - impl->_dxKeyboard = uNew(); + impl = unew(); } bool Keyboard::IsConnected() { diff --git a/framework/platform-dx/mouse.cpp b/framework/platform-dx/mouse.cpp index 310f30e..87614c8 100644 --- a/framework/platform-dx/mouse.cpp +++ b/framework/platform-dx/mouse.cpp @@ -1,5 +1,5 @@ #include "xna/input/mouse.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { MouseState Mouse::GetState() { @@ -49,7 +49,6 @@ namespace xna { } void Mouse::Initialize() { - impl = uNew(); - impl->_dxMouse = uNew(); + impl = unew(); } } \ No newline at end of file diff --git a/framework/platform-dx/rasterizerstate.cpp b/framework/platform-dx/rasterizerstate.cpp index aec633c..c9634a8 100644 --- a/framework/platform-dx/rasterizerstate.cpp +++ b/framework/platform-dx/rasterizerstate.cpp @@ -1,25 +1,24 @@ #include "xna/graphics/rasterizerstate.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { - RasterizerState::RasterizerState() : GraphicsResource(nullptr){ - impl = unew(); - } + RasterizerState::RasterizerState() : RasterizerState(nullptr){} RasterizerState::RasterizerState(sptr const& device) : GraphicsResource(device) { impl = unew(); + impl->dxDescription.CullMode = D3D11_CULL_MODE::D3D11_CULL_BACK; + impl->dxDescription.FillMode = D3D11_FILL_MODE::D3D11_FILL_SOLID; + impl->dxDescription.MultisampleEnable = true; + impl->dxDescription.DepthBias = 0; + impl->dxDescription.SlopeScaledDepthBias = 0; + impl->dxDescription.ScissorEnable = false; } - - RasterizerState::~RasterizerState() { - impl = nullptr; - } - - bool RasterizerState::Initialize(xna_error_ptr_arg) + + bool RasterizerState::Initialize() { if (!impl || !m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->dxRasterizerState) { @@ -32,23 +31,20 @@ namespace xna { &impl->dxRasterizerState); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; } - bool RasterizerState::Apply(xna_error_ptr_arg) + bool RasterizerState::Apply() { if (!impl || !m_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (!impl->dxRasterizerState) { - xna_error_apply(err, XnaErrorCode::UNINTIALIZED_RESOURCE); - return false; + Exception::Throw(ExMessage::UnintializedComponent); } m_device->impl->_context->RSSetState(impl->dxRasterizerState); @@ -56,9 +52,41 @@ namespace xna { return true; } + bool RasterizerState::ScissorTestEnable() const { + return impl->dxDescription.ScissorEnable; + } + + void RasterizerState::ScissorTestEnable(bool value) { + impl->dxDescription.ScissorEnable = value; + } + + bool RasterizerState::MultiSampleAntiAlias() const { + return impl->dxDescription.MultisampleEnable; + } + + void RasterizerState::MultiSampleAntiAlias(bool value) { + impl->dxDescription.MultisampleEnable = value; + } + + float RasterizerState::DepthBias() const { + return impl->dxDescription.DepthBias; + } + + void RasterizerState::DepthBias(float value) { + impl->dxDescription.DepthBias = value; + } + + float RasterizerState::SlopeScaleDepthBias() const { + return impl->dxDescription.SlopeScaledDepthBias; + } + + void RasterizerState::SlopeScaleDepthBias(float value) { + impl->dxDescription.SlopeScaledDepthBias = value; + } + uptr RasterizerState::CullNone() { - auto raster = uNew(); + auto raster = unew(); raster->impl->dxDescription.FillMode = D3D11_FILL_SOLID; raster->impl->dxDescription.CullMode = D3D11_CULL_MODE::D3D11_CULL_NONE; raster->impl->dxDescription.DepthClipEnable = true; @@ -67,7 +95,7 @@ namespace xna { uptr RasterizerState::CullClockwise() { - auto raster = uNew(); + auto raster = unew(); raster->impl->dxDescription.FillMode = D3D11_FILL_SOLID; raster->impl->dxDescription.CullMode = D3D11_CULL_MODE::D3D11_CULL_FRONT; raster->impl->dxDescription.DepthClipEnable = true; @@ -76,7 +104,7 @@ namespace xna { uptr RasterizerState::CullCounterClockwise() { - auto raster = uNew(); + auto raster = unew(); raster->impl->dxDescription.FillMode = D3D11_FILL_SOLID; raster->impl->dxDescription.CullMode = D3D11_CULL_MODE::D3D11_CULL_BACK; raster->impl->dxDescription.DepthClipEnable = true; diff --git a/framework/platform-dx/rendertarget.cpp b/framework/platform-dx/rendertarget.cpp index 12fe883..2f0bd14 100644 --- a/framework/platform-dx/rendertarget.cpp +++ b/framework/platform-dx/rendertarget.cpp @@ -1,4 +1,4 @@ -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { RenderTarget2D::RenderTarget2D() : Texture2D() { @@ -13,10 +13,9 @@ namespace xna { render_impl = nullptr; } - bool RenderTarget2D::Initialize(xna_error_ptr_arg) { + bool RenderTarget2D::Initialize() { if (!impl || !m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->dxTexture2D) { @@ -32,19 +31,20 @@ namespace xna { const auto hr = dxdevice->CreateRenderTargetView(impl->dxTexture2D, NULL, &render_impl->_renderTargetView); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; } - bool RenderTarget2D::Apply(xna_error_ptr_arg) { + bool RenderTarget2D::Apply() { if (!m_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::ApplyComponent); } + if(!render_impl->_renderTargetView) + Exception::Throw(ExMessage::UnintializedComponent); + auto& context = m_device->impl->_context; context->OMSetRenderTargets(1, &render_impl->_renderTargetView, nullptr); return true; diff --git a/framework/platform-dx/samplerstate.cpp b/framework/platform-dx/samplerstate.cpp index 6d61ddc..2a8e8d1 100644 --- a/framework/platform-dx/samplerstate.cpp +++ b/framework/platform-dx/samplerstate.cpp @@ -1,26 +1,18 @@ #include "xna/graphics/samplerstate.hpp" #include "xna/graphics/samplerstate.hpp" -#include "xna/platform-dx/implementations.hpp" -#include "xna/platform-dx/helpers.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { - SamplerState::SamplerState() : GraphicsResource(nullptr) { - impl = unew(); - } + SamplerState::SamplerState() : SamplerState(nullptr){} SamplerState::SamplerState(sptr const& device) : GraphicsResource(device) { impl = unew(); } - SamplerState::~SamplerState() { - impl = nullptr; - } - - bool SamplerState::Initialize(xna_error_ptr_arg) + bool SamplerState::Initialize() { if (!impl || !m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->_samplerState) { @@ -33,23 +25,20 @@ namespace xna { &impl->_samplerState); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; } - bool SamplerState::Apply(xna_error_ptr_arg) + bool SamplerState::Apply() { if (!impl || !m_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InvalidOperation); } if (!impl->_samplerState) { - xna_error_apply(err, XnaErrorCode::UNINTIALIZED_RESOURCE); - return false; + Exception::Throw(ExMessage::UnintializedComponent); } m_device->impl->_context->PSSetSamplers(0, 1, &impl->_samplerState); @@ -161,15 +150,15 @@ namespace xna { impl->_description.ComparisonFunc = static_cast(static_cast(value) + 1); } - void SamplerState::MipLODBias(float value) { + void SamplerState::MipMapLevelOfDetailBias(float value) { impl->_description.MipLODBias = value; } - void SamplerState::MinLOD(float value) { + void SamplerState::MinMipLevel(float value) { impl->_description.MinLOD = value; } - void SamplerState::MaxLOD(float value) { + void SamplerState::MaxMipLevel (float value) { impl->_description.MaxLOD = value; } @@ -225,15 +214,15 @@ namespace xna { return static_cast(impl->_description.ComparisonFunc - 1); } - float SamplerState::MipLODBias() const { + float SamplerState::MipMapLevelOfDetailBias() const { return impl->_description.MipLODBias; } - float SamplerState::MinLOD() const { + float SamplerState::MinMipLevel() const { return impl->_description.MinLOD; } - float SamplerState::MaxLOD() const { + float SamplerState::MaxMipLevel() const { return impl->_description.MaxLOD; } diff --git a/framework/platform-dx/shader.cpp b/framework/platform-dx/shader.cpp index b243fe8..8ceda6b 100644 --- a/framework/platform-dx/shader.cpp +++ b/framework/platform-dx/shader.cpp @@ -1,5 +1,5 @@ #include "xna/graphics/buffer.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" #include "xna/graphics/shader.hpp" namespace xna { @@ -61,11 +61,10 @@ namespace xna { impl = nullptr; } - bool VertexShader::Initialize(DataBuffer& buffer, xna_error_ptr_arg) + bool VertexShader::Initialize(DataBuffer& buffer) { if (!impl || !m_device || !m_device->impl->_device || !buffer.impl->_blob) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->_vertexShader) { @@ -80,18 +79,16 @@ namespace xna { &impl->_vertexShader); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; } - bool PixelShader::Initialize(DataBuffer& buffer, xna_error_ptr_arg) + bool PixelShader::Initialize(DataBuffer& buffer) { if (!impl || !m_device || !m_device->impl->_device || !buffer.impl->_blob) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } if (impl->_pixelShader) { @@ -106,8 +103,7 @@ namespace xna { &impl->_pixelShader); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; diff --git a/framework/platform-dx/soundeffect.cpp b/framework/platform-dx/soundeffect.cpp index 2c83731..da984aa 100644 --- a/framework/platform-dx/soundeffect.cpp +++ b/framework/platform-dx/soundeffect.cpp @@ -1,4 +1,4 @@ -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" #include "xna/csharp/stream.hpp" using DxSoundEffect = DirectX::SoundEffect; diff --git a/framework/platform-dx/sprite.cpp b/framework/platform-dx/sprite.cpp index c6657a0..95276ab 100644 --- a/framework/platform-dx/sprite.cpp +++ b/framework/platform-dx/sprite.cpp @@ -6,8 +6,7 @@ #include "xna/graphics/viewport.hpp" #include "xna/graphics/blendstate.hpp" #include "xna/graphics/depthstencilstate.hpp" -#include "xna/platform-dx/implementations.hpp" -#include +#include "xna/platform-dx/dx.hpp" using DxSpriteBatch = DirectX::SpriteBatch; using DxSpriteSortMode = DirectX::SpriteSortMode; @@ -29,30 +28,39 @@ namespace xna { Int lineSpacing, float spacing, std::vector const& kerning, - std::optional defaultCharacter) : - textureValue(texture), glyphData(glyphs), croppingData(cropping), - characterMap(charMap), lineSpacing(lineSpacing), spacing(spacing), - kerning(kerning), defaultCharacter(defaultCharacter) + std::optional const& defaultCharacter) { - if (!texture) + if (!texture || !texture->impl->dxShaderResource) throw std::invalid_argument("SpriteFont: texture is null."); + if(cropping.size() != glyphs.size() || charMap.size() != glyphs.size() || (!kerning.empty() && kerning.size() != glyphs.size())) + throw std::invalid_argument("SpriteFont: cropping, charmap and kerning (if not empty) must all be the same size."); + std::vector dxGlyps(glyphs.size()); for (size_t i = 0; i < dxGlyps.size(); ++i) { DxGlyph g; - g.Subrect.left = glyphs[i].Left(); - g.Subrect.right = glyphs[i].Right(); - g.Subrect.top = glyphs[i].Top(); - g.Subrect.bottom = glyphs[i].Bottom(); + g.Subrect.left = static_cast(glyphs[i].Left()); + g.Subrect.right = static_cast(glyphs[i].Right()); + g.Subrect.top = static_cast(glyphs[i].Top()); + g.Subrect.bottom = static_cast(glyphs[i].Bottom()); g.Character = static_cast(charMap[i]); - g.XOffset = kerning[i].X; - g.YOffset = cropping[i].Y; - g.XAdvance = kerning[i].Z; + + if (!kerning.empty()) { + g.XOffset = kerning[i].X; + g.YOffset = static_cast(cropping[i].Y); + g.XAdvance = kerning[i].Z + spacing; + } + else { + g.XOffset = 0; + g.YOffset = 0; + g.XAdvance = spacing; + } + dxGlyps[i] = g; } - impl = uNew(); + impl = unew(); impl->_dxSpriteFont = unew( //ID3D11ShaderResourceView* texture texture->impl->dxShaderResource, @@ -68,14 +76,7 @@ namespace xna { const auto defChar = static_cast(defaultCharacter.value()); impl->_dxSpriteFont->SetDefaultCharacter(defChar); } - else { - impl->_dxSpriteFont->SetDefaultCharacter(charMap[0]); - } - } - - SpriteFont::~SpriteFont() { - impl = nullptr; - } + } Vector2 SpriteFont::MeasureString(String const& text, bool ignoreWhiteSpace) { @@ -103,22 +104,37 @@ namespace xna { return vec2; } - static constexpr void ConvertSpriteSort(SpriteSortMode value, DirectX::SpriteSortMode& target) { - target = static_cast(static_cast(value)); + Char SpriteFont::DefaultCharacter() const { + const auto defChar = impl->_dxSpriteFont->GetDefaultCharacter(); + return static_cast(defChar); + } + + void SpriteFont::DefaultCharacter(Char value) { + const auto defChar = static_cast(value); + impl->_dxSpriteFont->SetDefaultCharacter(defChar); } - SpriteBatch::SpriteBatch(GraphicsDevice& device) { - if (!device.impl->_context) + Int SpriteFont::LineSpacing() const { + const auto space = impl->_dxSpriteFont->GetLineSpacing(); + return static_cast(space); + } + + void SpriteFont::LineSpacing(Int value) { + impl->_dxSpriteFont->SetLineSpacing(static_cast(value)); + } + + SpriteBatch::SpriteBatch(sptr const& device) : GraphicsResource(device) { + if (!device->impl->_context) return; - implementation = uNew(); - implementation->_dxspriteBatch = New(device.impl->_context); + implementation = unew(); + implementation->_dxspriteBatch = snew( + //ID3D11DeviceContext* deviceContext + device->impl->_context + ); - Viewport(device.Viewport()); - } - - SpriteBatch::~SpriteBatch() { - } + Viewport(device->Viewport()); + } void SpriteBatch::Begin(SpriteSortMode sortMode, BlendState* blendState, SamplerState* samplerState, DepthStencilState* depthStencil, RasterizerState* rasterizerState, Matrix const& transformMatrix) { @@ -126,7 +142,7 @@ namespace xna { return; DxSpriteSortMode sort; - ConvertSpriteSort(sortMode, sort); + DxHelpers::SpriteSortToDx(sortMode, sort); const auto& t = transformMatrix; DxMatrix matrix = DxMatrix( @@ -172,10 +188,10 @@ namespace xna { ); } - void SpriteBatch::Draw(Texture2D& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color) { + void SpriteBatch::Draw(Texture2D& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color) { if (!implementation->_dxspriteBatch) return; - + if (!texture.impl->dxShaderResource) return; @@ -185,7 +201,7 @@ namespace xna { RECT _sourceRect{}; - if (sourceRectangle) { + if (sourceRectangle.has_value()) { _sourceRect.top = sourceRectangle->Y; _sourceRect.left = sourceRectangle->X; _sourceRect.right = sourceRectangle->X + sourceRectangle->Width; @@ -199,7 +215,7 @@ namespace xna { _color); } - void SpriteBatch::Draw(Texture2D& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color, float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth) { + void SpriteBatch::Draw(Texture2D& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color, float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth) { if (!implementation->_dxspriteBatch) return; @@ -213,7 +229,7 @@ namespace xna { RECT _sourceRect{}; - if (sourceRectangle) { + if (sourceRectangle.has_value()) { _sourceRect.top = sourceRectangle->Y; _sourceRect.left = sourceRectangle->X; _sourceRect.right = sourceRectangle->X + sourceRectangle->Width; @@ -234,7 +250,7 @@ namespace xna { layerDepth); } - void SpriteBatch::Draw(Texture2D& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color, float rotation, Vector2 const& origin, Vector2 const& scale, SpriteEffects effects, float layerDepth) { + void SpriteBatch::Draw(Texture2D& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color, float rotation, Vector2 const& origin, Vector2 const& scale, SpriteEffects effects, float layerDepth) { if (!implementation->_dxspriteBatch) return; @@ -248,7 +264,7 @@ namespace xna { RECT _sourceRect{}; - if (sourceRectangle) { + if (sourceRectangle.has_value()) { _sourceRect.top = sourceRectangle->Y; _sourceRect.left = sourceRectangle->X; _sourceRect.right = sourceRectangle->X + sourceRectangle->Width; @@ -289,7 +305,7 @@ namespace xna { implementation->_dxspriteBatch->Draw(texture.impl->dxShaderResource, _destinationRect, _color); } - void SpriteBatch::Draw(Texture2D& texture, Rectangle const& destinationRectangle, Rectangle const* sourceRectangle, Color const& color) { + void SpriteBatch::Draw(Texture2D& texture, Rectangle const& destinationRectangle, std::optional const& sourceRectangle, Color const& color) { if (!implementation->_dxspriteBatch) return; @@ -307,7 +323,7 @@ namespace xna { RECT _sourceRect{}; - if (sourceRectangle) { + if (sourceRectangle.has_value()) { _sourceRect.top = sourceRectangle->Y; _sourceRect.left = sourceRectangle->X; _sourceRect.right = sourceRectangle->X + sourceRectangle->Width; @@ -317,7 +333,7 @@ namespace xna { implementation->_dxspriteBatch->Draw(texture.impl->dxShaderResource, _destinationRect, sourceRectangle ? &_sourceRect : nullptr, _color); } - void SpriteBatch::Draw(Texture2D& texture, Rectangle const& destinationRectangle, Rectangle const* sourceRectangle, Color const& color, float rotation, Vector2 const& origin, SpriteEffects effects, float layerDepth) { + void SpriteBatch::Draw(Texture2D& texture, Rectangle const& destinationRectangle, std::optional const& sourceRectangle, Color const& color, float rotation, Vector2 const& origin, SpriteEffects effects, float layerDepth) { if (!implementation->_dxspriteBatch) return; @@ -335,7 +351,7 @@ namespace xna { RECT _sourceRect{}; - if (sourceRectangle) { + if (sourceRectangle.has_value()) { _sourceRect.top = sourceRectangle->Y; _sourceRect.left = sourceRectangle->X; _sourceRect.right = sourceRectangle->X + sourceRectangle->Width; diff --git a/framework/platform-dx/swapchain.cpp b/framework/platform-dx/swapchain.cpp index 73586c5..82469a1 100644 --- a/framework/platform-dx/swapchain.cpp +++ b/framework/platform-dx/swapchain.cpp @@ -1,7 +1,6 @@ -#include "xna/platform-dx/helpers.hpp" #include "xna/graphics/adapter.hpp" #include "xna/graphics/swapchain.hpp" -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" #include "xna/graphics/device.hpp" namespace xna { @@ -51,17 +50,16 @@ namespace xna { return true; } - bool SwapChain::Initialize(xna_error_ptr_arg) { + bool SwapChain::Initialize() { if (!impl || !m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } const auto parameters = m_device->impl->_presentationParameters; impl->dxDescription.Width = static_cast(parameters->BackBufferWidth); impl->dxDescription.Height = static_cast(parameters->BackBufferHeight); - impl->dxDescription.Format = DxHelpers::ConvertSurfaceToDXGIFORMAT(parameters->BackBufferFormat); + impl->dxDescription.Format = DxHelpers::SurfaceFormatToDx(parameters->BackBufferFormat); impl->dxDescription.SampleDesc.Count = 1; impl->dxDescription.SampleDesc.Quality = 0; impl->dxDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; diff --git a/framework/platform-dx/texture.cpp b/framework/platform-dx/texture.cpp index f2960fd..d4b9c29 100644 --- a/framework/platform-dx/texture.cpp +++ b/framework/platform-dx/texture.cpp @@ -1,15 +1,14 @@ -#include "xna/platform-dx/implementations.hpp" -#include "xna/platform-dx/helpers.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { Texture2D::~Texture2D() { impl = nullptr; } - sptr Texture2D::FromStream(GraphicsDevice& device, String const& fileName, xna_error_ptr_arg) + sptr Texture2D::FromStream(GraphicsDevice& device, String const& fileName) { auto _this = device.shared_from_this(); - auto texture2d = New(_this); + auto texture2d = snew(_this); ID3D11Resource* resource = nullptr; auto wstr = XnaHelper::ToWString(fileName); @@ -22,9 +21,7 @@ namespace xna { 0U); if (FAILED(result)) - { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - + { if (resource) { resource->Release(); resource = nullptr; @@ -36,8 +33,6 @@ namespace xna { result = resource->QueryInterface(IID_ID3D11Texture2D, (void**)&texture2d->impl->dxTexture2D); if (FAILED(result)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - if (resource) { resource->Release(); resource = nullptr; @@ -56,31 +51,23 @@ namespace xna { return texture2d; } - bool Texture2D::Initialize(xna_error_ptr_arg) + bool Texture2D::Initialize() { - if (impl->dxTexture2D) { - xna_error_apply(err, XnaErrorCode::WARNING_INITIALIZED_RESOURCE); - return false; - } - if (!m_device || !m_device->impl->_device) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; + Exception::Throw(ExMessage::InitializeComponent); } auto hr = m_device->impl->_device->CreateTexture2D(&impl->dxDescription, nullptr, &impl->dxTexture2D); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } ID3D11Resource* resource = nullptr; hr = impl->dxTexture2D->QueryInterface(IID_ID3D11Resource, (void**)&resource); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::InvalidOperation); } hr = m_device->impl->_device->CreateShaderResourceView(resource, &impl->dxShaderDescription, &impl->dxShaderResource); @@ -91,8 +78,7 @@ namespace xna { } if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; + Exception::Throw(ExMessage::CreateComponent); } return true; @@ -136,17 +122,16 @@ namespace xna { impl->dxDescription.Width = static_cast(width); impl->dxDescription.Height = static_cast(height); impl->dxDescription.MipLevels = static_cast(mipMap); - impl->dxDescription.Format = DxHelpers::ConvertSurfaceToDXGIFORMAT(format); + impl->dxDescription.Format = DxHelpers::SurfaceFormatToDx(format); } - HRESULT internalSetData(Texture2D::PlatformImplementation& impl, GraphicsDevice& device, UINT const* data, xna_error_ptr_arg) + HRESULT internalSetData(Texture2D::PlatformImplementation& impl, GraphicsDevice& device, UINT const* data) { if (!impl.dxTexture2D) { auto hr = device.impl->_device->CreateTexture2D(&impl.dxDescription, nullptr, &impl.dxTexture2D); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return hr; + Exception::Throw(ExMessage::CreateComponent); } } @@ -154,8 +139,7 @@ namespace xna { auto hr = impl.dxTexture2D->QueryInterface(IID_ID3D11Resource, (void**)&resource); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return hr; + Exception::Throw(ExMessage::InvalidOperation); } constexpr int R8G8B8A8U_BYTE_SIZE = 4; @@ -175,8 +159,7 @@ namespace xna { } if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return hr; + Exception::Throw(ExMessage::CreateComponent); } impl.dxTexture2D->GetDesc(&impl.dxDescription); @@ -184,21 +167,19 @@ namespace xna { return NO_ERROR; } - void Texture2D::SetData(std::vector const& data, size_t startIndex, size_t elementCount, xna_error_ptr_arg) + void Texture2D::SetData(std::vector const& data, size_t startIndex, size_t elementCount) { if (!impl || !m_device || !m_device->impl->_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return; + Exception::Throw(ExMessage::InvalidOperation); } - internalSetData(*impl, *m_device, data.data(), err); + internalSetData(*impl, *m_device, data.data()); } - void Texture2D::SetData(std::vector const& data, size_t startIndex, size_t elementCount, xna_error_ptr_arg) + void Texture2D::SetData(std::vector const& data, size_t startIndex, size_t elementCount) { if (!m_device || !m_device->impl->_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return; + Exception::Throw(ExMessage::InvalidOperation); } std::vector finalData(elementCount / 4); @@ -213,14 +194,13 @@ namespace xna { ++fIndex; } - internalSetData(*impl, *m_device, finalData.data(), err); + internalSetData(*impl, *m_device, finalData.data()); } - void Texture2D::SetData(Int level, Rectangle* rect, std::vector const& data, size_t startIndex, size_t elementCount, xna_error_ptr_arg) + void Texture2D::SetData(Int level, Rectangle* rect, std::vector const& data, size_t startIndex, size_t elementCount) { if (!m_device || !m_device->impl->_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return; + Exception::Throw(ExMessage::InvalidOperation); } std::vector finalData(elementCount / 4); @@ -239,8 +219,7 @@ namespace xna { auto hr = m_device->impl->_device->CreateTexture2D(&impl->dxDescription, nullptr, &impl->dxTexture2D); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return; + Exception::Throw(ExMessage::CreateComponent); } } @@ -248,8 +227,7 @@ namespace xna { auto hr = impl->dxTexture2D->QueryInterface(IID_ID3D11Resource, (void**)&resource); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return; + Exception::Throw(ExMessage::InvalidOperation); } D3D11_BOX box{}; @@ -281,18 +259,16 @@ namespace xna { } if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return; + Exception::Throw(ExMessage::CreateComponent); } impl->dxTexture2D->GetDesc(&impl->dxDescription); } - void Texture2D::SetData(std::vector const& data, size_t startIndex, size_t elementCount, xna_error_ptr_arg) + void Texture2D::SetData(std::vector const& data, size_t startIndex, size_t elementCount) { if (!m_device || !m_device->impl->_device || !m_device->impl->_context) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return; + Exception::Throw(ExMessage::InvalidOperation); } std::vector finalData(elementCount); @@ -303,13 +279,13 @@ namespace xna { ++finalDataIndex; } - internalSetData(*impl, *m_device, finalData.data(), err); + internalSetData(*impl, *m_device, finalData.data()); } - sptr Texture2D::FromMemory(GraphicsDevice& device, std::vector const& data, xna_error_ptr_arg) + sptr Texture2D::FromMemory(GraphicsDevice& device, std::vector const& data) { auto _this = device.shared_from_this(); - auto texture2d = New(_this); + auto texture2d = snew(_this); ID3D11Resource* resource = nullptr; auto hr = DirectX::CreateWICTextureFromMemory( @@ -322,8 +298,6 @@ namespace xna { if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - if (resource) { resource->Release(); resource = nullptr; @@ -335,8 +309,6 @@ namespace xna { hr = resource->QueryInterface(IID_ID3D11Texture2D, (void**)&texture2d->impl->dxTexture2D); if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - if (resource) { resource->Release(); resource = nullptr; diff --git a/framework/platform-dx/window.cpp b/framework/platform-dx/window.cpp index 66cdc97..3e734f6 100644 --- a/framework/platform-dx/window.cpp +++ b/framework/platform-dx/window.cpp @@ -1,4 +1,4 @@ -#include "xna/platform-dx/implementations.hpp" +#include "xna/platform-dx/dx.hpp" namespace xna { GameWindow::GameWindow() { diff --git a/inc/effects11/Effects11.lib b/inc/effects11/Effects11.lib new file mode 100644 index 0000000..030886a Binary files /dev/null and b/inc/effects11/Effects11.lib differ diff --git a/inc/effects11/d3dx11effect.h b/inc/effects11/d3dx11effect.h new file mode 100644 index 0000000..6207b81 --- /dev/null +++ b/inc/effects11/d3dx11effect.h @@ -0,0 +1,1212 @@ +//-------------------------------------------------------------------------------------- +// File: D3DX11Effect.h +// +// Direct3D 11 Effect Types & APIs Header +// +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/p/?LinkId=271568 +//-------------------------------------------------------------------------------------- + +#pragma once + +#define D3DX11_EFFECTS_VERSION 1129 + +#if defined(_XBOX_ONE) && defined(_TITLE) +#include +#define NO_D3D11_DEBUG_NAME +#else +#include +#include +#endif + +#pragma comment( lib, "d3dcompiler.lib" ) +#pragma comment( lib, "dxguid.lib" ) + +#include + +////////////////////////////////////////////////////////////////////////////// +// File contents: +// +// 1) Stateblock enums, structs, interfaces, flat APIs +// 2) Effect enums, structs, interfaces, flat APIs +////////////////////////////////////////////////////////////////////////////// + +#ifndef D3DX11_BYTES_FROM_BITS +#define D3DX11_BYTES_FROM_BITS(x) (((x) + 7) / 8) +#endif // D3DX11_BYTES_FROM_BITS + +#ifndef D3DERR_INVALIDCALL +#define D3DERR_INVALIDCALL MAKE_HRESULT( 1, 0x876, 2156 ) +#endif + +struct D3DX11_STATE_BLOCK_MASK +{ + uint8_t VS; + uint8_t VSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + uint8_t VSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + uint8_t VSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + uint8_t VSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + + uint8_t HS; + uint8_t HSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + uint8_t HSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + uint8_t HSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + uint8_t HSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + + uint8_t DS; + uint8_t DSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + uint8_t DSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + uint8_t DSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + uint8_t DSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + + uint8_t GS; + uint8_t GSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + uint8_t GSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + uint8_t GSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + uint8_t GSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + + uint8_t PS; + uint8_t PSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + uint8_t PSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + uint8_t PSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + uint8_t PSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + uint8_t PSUnorderedAccessViews; + + uint8_t CS; + uint8_t CSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + uint8_t CSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + uint8_t CSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + uint8_t CSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + uint8_t CSUnorderedAccessViews; + + uint8_t IAVertexBuffers[D3DX11_BYTES_FROM_BITS(D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT)]; + uint8_t IAIndexBuffer; + uint8_t IAInputLayout; + uint8_t IAPrimitiveTopology; + + uint8_t OMRenderTargets; + uint8_t OMDepthStencilState; + uint8_t OMBlendState; + + uint8_t RSViewports; + uint8_t RSScissorRects; + uint8_t RSRasterizerState; + + uint8_t SOBuffers; + + uint8_t Predication; +}; + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT flags: +// ------------------------------------- +// +// These flags are passed in when creating an effect, and affect +// the runtime effect behavior: +// +// (Currently none) +// +// +// These flags are set by the effect runtime: +// +// D3DX11_EFFECT_OPTIMIZED +// This effect has been optimized. Reflection functions that rely on +// names/semantics/strings should fail. This is set when Optimize() is +// called, but CEffect::IsOptimized() should be used to test for this. +// +// D3DX11_EFFECT_CLONE +// This effect is a clone of another effect. Single CBs will never be +// updated when internal variable values are changed. +// This flag is not set when the D3DX11_EFFECT_CLONE_FORCE_NONSINGLE flag +// is used in cloning. +// +//---------------------------------------------------------------------------- + +#define D3DX11_EFFECT_OPTIMIZED (1 << 21) +#define D3DX11_EFFECT_CLONE (1 << 22) + +// Mask of valid D3DCOMPILE_EFFECT flags for D3DX11CreateEffect* +#define D3DX11_EFFECT_RUNTIME_VALID_FLAGS (0) + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_VARIABLE flags: +// ---------------------------- +// +// These flags describe an effect variable (global or annotation), +// and are returned in D3DX11_EFFECT_VARIABLE_DESC::Flags. +// +// D3DX11_EFFECT_VARIABLE_ANNOTATION +// Indicates that this is an annotation on a technique, pass, or global +// variable. Otherwise, this is a global variable. Annotations cannot +// be shared. +// +// D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT +// Indicates that the variable has been explicitly bound using the +// register keyword. +//---------------------------------------------------------------------------- + +#define D3DX11_EFFECT_VARIABLE_ANNOTATION (1 << 1) +#define D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT (1 << 2) + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_CLONE flags: +// ---------------------------- +// +// These flags modify the effect cloning process and are passed into Clone. +// +// D3DX11_EFFECT_CLONE_FORCE_NONSINGLE +// Ignore all "single" qualifiers on cbuffers. All cbuffers will have their +// own ID3D11Buffer's created in the cloned effect. +//---------------------------------------------------------------------------- + +#define D3DX11_EFFECT_CLONE_FORCE_NONSINGLE (1 << 0) + + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectType ////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_TYPE_DESC: +// +// Retrieved by ID3DX11EffectType::GetDesc() +//---------------------------------------------------------------------------- + +struct D3DX11_EFFECT_TYPE_DESC +{ + LPCSTR TypeName; // Name of the type + // (e.g. "float4" or "MyStruct") + + D3D_SHADER_VARIABLE_CLASS Class; // (e.g. scalar, vector, object, etc.) + D3D_SHADER_VARIABLE_TYPE Type; // (e.g. float, texture, vertexshader, etc.) + + uint32_t Elements; // Number of elements in this type + // (0 if not an array) + uint32_t Members; // Number of members + // (0 if not a structure) + uint32_t Rows; // Number of rows in this type + // (0 if not a numeric primitive) + uint32_t Columns; // Number of columns in this type + // (0 if not a numeric primitive) + + uint32_t PackedSize; // Number of bytes required to represent + // this data type, when tightly packed + uint32_t UnpackedSize; // Number of bytes occupied by this data + // type, when laid out in a constant buffer + uint32_t Stride; // Number of bytes to seek between elements, + // when laid out in a constant buffer +}; + +typedef interface ID3DX11EffectType ID3DX11EffectType; +typedef interface ID3DX11EffectType *LPD3D11EFFECTTYPE; + +// {4250D721-D5E5-491F-B62B-587C43186285} +DEFINE_GUID(IID_ID3DX11EffectType, + 0x4250d721, 0xd5e5, 0x491f, 0xb6, 0x2b, 0x58, 0x7c, 0x43, 0x18, 0x62, 0x85); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectType + +DECLARE_INTERFACE_(ID3DX11EffectType, IUnknown) +{ + // IUnknown + + // ID3DX11EffectType + STDMETHOD_(bool, IsValid)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_EFFECT_TYPE_DESC *pDesc) PURE; + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(THIS_ _In_z_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(THIS_ _In_z_ LPCSTR Semantic) PURE; + STDMETHOD_(LPCSTR, GetMemberName)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(LPCSTR, GetMemberSemantic)(THIS_ _In_ uint32_t Index) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectVariable ////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_VARIABLE_DESC: +// +// Retrieved by ID3DX11EffectVariable::GetDesc() +//---------------------------------------------------------------------------- + +struct D3DX11_EFFECT_VARIABLE_DESC +{ + LPCSTR Name; // Name of this variable, annotation, + // or structure member + LPCSTR Semantic; // Semantic string of this variable + // or structure member (nullptr for + // annotations or if not present) + + uint32_t Flags; // D3DX11_EFFECT_VARIABLE_* flags + uint32_t Annotations; // Number of annotations on this variable + // (always 0 for annotations) + + uint32_t BufferOffset; // Offset into containing cbuffer or tbuffer + // (always 0 for annotations or variables + // not in constant buffers) + + uint32_t ExplicitBindPoint; // Used if the variable has been explicitly bound + // using the register keyword. Check Flags for + // D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT; +}; + +typedef interface ID3DX11EffectVariable ID3DX11EffectVariable; +typedef interface ID3DX11EffectVariable *LPD3D11EFFECTVARIABLE; + +// {036A777D-B56E-4B25-B313-CC3DDAB71873} +DEFINE_GUID(IID_ID3DX11EffectVariable, + 0x036a777d, 0xb56e, 0x4b25, 0xb3, 0x13, 0xcc, 0x3d, 0xda, 0xb7, 0x18, 0x73); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectVariable + +// Forward defines +typedef interface ID3DX11EffectScalarVariable ID3DX11EffectScalarVariable; +typedef interface ID3DX11EffectVectorVariable ID3DX11EffectVectorVariable; +typedef interface ID3DX11EffectMatrixVariable ID3DX11EffectMatrixVariable; +typedef interface ID3DX11EffectStringVariable ID3DX11EffectStringVariable; +typedef interface ID3DX11EffectClassInstanceVariable ID3DX11EffectClassInstanceVariable; +typedef interface ID3DX11EffectInterfaceVariable ID3DX11EffectInterfaceVariable; +typedef interface ID3DX11EffectShaderResourceVariable ID3DX11EffectShaderResourceVariable; +typedef interface ID3DX11EffectUnorderedAccessViewVariable ID3DX11EffectUnorderedAccessViewVariable; +typedef interface ID3DX11EffectRenderTargetViewVariable ID3DX11EffectRenderTargetViewVariable; +typedef interface ID3DX11EffectDepthStencilViewVariable ID3DX11EffectDepthStencilViewVariable; +typedef interface ID3DX11EffectConstantBuffer ID3DX11EffectConstantBuffer; +typedef interface ID3DX11EffectShaderVariable ID3DX11EffectShaderVariable; +typedef interface ID3DX11EffectBlendVariable ID3DX11EffectBlendVariable; +typedef interface ID3DX11EffectDepthStencilVariable ID3DX11EffectDepthStencilVariable; +typedef interface ID3DX11EffectRasterizerVariable ID3DX11EffectRasterizerVariable; +typedef interface ID3DX11EffectSamplerVariable ID3DX11EffectSamplerVariable; + +DECLARE_INTERFACE_(ID3DX11EffectVariable, IUnknown) +{ + // IUnknown + + // ID3DX11EffectVariable + STDMETHOD_(bool, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ _In_z_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ _In_z_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ _In_z_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ _In_ uint32_t Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ _In_reads_bytes_(ByteCount) const void *pData, _In_ uint32_t ByteOffset, _In_ uint32_t ByteCount) PURE; + STDMETHOD(GetRawValue)(THIS_ _Out_writes_bytes_(ByteCount) void *pData, _In_ uint32_t ByteOffset, _In_ uint32_t ByteCount) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectScalarVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectScalarVariable ID3DX11EffectScalarVariable; +typedef interface ID3DX11EffectScalarVariable *LPD3D11EFFECTSCALARVARIABLE; + +// {921EF2E5-A65D-4E92-9FC6-4E9CC09A4ADE} +DEFINE_GUID(IID_ID3DX11EffectScalarVariable, + 0x921ef2e5, 0xa65d, 0x4e92, 0x9f, 0xc6, 0x4e, 0x9c, 0xc0, 0x9a, 0x4a, 0xde); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectScalarVariable + +DECLARE_INTERFACE_(ID3DX11EffectScalarVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectScalarVariable + STDMETHOD(SetFloat)(THIS_ _In_ const float Value) PURE; + STDMETHOD(GetFloat)(THIS_ _Out_ float *pValue) PURE; + + STDMETHOD(SetFloatArray)(THIS_ _In_reads_(Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetFloatArray)(THIS_ _Out_writes_(Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + + STDMETHOD(SetInt)(THIS_ _In_ const int Value) PURE; + STDMETHOD(GetInt)(THIS_ _Out_ int *pValue) PURE; + + STDMETHOD(SetIntArray)(THIS_ _In_reads_(Count) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetIntArray)(THIS_ _Out_writes_(Count) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + + STDMETHOD(SetBool)(THIS_ _In_ const bool Value) PURE; + STDMETHOD(GetBool)(THIS_ _Out_ bool *pValue) PURE; + + STDMETHOD(SetBoolArray)(THIS_ _In_reads_(Count) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetBoolArray)(THIS_ _Out_writes_(Count) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectVectorVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectVectorVariable ID3DX11EffectVectorVariable; +typedef interface ID3DX11EffectVectorVariable *LPD3D11EFFECTVECTORVARIABLE; + +// {5E785D4A-D87B-48D8-B6E6-0F8CA7E7467A} +DEFINE_GUID(IID_ID3DX11EffectVectorVariable, + 0x5e785d4a, 0xd87b, 0x48d8, 0xb6, 0xe6, 0x0f, 0x8c, 0xa7, 0xe7, 0x46, 0x7a); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectVectorVariable + +DECLARE_INTERFACE_(ID3DX11EffectVectorVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectVectorVariable + STDMETHOD(SetBoolVector) (THIS_ _In_reads_(4) const bool *pData) PURE; + STDMETHOD(SetIntVector) (THIS_ _In_reads_(4) const int *pData) PURE; + STDMETHOD(SetFloatVector)(THIS_ _In_reads_(4) const float *pData) PURE; + + STDMETHOD(GetBoolVector) (THIS_ _Out_writes_(4) bool *pData) PURE; + STDMETHOD(GetIntVector) (THIS_ _Out_writes_(4) int *pData) PURE; + STDMETHOD(GetFloatVector)(THIS_ _Out_writes_(4) float *pData) PURE; + + STDMETHOD(SetBoolVectorArray) (THIS_ _In_reads_(Count*4) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(SetIntVectorArray) (THIS_ _In_reads_(Count*4) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(SetFloatVectorArray)(THIS_ _In_reads_(Count*4) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + + STDMETHOD(GetBoolVectorArray) (THIS_ _Out_writes_(Count*4) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetIntVectorArray) (THIS_ _Out_writes_(Count*4) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetFloatVectorArray)(THIS_ _Out_writes_(Count*4) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectMatrixVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectMatrixVariable ID3DX11EffectMatrixVariable; +typedef interface ID3DX11EffectMatrixVariable *LPD3D11EFFECTMATRIXVARIABLE; + +// {E1096CF4-C027-419A-8D86-D29173DC803E} +DEFINE_GUID(IID_ID3DX11EffectMatrixVariable, + 0xe1096cf4, 0xc027, 0x419a, 0x8d, 0x86, 0xd2, 0x91, 0x73, 0xdc, 0x80, 0x3e); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectMatrixVariable + +DECLARE_INTERFACE_(ID3DX11EffectMatrixVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectMatrixVariable + STDMETHOD(SetMatrix)(THIS_ _In_reads_(16) const float *pData) PURE; + STDMETHOD(GetMatrix)(THIS_ _Out_writes_(16) float *pData) PURE; + + STDMETHOD(SetMatrixArray)(THIS_ _In_reads_(Count*16) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetMatrixArray)(THIS_ _Out_writes_(Count*16) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + + STDMETHOD(SetMatrixPointerArray)(_In_reads_(Count*16) const float **ppData, uint32_t Offset, uint32_t Count) PURE; + STDMETHOD(GetMatrixPointerArray)(_Out_writes_(Count*16) float **ppData, uint32_t Offset, uint32_t Count) PURE; + + STDMETHOD(SetMatrixTranspose)(THIS_ _In_reads_(16) const float *pData) PURE; + STDMETHOD(GetMatrixTranspose)(THIS_ _Out_writes_(16) float *pData) PURE; + + STDMETHOD(SetMatrixTransposeArray)(THIS_ _In_reads_(Count*16) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetMatrixTransposeArray)(THIS_ _Out_writes_(Count*16) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + + STDMETHOD(SetMatrixTransposePointerArray)(_In_reads_(Count*16) const float **ppData, uint32_t Offset, uint32_t Count) PURE; + STDMETHOD(GetMatrixTransposePointerArray)(_Out_writes_(Count*16) float **ppData, uint32_t Offset, uint32_t Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectStringVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectStringVariable ID3DX11EffectStringVariable; +typedef interface ID3DX11EffectStringVariable *LPD3D11EFFECTSTRINGVARIABLE; + +// {F355C818-01BE-4653-A7CC-60FFFEDDC76D} +DEFINE_GUID(IID_ID3DX11EffectStringVariable, + 0xf355c818, 0x01be, 0x4653, 0xa7, 0xcc, 0x60, 0xff, 0xfe, 0xdd, 0xc7, 0x6d); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectStringVariable + +DECLARE_INTERFACE_(ID3DX11EffectStringVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectStringVariable + STDMETHOD(GetString)(THIS_ _Outptr_result_z_ LPCSTR *ppString) PURE; + STDMETHOD(GetStringArray)(THIS_ _Out_writes_(Count) LPCSTR *ppStrings, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectClassInstanceVariable //////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectClassInstanceVariable ID3DX11EffectClassInstanceVariable; +typedef interface ID3DX11EffectClassInstanceVariable *LPD3D11EFFECTCLASSINSTANCEVARIABLE; + +// {926A8053-2A39-4DB4-9BDE-CF649ADEBDC1} +DEFINE_GUID(IID_ID3DX11EffectClassInstanceVariable, + 0x926a8053, 0x2a39, 0x4db4, 0x9b, 0xde, 0xcf, 0x64, 0x9a, 0xde, 0xbd, 0xc1); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectClassInstanceVariable + +DECLARE_INTERFACE_(ID3DX11EffectClassInstanceVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectClassInstanceVariable + STDMETHOD(GetClassInstance)(_Outptr_ ID3D11ClassInstance** ppClassInstance) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectInterfaceVariable //////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectInterfaceVariable ID3DX11EffectInterfaceVariable; +typedef interface ID3DX11EffectInterfaceVariable *LPD3D11EFFECTINTERFACEVARIABLE; + +// {516C8CD8-1C80-40A4-B19B-0688792F11A5} +DEFINE_GUID(IID_ID3DX11EffectInterfaceVariable, + 0x516c8cd8, 0x1c80, 0x40a4, 0xb1, 0x9b, 0x06, 0x88, 0x79, 0x2f, 0x11, 0xa5); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectInterfaceVariable + +DECLARE_INTERFACE_(ID3DX11EffectInterfaceVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectInterfaceVariable + STDMETHOD(SetClassInstance)(_In_ ID3DX11EffectClassInstanceVariable *pEffectClassInstance) PURE; + STDMETHOD(GetClassInstance)(_Outptr_ ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectShaderResourceVariable //////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectShaderResourceVariable ID3DX11EffectShaderResourceVariable; +typedef interface ID3DX11EffectShaderResourceVariable *LPD3D11EFFECTSHADERRESOURCEVARIABLE; + +// {350DB233-BBE0-485C-9BFE-C0026B844F89} +DEFINE_GUID(IID_ID3DX11EffectShaderResourceVariable, + 0x350db233, 0xbbe0, 0x485c, 0x9b, 0xfe, 0xc0, 0x02, 0x6b, 0x84, 0x4f, 0x89); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectShaderResourceVariable + +DECLARE_INTERFACE_(ID3DX11EffectShaderResourceVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectShaderResourceVariable + STDMETHOD(SetResource)(THIS_ _In_ ID3D11ShaderResourceView *pResource) PURE; + STDMETHOD(GetResource)(THIS_ _Outptr_ ID3D11ShaderResourceView **ppResource) PURE; + + STDMETHOD(SetResourceArray)(THIS_ _In_reads_(Count) ID3D11ShaderResourceView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetResourceArray)(THIS_ _Out_writes_(Count) ID3D11ShaderResourceView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectUnorderedAccessViewVariable //////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectUnorderedAccessViewVariable ID3DX11EffectUnorderedAccessViewVariable; +typedef interface ID3DX11EffectUnorderedAccessViewVariable *LPD3D11EFFECTUNORDEREDACCESSVIEWVARIABLE; + +// {79B4AC8C-870A-47D2-B05A-8BD5CC3EE6C9} +DEFINE_GUID(IID_ID3DX11EffectUnorderedAccessViewVariable, + 0x79b4ac8c, 0x870a, 0x47d2, 0xb0, 0x5a, 0x8b, 0xd5, 0xcc, 0x3e, 0xe6, 0xc9); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectUnorderedAccessViewVariable + +DECLARE_INTERFACE_(ID3DX11EffectUnorderedAccessViewVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectUnorderedAccessViewVariable + STDMETHOD(SetUnorderedAccessView)(THIS_ _In_ ID3D11UnorderedAccessView *pResource) PURE; + STDMETHOD(GetUnorderedAccessView)(THIS_ _Outptr_ ID3D11UnorderedAccessView **ppResource) PURE; + + STDMETHOD(SetUnorderedAccessViewArray)(THIS_ _In_reads_(Count) ID3D11UnorderedAccessView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetUnorderedAccessViewArray)(THIS_ _Out_writes_(Count) ID3D11UnorderedAccessView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectRenderTargetViewVariable ////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectRenderTargetViewVariable ID3DX11EffectRenderTargetViewVariable; +typedef interface ID3DX11EffectRenderTargetViewVariable *LPD3D11EFFECTRENDERTARGETVIEWVARIABLE; + +// {D5066909-F40C-43F8-9DB5-057C2A208552} +DEFINE_GUID(IID_ID3DX11EffectRenderTargetViewVariable, + 0xd5066909, 0xf40c, 0x43f8, 0x9d, 0xb5, 0x05, 0x7c, 0x2a, 0x20, 0x85, 0x52); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectRenderTargetViewVariable + +DECLARE_INTERFACE_(ID3DX11EffectRenderTargetViewVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectRenderTargetViewVariable + STDMETHOD(SetRenderTarget)(THIS_ _In_ ID3D11RenderTargetView *pResource) PURE; + STDMETHOD(GetRenderTarget)(THIS_ _Outptr_ ID3D11RenderTargetView **ppResource) PURE; + + STDMETHOD(SetRenderTargetArray)(THIS_ _In_reads_(Count) ID3D11RenderTargetView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetRenderTargetArray)(THIS_ _Out_writes_(Count) ID3D11RenderTargetView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectDepthStencilViewVariable ////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectDepthStencilViewVariable ID3DX11EffectDepthStencilViewVariable; +typedef interface ID3DX11EffectDepthStencilViewVariable *LPD3D11EFFECTDEPTHSTENCILVIEWVARIABLE; + +// {33C648AC-2E9E-4A2E-9CD6-DE31ACC5B347} +DEFINE_GUID(IID_ID3DX11EffectDepthStencilViewVariable, + 0x33c648ac, 0x2e9e, 0x4a2e, 0x9c, 0xd6, 0xde, 0x31, 0xac, 0xc5, 0xb3, 0x47); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectDepthStencilViewVariable + +DECLARE_INTERFACE_(ID3DX11EffectDepthStencilViewVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectDepthStencilViewVariable + STDMETHOD(SetDepthStencil)(THIS_ _In_ ID3D11DepthStencilView *pResource) PURE; + STDMETHOD(GetDepthStencil)(THIS_ _Outptr_ ID3D11DepthStencilView **ppResource) PURE; + + STDMETHOD(SetDepthStencilArray)(THIS_ _In_reads_(Count) ID3D11DepthStencilView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; + STDMETHOD(GetDepthStencilArray)(THIS_ _Out_writes_(Count) ID3D11DepthStencilView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectConstantBuffer //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectConstantBuffer ID3DX11EffectConstantBuffer; +typedef interface ID3DX11EffectConstantBuffer *LPD3D11EFFECTCONSTANTBUFFER; + +// {2CB6C733-82D2-4000-B3DA-6219D9A99BF2} +DEFINE_GUID(IID_ID3DX11EffectConstantBuffer, + 0x2cb6c733, 0x82d2, 0x4000, 0xb3, 0xda, 0x62, 0x19, 0xd9, 0xa9, 0x9b, 0xf2); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectConstantBuffer + +DECLARE_INTERFACE_(ID3DX11EffectConstantBuffer, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectConstantBuffer + STDMETHOD(SetConstantBuffer)(THIS_ _In_ ID3D11Buffer *pConstantBuffer) PURE; + STDMETHOD(UndoSetConstantBuffer)(THIS) PURE; + STDMETHOD(GetConstantBuffer)(THIS_ _Outptr_ ID3D11Buffer **ppConstantBuffer) PURE; + + STDMETHOD(SetTextureBuffer)(THIS_ _In_ ID3D11ShaderResourceView *pTextureBuffer) PURE; + STDMETHOD(UndoSetTextureBuffer)(THIS) PURE; + STDMETHOD(GetTextureBuffer)(THIS_ _Outptr_ ID3D11ShaderResourceView **ppTextureBuffer) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectShaderVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_SHADER_DESC: +// +// Retrieved by ID3DX11EffectShaderVariable::GetShaderDesc() +//---------------------------------------------------------------------------- + +struct D3DX11_EFFECT_SHADER_DESC +{ + const uint8_t *pInputSignature; // Passed into CreateInputLayout, + // valid on VS and GS only + + bool IsInline; // Is this an anonymous shader variable + // resulting from an inline shader assignment? + + + // -- The following fields are not valid after Optimize() -- + const uint8_t *pBytecode; // Shader bytecode + uint32_t BytecodeLength; + + LPCSTR SODecls[D3D11_SO_STREAM_COUNT]; // Stream out declaration string (for GS with SO) + uint32_t RasterizedStream; + + uint32_t NumInputSignatureEntries; // Number of entries in the input signature + uint32_t NumOutputSignatureEntries; // Number of entries in the output signature + uint32_t NumPatchConstantSignatureEntries; // Number of entries in the patch constant signature +}; + + +typedef interface ID3DX11EffectShaderVariable ID3DX11EffectShaderVariable; +typedef interface ID3DX11EffectShaderVariable *LPD3D11EFFECTSHADERVARIABLE; + +// {7508B344-020A-4EC7-9118-62CDD36C88D7} +DEFINE_GUID(IID_ID3DX11EffectShaderVariable, + 0x7508b344, 0x020a, 0x4ec7, 0x91, 0x18, 0x62, 0xcd, 0xd3, 0x6c, 0x88, 0xd7); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectShaderVariable + +DECLARE_INTERFACE_(ID3DX11EffectShaderVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectShaderVariable + STDMETHOD(GetShaderDesc)(THIS_ _In_ uint32_t ShaderIndex, _Out_ D3DX11_EFFECT_SHADER_DESC *pDesc) PURE; + + STDMETHOD(GetVertexShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11VertexShader **ppVS) PURE; + STDMETHOD(GetGeometryShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11GeometryShader **ppGS) PURE; + STDMETHOD(GetPixelShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11PixelShader **ppPS) PURE; + STDMETHOD(GetHullShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11HullShader **ppHS) PURE; + STDMETHOD(GetDomainShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11DomainShader **ppDS) PURE; + STDMETHOD(GetComputeShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11ComputeShader **ppCS) PURE; + + STDMETHOD(GetInputSignatureElementDesc)(THIS_ _In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetOutputSignatureElementDesc)(THIS_ _In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetPatchConstantSignatureElementDesc)(THIS_ _In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectBlendVariable ///////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectBlendVariable ID3DX11EffectBlendVariable; +typedef interface ID3DX11EffectBlendVariable *LPD3D11EFFECTBLENDVARIABLE; + +// {D664F4D7-3B81-4805-B277-C1DF58C39F53} +DEFINE_GUID(IID_ID3DX11EffectBlendVariable, + 0xd664f4d7, 0x3b81, 0x4805, 0xb2, 0x77, 0xc1, 0xdf, 0x58, 0xc3, 0x9f, 0x53); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectBlendVariable + +DECLARE_INTERFACE_(ID3DX11EffectBlendVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectBlendVariable + STDMETHOD(GetBlendState)(THIS_ _In_ uint32_t Index, _Outptr_ ID3D11BlendState **ppState) PURE; + STDMETHOD(SetBlendState)(THIS_ _In_ uint32_t Index, _In_ ID3D11BlendState *pState) PURE; + STDMETHOD(UndoSetBlendState)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD(GetBackingStore)(THIS_ _In_ uint32_t Index, _Out_ D3D11_BLEND_DESC *pDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectDepthStencilVariable ////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectDepthStencilVariable ID3DX11EffectDepthStencilVariable; +typedef interface ID3DX11EffectDepthStencilVariable *LPD3D11EFFECTDEPTHSTENCILVARIABLE; + +// {69B5751B-61A5-48E5-BD41-D93988111563} +DEFINE_GUID(IID_ID3DX11EffectDepthStencilVariable, + 0x69b5751b, 0x61a5, 0x48e5, 0xbd, 0x41, 0xd9, 0x39, 0x88, 0x11, 0x15, 0x63); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectDepthStencilVariable + +DECLARE_INTERFACE_(ID3DX11EffectDepthStencilVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectDepthStencilVariable + STDMETHOD(GetDepthStencilState)(THIS_ _In_ uint32_t Index, _Outptr_ ID3D11DepthStencilState **ppState) PURE; + STDMETHOD(SetDepthStencilState)(THIS_ _In_ uint32_t Index, _In_ ID3D11DepthStencilState *pState) PURE; + STDMETHOD(UndoSetDepthStencilState)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD(GetBackingStore)(THIS_ _In_ uint32_t Index, _Out_ D3D11_DEPTH_STENCIL_DESC *pDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectRasterizerVariable //////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectRasterizerVariable ID3DX11EffectRasterizerVariable; +typedef interface ID3DX11EffectRasterizerVariable *LPD3D11EFFECTRASTERIZERVARIABLE; + +// {53A262F6-5F74-4151-A132-E3DD19A62C9D} +DEFINE_GUID(IID_ID3DX11EffectRasterizerVariable, + 0x53a262f6, 0x5f74, 0x4151, 0xa1, 0x32, 0xe3, 0xdd, 0x19, 0xa6, 0x2c, 0x9d); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectRasterizerVariable + +DECLARE_INTERFACE_(ID3DX11EffectRasterizerVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectRasterizerVariable + STDMETHOD(GetRasterizerState)(THIS_ _In_ uint32_t Index, _Outptr_ ID3D11RasterizerState **ppState) PURE; + STDMETHOD(SetRasterizerState)(THIS_ _In_ uint32_t Index, _In_ ID3D11RasterizerState *pState) PURE; + STDMETHOD(UndoSetRasterizerState)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD(GetBackingStore)(THIS_ _In_ uint32_t Index, _Out_ D3D11_RASTERIZER_DESC *pDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectSamplerVariable /////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectSamplerVariable ID3DX11EffectSamplerVariable; +typedef interface ID3DX11EffectSamplerVariable *LPD3D11EFFECTSAMPLERVARIABLE; + +// {C6402E55-1095-4D95-8931-F92660513DD9} +DEFINE_GUID(IID_ID3DX11EffectSamplerVariable, + 0xc6402e55, 0x1095, 0x4d95, 0x89, 0x31, 0xf9, 0x26, 0x60, 0x51, 0x3d, 0xd9); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectSamplerVariable + +DECLARE_INTERFACE_(ID3DX11EffectSamplerVariable, ID3DX11EffectVariable) +{ + // IUnknown + // ID3DX11EffectVariable + + // ID3DX11EffectSamplerVariable + STDMETHOD(GetSampler)(THIS_ _In_ uint32_t Index, _Outptr_ ID3D11SamplerState **ppSampler) PURE; + STDMETHOD(SetSampler)(THIS_ _In_ uint32_t Index, _In_ ID3D11SamplerState *pSampler) PURE; + STDMETHOD(UndoSetSampler)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD(GetBackingStore)(THIS_ _In_ uint32_t Index, _Out_ D3D11_SAMPLER_DESC *pDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectPass ////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_PASS_DESC: +// +// Retrieved by ID3DX11EffectPass::GetDesc() +//---------------------------------------------------------------------------- + +struct D3DX11_PASS_DESC +{ + LPCSTR Name; // Name of this pass (nullptr if not anonymous) + uint32_t Annotations; // Number of annotations on this pass + + uint8_t *pIAInputSignature; // Signature from VS or GS (if there is no VS) + // or nullptr if neither exists + size_t IAInputSignatureSize; // Singature size in bytes + + uint32_t StencilRef; // Specified in SetDepthStencilState() + uint32_t SampleMask; // Specified in SetBlendState() + FLOAT BlendFactor[4]; // Specified in SetBlendState() +}; + +//---------------------------------------------------------------------------- +// D3DX11_PASS_SHADER_DESC: +// +// Retrieved by ID3DX11EffectPass::Get**ShaderDesc() +//---------------------------------------------------------------------------- + +struct D3DX11_PASS_SHADER_DESC +{ + ID3DX11EffectShaderVariable *pShaderVariable; // The variable that this shader came from. + // If this is an inline shader assignment, + // the returned interface will be an + // anonymous shader variable, which is + // not retrievable any other way. It's + // name in the variable description will + // be "$Anonymous". + // If there is no assignment of this type in + // the pass block, pShaderVariable != nullptr, + // but pShaderVariable->IsValid() == false. + + uint32_t ShaderIndex; // The element of pShaderVariable (if an array) + // or 0 if not applicable +}; + +typedef interface ID3DX11EffectPass ID3DX11EffectPass; +typedef interface ID3DX11EffectPass *LPD3D11EFFECTPASS; + +// {3437CEC4-4AC1-4D87-8916-F4BD5A41380C} +DEFINE_GUID(IID_ID3DX11EffectPass, + 0x3437cec4, 0x4ac1, 0x4d87, 0x89, 0x16, 0xf4, 0xbd, 0x5a, 0x41, 0x38, 0x0c); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectPass + +DECLARE_INTERFACE_(ID3DX11EffectPass, IUnknown) +{ + // IUnknown + + // ID3DX11EffectPass + STDMETHOD_(bool, IsValid)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_PASS_DESC *pDesc) PURE; + + STDMETHOD(GetVertexShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetGeometryShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetPixelShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetHullShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetDomainShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetComputeShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ _In_z_ LPCSTR Name) PURE; + + STDMETHOD(Apply)(THIS_ _In_ uint32_t Flags, _In_ ID3D11DeviceContext* pContext) PURE; + + STDMETHOD(ComputeStateBlockMask)(THIS_ _Inout_ D3DX11_STATE_BLOCK_MASK *pStateBlockMask) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectTechnique ///////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_TECHNIQUE_DESC: +// +// Retrieved by ID3DX11EffectTechnique::GetDesc() +//---------------------------------------------------------------------------- + +struct D3DX11_TECHNIQUE_DESC +{ + LPCSTR Name; // Name of this technique (nullptr if not anonymous) + uint32_t Passes; // Number of passes contained within + uint32_t Annotations; // Number of annotations on this technique +}; + +typedef interface ID3DX11EffectTechnique ID3DX11EffectTechnique; +typedef interface ID3DX11EffectTechnique *LPD3D11EFFECTTECHNIQUE; + +// {51198831-1F1D-4F47-BD76-41CB0835B1DE} +DEFINE_GUID(IID_ID3DX11EffectTechnique, + 0x51198831, 0x1f1d, 0x4f47, 0xbd, 0x76, 0x41, 0xcb, 0x08, 0x35, 0xb1, 0xde); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectTechnique + +DECLARE_INTERFACE_(ID3DX11EffectTechnique, IUnknown) +{ + // IUnknown + + // ID3DX11EffectTechnique + STDMETHOD_(bool, IsValid)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_TECHNIQUE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ _In_z_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectPass*, GetPassByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectPass*, GetPassByName)(THIS_ _In_z_ LPCSTR Name) PURE; + + STDMETHOD(ComputeStateBlockMask)(THIS_ _Inout_ D3DX11_STATE_BLOCK_MASK *pStateBlockMask) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectTechnique ///////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_GROUP_DESC: +// +// Retrieved by ID3DX11EffectTechnique::GetDesc() +//---------------------------------------------------------------------------- + +struct D3DX11_GROUP_DESC +{ + LPCSTR Name; // Name of this group (only nullptr if global) + uint32_t Techniques; // Number of techniques contained within + uint32_t Annotations; // Number of annotations on this group +}; + +typedef interface ID3DX11EffectGroup ID3DX11EffectGroup; +typedef interface ID3DX11EffectGroup *LPD3D11EFFECTGROUP; + +// {03074acf-97de-485f-b201-cb775264afd6} +DEFINE_GUID(IID_ID3DX11EffectGroup, + 0x03074acf, 0x97de, 0x485f, 0xb2, 0x01, 0xcb, 0x77, 0x52, 0x64, 0xaf, 0xd6); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectGroup + +DECLARE_INTERFACE_(ID3DX11EffectGroup, IUnknown) +{ + // IUnknown + + // ID3DX11EffectGroup + STDMETHOD_(bool, IsValid)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_GROUP_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ _In_z_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(THIS_ _In_z_ LPCSTR Name) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11Effect ////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_DESC: +// +// Retrieved by ID3DX11Effect::GetDesc() +//---------------------------------------------------------------------------- + +struct D3DX11_EFFECT_DESC +{ + uint32_t ConstantBuffers; // Number of constant buffers in this effect + uint32_t GlobalVariables; // Number of global variables in this effect + uint32_t InterfaceVariables; // Number of global interfaces in this effect + uint32_t Techniques; // Number of techniques in this effect + uint32_t Groups; // Number of groups in this effect +}; + +typedef interface ID3DX11Effect ID3DX11Effect; +typedef interface ID3DX11Effect *LPD3D11EFFECT; + +// {FA61CA24-E4BA-4262-9DB8-B132E8CAE319} +DEFINE_GUID(IID_ID3DX11Effect, + 0xfa61ca24, 0xe4ba, 0x4262, 0x9d, 0xb8, 0xb1, 0x32, 0xe8, 0xca, 0xe3, 0x19); + +#undef INTERFACE +#define INTERFACE ID3DX11Effect + +DECLARE_INTERFACE_(ID3DX11Effect, IUnknown) +{ + // IUnknown + + // ID3DX11Effect + STDMETHOD_(bool, IsValid)(THIS) PURE; + + STDMETHOD(GetDevice)(THIS_ _Outptr_ ID3D11Device** ppDevice) PURE; + + STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_EFFECT_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetConstantBufferByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetConstantBufferByName)(THIS_ _In_z_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetVariableByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetVariableByName)(THIS_ _In_z_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetVariableBySemantic)(THIS_ _In_z_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectGroup*, GetGroupByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectGroup*, GetGroupByName)(THIS_ _In_z_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(THIS_ _In_ uint32_t Index) PURE; + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(THIS_ _In_z_ LPCSTR Name) PURE; + + STDMETHOD_(ID3D11ClassLinkage*, GetClassLinkage)(THIS) PURE; + + STDMETHOD(CloneEffect)(THIS_ _In_ uint32_t Flags, _Outptr_ ID3DX11Effect** ppClonedEffect ) PURE; + STDMETHOD(Optimize)(THIS) PURE; + STDMETHOD_(bool, IsOptimized)(THIS) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// APIs ////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + +//---------------------------------------------------------------------------- +// D3DX11CreateEffectFromMemory +// +// Creates an effect instance from a compiled effect in memory +// +// Parameters: +// +// [in] +// +// pData +// Blob of compiled effect data +// DataLength +// Length of the data blob +// FXFlags +// Flags pertaining to Effect creation +// pDevice +// Pointer to the D3D11 device on which to create Effect resources +// srcName [optional] +// ASCII string to use for debug object naming +// +// [out] +// +// ppEffect +// Address of the newly created Effect interface +// +//---------------------------------------------------------------------------- + +HRESULT WINAPI D3DX11CreateEffectFromMemory( _In_reads_bytes_(DataLength) LPCVOID pData, + _In_ SIZE_T DataLength, + _In_ UINT FXFlags, + _In_ ID3D11Device *pDevice, + _Outptr_ ID3DX11Effect **ppEffect, + _In_opt_z_ LPCSTR srcName = nullptr ); + +//---------------------------------------------------------------------------- +// D3DX11CreateEffectFromFile +// +// Creates an effect instance from a compiled effect data file +// +// Parameters: +// +// [in] +// +// pFileName +// Compiled effect file +// FXFlags +// Flags pertaining to Effect creation +// pDevice +// Pointer to the D3D11 device on which to create Effect resources +// +// [out] +// +// ppEffect +// Address of the newly created Effect interface +// +//---------------------------------------------------------------------------- + +HRESULT WINAPI D3DX11CreateEffectFromFile( _In_z_ LPCWSTR pFileName, + _In_ UINT FXFlags, + _In_ ID3D11Device *pDevice, + _Outptr_ ID3DX11Effect **ppEffect ); + +//---------------------------------------------------------------------------- +// D3DX11CompileEffectFromMemory +// +// Complies an effect shader source file in memory and then creates an effect instance +// +// Parameters: +// +// [in] +// +// pData +// Pointer to FX shader as an ASCII string +// DataLength +// Length of the FX shader ASCII string +// srcName [optional] +// ASCII string to use for debug object naming +// pDefines [optional] +// A NULL-terminated array of shader macros +// pInclude [optional] +// A pointer to an include interface +// HLSLFlags +// HLSL compile options (see D3DCOMPILE flags) +// FXFlags +// Flags pertaining to Effect compilation (see D3DCOMPILE_EFFECT flags) +// pDevice +// Pointer to the D3D11 device on which to create Effect resources +// +// [out] +// +// ppEffect +// Address of the newly created Effect interface +// +//---------------------------------------------------------------------------- + +HRESULT D3DX11CompileEffectFromMemory( _In_reads_bytes_(DataLength) LPCVOID pData, + _In_ SIZE_T DataLength, + _In_opt_z_ LPCSTR srcName, + _In_opt_ const D3D_SHADER_MACRO *pDefines, + _In_opt_ ID3DInclude *pInclude, + _In_ UINT HLSLFlags, + _In_ UINT FXFlags, + _In_ ID3D11Device *pDevice, + _Out_ ID3DX11Effect **ppEffect, + _Outptr_opt_result_maybenull_ ID3DBlob **ppErrors ); + +//---------------------------------------------------------------------------- +// D3DX11CompileEffectFromFile +// +// Complies an effect shader source file and then creates an effect instance +// +// Parameters: +// +// [in] +// +// pFileName +// FX shader source file +// pDefines [optional] +// A NULL-terminated array of shader macros +// pInclude [optional] +// A pointer to an include interface +// HLSLFlags +// HLSL compile options (see D3DCOMPILE flags) +// FXFlags +// Flags pertaining to Effect compilation (see D3DCOMPILE_EFFECT flags) +// pDevice +// Pointer to the D3D11 device on which to create Effect resources +// +// [out] +// +// ppEffect +// Address of the newly created Effect interface +// +//---------------------------------------------------------------------------- + +HRESULT D3DX11CompileEffectFromFile( _In_z_ LPCWSTR pFileName, + _In_opt_ const D3D_SHADER_MACRO *pDefines, + _In_opt_ ID3DInclude *pInclude, + _In_ UINT HLSLFlags, + _In_ UINT FXFlags, + _In_ ID3D11Device *pDevice, + _Out_ ID3DX11Effect **ppEffect, + _Outptr_opt_result_maybenull_ ID3DBlob **ppErrors ); + + +//---------------------------------------------------------------------------- +// D3DX11DebugMute +// +// Controls the output of diagnostic information in DEBUG builds. No effect +// in RELEASE builds. +// +// Returns the previous state so you can do temporary suppression like: +// +// bool oldmute = D3DX11DebugMute(true); +// ... +// D3DX11DebugMute(oldmute); +// +//---------------------------------------------------------------------------- + +bool D3DX11DebugMute(bool mute); + +#ifdef __cplusplus +} +#endif //__cplusplus diff --git a/inc/xna/common/numerics.hpp b/inc/xna/common/numerics.hpp index 8af7812..bb36aa5 100644 --- a/inc/xna/common/numerics.hpp +++ b/inc/xna/common/numerics.hpp @@ -3,6 +3,7 @@ #include #include "../default.hpp" +#include namespace xna { struct Point { @@ -34,6 +35,10 @@ namespace xna { return Height == other.Height && Width == other.Width && X == other.X && Y == other.Y; } + constexpr operator std::optional() const { + return std::make_optional(X, Y, Width, Height); + } + constexpr Int Left() const { return X; } constexpr Int Right() const { return X + Width; } constexpr Int Top() const { return Y; } diff --git a/inc/xna/content/readers/graphics.hpp b/inc/xna/content/readers/graphics.hpp index 6c4194c..2254ca0 100644 --- a/inc/xna/content/readers/graphics.hpp +++ b/inc/xna/content/readers/graphics.hpp @@ -28,7 +28,7 @@ namespace xna { if (a_device.has_value()) device = std::any_cast>(a_device); - auto texture2D = New(device, width, height, mipMaps, format); + auto texture2D = snew(device, width, height, mipMaps, format); for (size_t level = 0; level < mipMaps; ++level) { auto elementCount = input.ReadInt32(); diff --git a/inc/xna/csharp/stream.hpp b/inc/xna/csharp/stream.hpp index 75977fb..8e8d4b7 100644 --- a/inc/xna/csharp/stream.hpp +++ b/inc/xna/csharp/stream.hpp @@ -3,7 +3,6 @@ #include "../types.hpp" #include "../enums.hpp" -#include "../xnaerror.hpp" #include #include diff --git a/inc/xna/csharp/type.hpp b/inc/xna/csharp/type.hpp index 089e7bd..934ee84 100644 --- a/inc/xna/csharp/type.hpp +++ b/inc/xna/csharp/type.hpp @@ -51,7 +51,7 @@ namespace xna { template inline sptr typeof() { if (std::is_arithmetic::value) { - auto primitiveType = New(); + auto primitiveType = snew(); primitiveType->fullName = typeid(T).name(); primitiveType->isPrimitive = true; primitiveType->isValueType = true; @@ -59,7 +59,7 @@ namespace xna { } if (std::is_enum::value) { - auto enumType = New(); + auto enumType = snew(); enumType->fullName = typeid(T).name(); enumType->isValueType = true; enumType->isEnum = true; @@ -67,14 +67,14 @@ namespace xna { } if (std::is_pointer::value) { - auto pointerType = New(); + auto pointerType = snew(); pointerType->fullName = typeid(T).name(); pointerType->isPointer = true; return pointerType; } if (std::is_class::value) { - auto classType = New(); + auto classType = snew(); classType->fullName = typeid(T).name(); classType->isClass = true; diff --git a/inc/xna/default.hpp b/inc/xna/default.hpp index ee10054..634624e 100644 --- a/inc/xna/default.hpp +++ b/inc/xna/default.hpp @@ -2,4 +2,4 @@ #include "forward.hpp" #include "enums.hpp" #include "helpers.hpp" -#include "xnaerror.hpp" \ No newline at end of file +#include "exception.hpp" \ No newline at end of file diff --git a/inc/xna/enums.hpp b/inc/xna/enums.hpp index 83d09f9..d55fcf5 100644 --- a/inc/xna/enums.hpp +++ b/inc/xna/enums.hpp @@ -119,7 +119,8 @@ namespace xna { Green, Blue, Alpha, - All + All, + None }; enum class ContainmentType { @@ -138,6 +139,8 @@ namespace xna { GreaterEqual, Always }; + + using CompareFunction = ComparisonFunction; enum class CurveContinuity { Smooth, @@ -197,6 +200,27 @@ namespace xna { Stretched = 2 }; + enum class EffectParameterClass { + Matrix, + Object, + Scalar, + Struct, + Vector + }; + + enum class EffectParameterType { + Bool, + Int32, + Single, + String, + Texture, + Texture1D, + Texture2D, + Texture3D, + TextureCube, + Void + }; + enum class FileMode { CreateNew, Create, @@ -450,6 +474,14 @@ namespace xna { Immediate }; + enum class PrimitiveType + { + TriangleList, + TriangleStrip, + LineList, + LineStrip, + }; + enum RenderTargetUsage { DiscardContents, PreserveContents, diff --git a/inc/xna/exception.hpp b/inc/xna/exception.hpp new file mode 100644 index 0000000..d981002 --- /dev/null +++ b/inc/xna/exception.hpp @@ -0,0 +1,48 @@ +#ifndef XNA_EXCEPTION_HPP +#define XNA_EXCEPTION_HPP + +#include +#include +#include + +namespace xna { + + //A list of standard exceptions + struct ExMessage { + inline static const std::string InvalidOperation = "An invalid operation occurred."; + inline static const std::string InitializeComponent = "Unable to initialize component"; + inline static const std::string CreateComponent = "Failed to create component"; + inline static const std::string ApplyComponent = "Failed to apply component"; + inline static const std::string UnintializedComponent = "Component is not initialized"; + inline static const std::string MakeWindowAssociation = "Failed to create association with window"; + inline static const std::string BuildObject = "Unable to build object"; + }; + + //Structure for throwing exceptions with a message and information from the source file + struct Exception { + + //Raises an exception with a message. Source file information is automatically captured. + static void Throw(std::string const& message, const std::source_location location = std::source_location::current()) { + std::string error; + + error.append("Exception in: "); +#if _DEBUG + error.append(location.file_name()); + error.append("("); + error.append(std::to_string(location.line())); + error.append(":"); + error.append(std::to_string(location.column())); + error.append(") "); +#endif + error.append("'"); + error.append(location.function_name()); + error.append("': "); + error.append(message); + error.append("\n"); + + throw std::runtime_error(error); + } + }; +} + +#endif \ No newline at end of file diff --git a/inc/xna/forward.hpp b/inc/xna/forward.hpp index 5247bd2..081be41 100644 --- a/inc/xna/forward.hpp +++ b/inc/xna/forward.hpp @@ -70,8 +70,11 @@ namespace xna { class SwapChain; class Texture; class Texture2D; + class Texture3D; + class TextureCube; class RasterizerState; class SamplerState; + class SamplerStateCollection; class Shader; class SpriteBatch; class SpriteFont; diff --git a/inc/xna/graphics/adapter.hpp b/inc/xna/graphics/adapter.hpp index a70c446..c0dad93 100644 --- a/inc/xna/graphics/adapter.hpp +++ b/inc/xna/graphics/adapter.hpp @@ -4,26 +4,42 @@ #include "../default.hpp" namespace xna { + //Provides methods to retrieve and manipulate graphics adapters. class GraphicsAdapter { public: GraphicsAdapter(); - ~GraphicsAdapter(); + //Retrieves a string used for presentation to the user. String Description() const; + //Retrieves a value that is used to help identify a particular chip set. Uint DeviceId() const; + //Retrieves a string that contains the device name. String DeviceName() const; + //Determines if this instance of GraphicsAdapter is the default adapter. bool IsDefaultAdapter() const; + //Retrieves the handle of the monitor intptr_t MonitorHandle() const; + //Retrieves a value used to help identify the revision level of a particular chip set. Uint Revision() const; + //Retrieves a value used to identify the subsystem. Uint SubSystemId() const; + //Retrieves a value used to identify the manufacturer. Uint VendorId() const; + + //Returns a collection of supported display modes for the current adapter. uptr SupportedDisplayModes() const; + //Returns a collection of supported display modes for the current adapter. uptr SupportedDisplayModes(SurfaceFormat surfaceFormat) const; + + //Gets the current display mode. sptr CurrentDisplayMode(); + //Gets the current display mode. void CurrentDisplayMode(SurfaceFormat surfaceFormat, Uint width, Uint height); + //Gets the default adapter. static uptr DefaultAdapter(); - static void Adapters(std::vector>& adapters); + + //Collection of available adapters on the system. static void Adapters(std::vector>& adapters); public: diff --git a/inc/xna/graphics/blendstate.hpp b/inc/xna/graphics/blendstate.hpp index ce9e4de..ba65f71 100644 --- a/inc/xna/graphics/blendstate.hpp +++ b/inc/xna/graphics/blendstate.hpp @@ -1,32 +1,83 @@ #ifndef XNA_GRAPHICS_BLENDSTATE_HPP #define XNA_GRAPHICS_BLENDSTATE_HPP +#include "../common/color.hpp" #include "../default.hpp" #include "gresource.hpp" namespace xna { struct BlendRenderTarget; + //Contains blend state for the device. class BlendState : public GraphicsResource { public: BlendState(); BlendState(sptr const& device); - ~BlendState() override; - bool Initialize(xna_error_nullarg) ; - void AlphaToCoverageEnable(bool value) ; - void IndependentBlendEnable(bool value) ; - void RenderTargets(std::vector const& value); - bool Apply(xna_error_nullarg); + //Gets or sets the arithmetic operation when blending alpha values. The default is BlendFunction.Add. + BlendFunction AlphaBlendFunction() const; + //Gets or sets the arithmetic operation when blending alpha values. The default is BlendFunction.Add. + void AlphaBlendFunction(BlendFunction value); + //Gets or sets the blend factor for the destination alpha, which is the percentage of the destination alpha included in the blended result. The default is Blend.One. + Blend AlphaDestinationBlend() const; + //Gets or sets the blend factor for the destination alpha, which is the percentage of the destination alpha included in the blended result. The default is Blend.One. + void AlphaDestinationBlend(Blend value); + //Gets or sets the alpha blend factor. The default is Blend.One. + Blend AlphaSourceBlend() const; + //Gets or sets the alpha blend factor. The default is Blend.One. + void AlphaSourceBlend(Blend value); + + //Gets or sets the arithmetic operation when blending color values. The default is BlendFunction.Add. + BlendFunction ColorBlendFunction() const; + //Gets or sets the arithmetic operation when blending color values. The default is BlendFunction.Add. + void ColorBlendFunction(BlendFunction value); + //Gets or sets the blend factor for the destination color. The default is Blend.One. + Blend ColorDestinationBlend() const; + //Gets or sets the blend factor for the destination color. The default is Blend.One. + void ColorDestinationBlend(Blend value); + //Gets or sets the blend factor for the source color. The default is Blend.One. + Blend ColorSourceBlend() const; + //Gets or sets the blend factor for the source color. The default is Blend.One. + void ColorSourceBlend(Blend value); + + //Gets or sets the four-component (RGBA) blend factor for alpha blending. + Color BlendFactor() const; + //Gets or sets the four-component (RGBA) blend factor for alpha blending. + void BlendFactor(Color const& value); + + //Gets or sets a bitmask which defines which samples can be written during multisampling. The default is 0xffffffff. + Int MultiSampleMask() const; + //Gets or sets a bitmask which defines which samples can be written during multisampling. The default is 0xffffffff. + void MultiSampleMast(Int value); + + //Specifies whether to use alpha-to-coverage as a multisampling technique when setting a pixel to a render target. + void AlphaToCoverageEnable(bool value); + //Specifies whether to enable independent blending in simultaneous render targets + void IndependentBlendEnable(bool value); + + void RenderTargets(std::vector const& value); + bool Initialize(); + bool Apply(); + + //A built-in state object with settings for opaque blend, + //that is overwriting the source with the destination data. static uptr Opaque(); + //A built-in state object with settings for alpha blend, + //that is blending the source and destination data using alpha. static uptr AlphaBlend(); + //A built-in state object with settings for additive blend, + //that is adding the destination data to the source data without using alpha. static uptr Additive(); + //A built-in state object with settings for blending with non-premultipled alpha, + //that is blending source and destination data using alpha while assuming the color data contains no alpha information. static uptr NonPremultiplied(); public: struct PlatformImplementation; uptr impl = nullptr; }; + + using PBlendState = sptr; } #endif \ No newline at end of file diff --git a/inc/xna/graphics/buffer.hpp b/inc/xna/graphics/buffer.hpp index 0adde1e..66e4671 100644 --- a/inc/xna/graphics/buffer.hpp +++ b/inc/xna/graphics/buffer.hpp @@ -10,7 +10,7 @@ namespace xna { ConstantBuffer(); ConstantBuffer(sptr const&); ~ConstantBuffer() override; - bool Initialize(xna_error_nullarg); + bool Initialize(); public: struct PlatformImplementation; @@ -22,7 +22,7 @@ namespace xna { DataBuffer(); DataBuffer(sptr const&); ~DataBuffer() override; - bool Initialize(xna_error_nullarg); + bool Initialize(); public: struct PlatformImplementation; @@ -36,8 +36,8 @@ namespace xna { ~IndexBuffer() override; template - bool Initialize(std::vector const& data, xna_error_nullarg); - bool Apply(xna_error_nullarg); + bool Initialize(std::vector const& data); + bool Apply(); public: struct PlatformImplementation; @@ -50,8 +50,8 @@ namespace xna { VertexBuffer(sptr const&); ~VertexBuffer(); template - bool Initialize(std::vector const& data, xna_error_nullarg); - bool Apply(xna_error_nullarg); + bool Initialize(std::vector const& data); + bool Apply(); public: struct PlatformImplementation; @@ -64,7 +64,7 @@ namespace xna { VertexInputLayout(sptr const&); ~VertexInputLayout(); - bool Initialize(DataBuffer& blob, xna_error_nullarg); + bool Initialize(DataBuffer& blob); public: struct PlatformImplementation; diff --git a/inc/xna/graphics/depthstencilstate.hpp b/inc/xna/graphics/depthstencilstate.hpp index 1decdbc..0664143 100644 --- a/inc/xna/graphics/depthstencilstate.hpp +++ b/inc/xna/graphics/depthstencilstate.hpp @@ -5,54 +5,95 @@ #include "gresource.hpp" namespace xna { + //Contains depth-stencil state for the device. class DepthStencilState : public GraphicsResource { public: - DepthStencilState(); DepthStencilState(sptr const& device); - - ~DepthStencilState() override; - bool Initialize(xna_error_nullarg); - bool Apply(xna_error_ptr_arg); - void DepthEnabled(bool value); - void DepthWriteEnabled(bool value); - void DepthCompareFunction(ComparisonFunction value); - void StencilEnabled(bool value); - void StencilReadMask(Int value); + //Gets or sets the stencil operation to perform if the stencil test passes and the depth-buffer test fails for a counterclockwise triangle. + //The default is StencilOperation.Keep. + void CounterClockwiseStencilDepthBufferFail(StencilOperation value); + //Gets or sets the stencil operation to perform if the stencil test passes and the depth-buffer test fails for a counterclockwise triangle. + //The default is StencilOperation.Keep. + StencilOperation CounterClockwiseStencilDepthBufferFail() const; + //Gets or sets the stencil operation to perform if the stencil test fails for a counterclockwise triangle. + //The default is StencilOperation.Keep. + void CounterClockwiseStencilFail(StencilOperation value); + //Gets or sets the stencil operation to perform if the stencil test fails for a counterclockwise triangle. + //The default is StencilOperation.Keep. + StencilOperation CounterClockwiseStencilFail() const; + //Gets or sets the comparison function to use for counterclockwise stencil tests. The default is CompareFunction.Always. + void CounterClockwiseStencilFunction(CompareFunction value); + //Gets or sets the comparison function to use for counterclockwise stencil tests. The default is CompareFunction.Always. + CompareFunction CounterClockwiseStencilFunction() const; + //Gets or sets the stencil operation to perform if the stencil and depth-tests pass for a counterclockwise triangle. + //The default is StencilOperation.Keep. + void CounterClockwiseStencilPass(StencilOperation value); + //Gets or sets the stencil operation to perform if the stencil and depth-tests pass for a counterclockwise triangle. + //The default is StencilOperation.Keep. + StencilOperation CounterClockwiseStencilPass() const; + + //Enables or disables depth buffering. The default is true. + void DepthBufferEnable(bool value); + //Enables or disables depth buffering. The default is true. + bool DepthBufferEnable() const; + //Enables or disables writing to the depth buffer. The default is true. + void DepthBufferWriteEnable(bool value); + //Enables or disables writing to the depth buffer. The default is true. + bool DepthBufferWriteEnable() const; + //Gets or sets the comparison function for the depth-buffer test. The default is CompareFunction.LessEqual + void DepthBufferFunction(CompareFunction value); + //Gets or sets the comparison function for the depth-buffer test. The default is CompareFunction.LessEqual + CompareFunction DepthBufferFunction() const; + + //Gets or sets stencil enabling. The default is false. + void StencilEnable(bool value); + //Gets or sets stencil enabling. The default is false. + bool StencilEnable() const; + //Gets or sets the stencil operation to perform if the stencil test fails. The default is StencilOperation.Keep. + void StencilFail(StencilOperation value); + //Gets or sets the stencil operation to perform if the stencil test fails. The default is StencilOperation.Keep. + StencilOperation StencilFail() const; + //Gets or sets the comparison function for the stencil test.The default is CompareFunction.Always. + void StencilFunction(CompareFunction value); + //Gets or sets the comparison function for the stencil test. The default is CompareFunction.Always. + CompareFunction StencilFunction() const; + //Gets or sets the mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. + //The default mask is Int32.MaxValue. + void StencilMask(Int value); + //Gets or sets the mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. + //The default mask is Int32.MaxValue. + Int StencilMask() const; + //Gets or sets the write mask applied to values written into the stencil buffer. The default mask is Int32.MaxValue. void StencilWriteMask(Int value); - void StencilFrontFacePass(StencilOperation value); - void StencilFrontFaceFail(StencilOperation value); - void StencilFrontFaceDepthFail(StencilOperation value); - void StencilFrontFaceCompare(ComparisonFunction value); - void StencilBackFacePass(StencilOperation value); - void StencilBackFaceFail(StencilOperation value); - void StencilBackFaceDepthFail(StencilOperation value); - void StencilBackFaceCompare(ComparisonFunction value); - - bool DepthEnabled() const; - bool DepthWriteEnabled() const; - ComparisonFunction DepthCompareFunction() const; - bool StencilEnabled() const; - Int StencilReadMask() const; + //Gets or sets the write mask applied to values written into the stencil buffer. The default mask is Int32.MaxValue. Int StencilWriteMask() const; - StencilOperation StencilFrontFacePass() const; - StencilOperation StencilFrontFaceFail() const; - StencilOperation StencilFrontFaceDepthFail() const; - ComparisonFunction StencilFrontFaceCompare() const; - StencilOperation StencilBackFacePass() const; - StencilOperation StencilBackFaceFail() const; - StencilOperation StencilBackFaceDepthFail() const; - ComparisonFunction StencilBackFaceCompare() const; + //Gets or sets the stencil operation to perform if the stencil test passes. The default is StencilOperation.Keep. + void StencilPass(StencilOperation value); + //Gets or sets the stencil operation to perform if the stencil test passes. The default is StencilOperation.Keep. + StencilOperation StencilPass() const; + //Gets or sets the stencil operation to perform if the stencil test passes and the depth-test fails. The default is StencilOperation.Keep. + void StencilDepthBufferFail(StencilOperation value); + //Gets or sets the stencil operation to perform if the stencil test passes and the depth-test fails. The default is StencilOperation.Keep. + StencilOperation StencilDepthBufferFail() const; + //A built-in state object with settings for not using a depth stencil buffer. static uptr None(); + //A built-in state object with default settings for using a depth stencil buffer. static uptr Default(); + //A built-in state object with settings for enabling a read-only depth stencil buffer. static uptr DepthRead(); + bool Initialize(); + bool Apply(); + public: struct PlatformImplementation; uptr impl = nullptr; }; + + using PDepthStencilState = sptr; } #endif \ No newline at end of file diff --git a/inc/xna/graphics/device.hpp b/inc/xna/graphics/device.hpp index 8642bc8..2c7e63b 100644 --- a/inc/xna/graphics/device.hpp +++ b/inc/xna/graphics/device.hpp @@ -4,25 +4,52 @@ #include "../default.hpp" namespace xna { + //Performs primitive-based rendering, creates resources, handles system-level variables, adjusts gamma ramp levels, and creates shaders. class GraphicsDevice : public std::enable_shared_from_this { public: GraphicsDevice(); GraphicsDevice(GraphicsDeviceInformation const& info); - ~GraphicsDevice(); + + //Gets the graphics adapter. + sptr Adapter() const; + + //Gets or sets a system-defined instance of a blend state object initialized for alpha blending. The default value is BlendState.Opaque. + sptr BlendState() const; + //Gets or sets a system-defined instance of a blend state object initialized for alpha blending. The default value is BlendState.Opaque. + void BlendState(sptr const& value); + //Gets or sets a system-defined instance of a depth-stencil state object. The default value is DepthStencilState.Default. + sptr DepthStencilState() const; + //Gets or sets a system-defined instance of a depth-stencil state object. The default value is DepthStencilState.Default. + void DepthStencilState(sptr const& value); + //Gets or sets rasterizer state. The default value is RasterizerState.CullCounterClockwise. + sptr RasterizerState() const; + //Gets or sets rasterizer state. The default value is RasterizerState.CullCounterClockwise. + void RasterizerState(sptr const& value); + //Retrieves a collection of SamplerState objects for the current GraphicsDevice. + sptr SamplerStates() const; + + //Gets or sets a bitmask controlling modification of the samples in a multisample render target. The default value is -1 (0xffffffff). + Int MultiSampleMask() const; + //Gets or sets a bitmask controlling modification of the samples in a multisample render target. The default value is -1 (0xffffffff). + void MultiSampleMask(Int value); + void Clear(); void Clear(Color const& color); - bool Initialize(GameWindow& gameWindow); + bool Initialize(); bool Present(); - sptr Adapter() const; - void Adapter(sptr const& adapter); + xna::Viewport Viewport() const; void Viewport(xna::Viewport const& viewport); void UseVSync(bool use); + //void DrawPrimitives(PrimitiveType primitiveType, Int startVertex, Int primitiveCount); + public: struct PlatformImplementation; uptr impl = nullptr; }; + + using PGraphicsDevice = sptr; } #endif \ No newline at end of file diff --git a/inc/xna/graphics/displaymode.hpp b/inc/xna/graphics/displaymode.hpp index 38540de..8861a7f 100644 --- a/inc/xna/graphics/displaymode.hpp +++ b/inc/xna/graphics/displaymode.hpp @@ -6,11 +6,12 @@ namespace xna { struct DisplayModeDescription; + //Describes the display mode. class DisplayMode { public: - DisplayMode(); - ~DisplayMode(); + DisplayMode(); + //Gets the aspect ratio used by the graphics device. constexpr float AspectRatio() const { if (Height == 0 || Width == 0) return 0; @@ -25,8 +26,11 @@ namespace xna { } public: + //Gets a value indicating the screen width, in pixels. Int Width{ 0 }; + //Gets a value indicating the screen height, in pixels. Int Height{ 0 }; + //Gets a value indicating the surface format of the display mode. SurfaceFormat Format{ SurfaceFormat::Color }; public: @@ -34,6 +38,7 @@ namespace xna { uptr impl; }; + //Manipulates a collection of DisplayMode structures. class DisplayModeCollection { public: constexpr DisplayModeCollection() = default; diff --git a/inc/xna/graphics/effect.hpp b/inc/xna/graphics/effect.hpp new file mode 100644 index 0000000..9cc4f30 --- /dev/null +++ b/inc/xna/graphics/effect.hpp @@ -0,0 +1,300 @@ +#ifndef XNA_GRAPHICS_EFFECT_HPP +#define XNA_GRAPHICS_EFFECT_HPP + +#include "../common/numerics.hpp" +#include "../default.hpp" +#include "gresource.hpp" + +namespace xna { + //Represents an annotation to an EffectParameter. + class EffectAnnotation { + public: + Int ColumCount() const; + String Name() const; + EffectParameterClass ParameterClass() const; + Int RowCount() const; + String Semantic() const; + bool GetValueBoolean() const; + Int GetValueInt32() const; + Matrix GetValueMatrix() const; + float GetValueSingle() const; + String GetValueString() const; + Vector2 GetValueVector2() const; + Vector3 GetValueVector3() const; + Vector4 GetValueVector4() const; + + public: + struct PlatformImplementation; + uptr impl; + + public: + EffectAnnotation(); + }; + using PEffectAnnotation = sptr; + + class EffectAnnotationCollection { + public: + EffectAnnotationCollection() {} + + EffectAnnotationCollection(std::vector const& data) : data(data) + { + } + + constexpr size_t Count() const { + return data.size(); + } + + PEffectAnnotation operator[](size_t index) { + if (index >= data.size()) + return nullptr; + + return data[index]; + } + + PEffectAnnotation operator[](String const& name) { + for (size_t i = 0; i < data.size(); ++i) { + const auto& p = data[i]; + + if (p->Name() == name) + return p; + } + + return nullptr; + } + + public: + std::vector data; + }; + using PEffectAnnotationCollection = sptr; + + class EffectPass { + public: + //Gets the name of this pass. + String Name() const; + //The EffectAnnotationCollection containing EffectAnnotation objects for this EffectPass. + PEffectAnnotationCollection Annotations() const; + + //Begins this pass. + void Apply(); + public: + struct PlatformImplementation; + uptr impl; + + public: + EffectPass(); + }; + using PEffectPass = sptr; + + class EffectPassCollection { + public: + EffectPassCollection() {} + + EffectPassCollection(std::vector const& data) : data(data) + { + } + + constexpr size_t Count() const { + return data.size(); + } + + PEffectPass operator[](size_t index) { + if (index >= data.size()) + return nullptr; + + return data[index]; + } + + PEffectPass operator[](String const& name) { + for (size_t i = 0; i < data.size(); ++i) { + const auto& p = data[i]; + + if (p->Name() == name) + return p; + } + + return nullptr; + } + + public: + std::vector data; + }; + using PEffectPassCollection = sptr; + + class EffectTechnique { + public: + PEffectAnnotationCollection Annotations() const; + String Name() const; + PEffectPassCollection Passes() const; + + public: + struct PlatformImplementation; + uptr impl; + + public: + EffectTechnique(); + }; + using PEffectTechnique = sptr; + + class EffectParameterCollection; + + class EffectParameter { + public: + //Gets the collection of EffectAnnotation objects for this parameter. + PEffectAnnotationCollection Annotations() const; + //Gets the number of columns in the parameter description. + Int ColumnCount() const; + //Gets the number of rows in the parameter description. + Int RowCount() const; + //Gets the semantic meaning, or usage, of the parameter. + String Semantic() const; + //Gets the type of the parameter. + EffectParameterType ParameterType() const; + //Gets the class of the parameter. + EffectParameterClass ParameterClass() const; + //Gets the name of the parameter. + String Name() const; + //Gets the collection of effect parameters. + sptr Elements() const; + //Gets the collection of structure members. + sptr StructureMembers() const; + + bool GetValueBoolean() const; + std::vector GetValueBooleanArray(size_t count) const; + Int GetValueInt32() const; + std::vector GetValueInt32Array(size_t count) const; + Matrix GetValueMatrix() const; + std::vector GetValueMatrixArray(size_t count) const; + Matrix GetValueMatrixTranspose() const; + std::vector GetValueMatrixTransposeArray(size_t count) const; + Quaternion GetValueQuaternion() const; + std::vector GetValueQuaternionArray() const; + float GetValueSingle() const; + std::vector GetValueSingleArray() const; + String GetValueString() const; + sptr GetValueTexture2D() const; + sptr GetValueTexture3D() const; + sptr GetValueTextureCube() const; + Vector2 GetValueVector2() const; + std::vector GetValueVector2Array() const; + Vector3 GetValueVector3() const; + std::vector GetValueVector3Array() const; + Vector4 GetValueVector4() const; + std::vector GetValueVector4Array() const; + + void SetValue(bool value); + void SetValue(std::vector const& value); + void SetValue(Int value); + void SetValue(std::vector const& value); + void SetValue(float value); + void SetValue(std::vector const& value); + void SetValue(Matrix const& value); + void SetValue(std::vector const& value); + void SetValue(Quaternion const& value); + void SetValue(std::vector const& value); + void SetValue(Vector2 const& value); + void SetValue(std::vector const& value); + void SetValue(Vector3 const& value); + void SetValue(std::vector const& value); + void SetValue(Vector4 const& value); + void SetValue(std::vector const& value); + void SetValue(String const& value); + void SetValue(sptr const& value); + + void SetValueTranspose(Matrix const& value); + void SetValueTranspose(std::vector const& value); + + public: + struct PlatformImplementation; + uptr impl; + + public: + EffectParameter(); + }; + using PEffectParameter = sptr; + + class EffectParameterCollection { + public: + EffectParameterCollection() {} + + EffectParameterCollection(std::vector const& data) : data(data) + { + } + + constexpr size_t Count() const { + return data.size(); + } + + PEffectParameter operator[](size_t index) { + if (index >= data.size()) + return nullptr; + + return data[index]; + } + + PEffectParameter operator[](String const& name) { + for (size_t i = 0; i < data.size(); ++i) { + const auto& p = data[i]; + + if (p->Name() == name) + return p; + } + + return nullptr; + } + + public: + std::vector data; + }; + using PEffectPassCollection = sptr; + + class Effect : public GraphicsResource { + Effect(sptr const& device, std::vector const& effectCode); + + PEffectTechnique CurrentTechnique() const; + + public: + struct PlatformImplementation; + uptr impl; + }; + + class IEffectMatrices { + virtual Matrix World() const = 0; + virtual Matrix View() const = 0; + virtual Matrix Projection() const = 0; + + virtual void World(Matrix const& value) = 0; + virtual void View(Matrix const& value) = 0; + virtual void Projection(Matrix const& value) = 0; + }; + + class DirectionalLight; + + class IEffectLights { + virtual DirectionalLight DirectionalLight0() const = 0; + virtual DirectionalLight DirectionalLight1() const = 0; + virtual DirectionalLight DirectionalLight2() const = 0; + + virtual Vector3 AmbientLightColor() const = 0; + virtual void AmbientLightColor(Vector3 const& value) = 0; + + virtual bool LightingEnabled() const = 0; + virtual void LightingEnabled(bool value) = 0; + + virtual void EnableDefaultLighting() = 0; + }; + + class IEffectFog + { + virtual bool FogEnabled() const = 0; + virtual float FogStart() const = 0; + virtual float FogEnd() const = 0; + virtual Vector3 FogColor() const = 0; + + virtual void FogEnabled(bool value) const = 0; + virtual void FogStart(float value) const = 0; + virtual void FogEnd(float value) const = 0; + virtual void FogColor(Vector3 const& value) const = 0; + }; +} + +#endif \ No newline at end of file diff --git a/inc/xna/graphics/gresource.hpp b/inc/xna/graphics/gresource.hpp index 13e6e2a..0c02ab5 100644 --- a/inc/xna/graphics/gresource.hpp +++ b/inc/xna/graphics/gresource.hpp @@ -4,20 +4,17 @@ #include "../default.hpp" namespace xna { + //Queries and prepares resources. class GraphicsResource { public: - GraphicsResource(sptr const& device) : m_device(device){} + GraphicsResource(sptr const& device); virtual ~GraphicsResource(){} - virtual bool Bind(sptr const& device) { - if (!device || device == m_device) - return false; + virtual bool Bind(sptr const& device); - m_device = device; - - return true; - } + //Gets the GraphicsDevice associated with this GraphicsResource. + sptr Device() const; protected: sptr m_device = nullptr; diff --git a/inc/xna/graphics/rasterizerstate.hpp b/inc/xna/graphics/rasterizerstate.hpp index da861b9..a04f55e 100644 --- a/inc/xna/graphics/rasterizerstate.hpp +++ b/inc/xna/graphics/rasterizerstate.hpp @@ -5,26 +5,61 @@ #include "gresource.hpp" namespace xna { - class RasterizerState : GraphicsResource { + //Contains rasterizer state, which determines how to convert vector data (shapes) into raster data (pixels). + class RasterizerState : public GraphicsResource { public: RasterizerState(); RasterizerState(sptr const& device); - ~RasterizerState() override; - bool Initialize(xna_error_nullarg); - bool Apply(xna_error_nullarg); + + //Specifies the conditions for culling or removing triangles. The default value is CullMode.CounterClockwise. xna::CullMode CullMode() const; + //Specifies the conditions for culling or removing triangles. The default value is CullMode.CounterClockwise. void CullMode(xna::CullMode value); + //The fill mode, which defines how a triangle is filled during rendering. The default is FillMode.Solid. xna::FillMode FillMode() const; + //The fill mode, which defines how a triangle is filled during rendering. The default is FillMode.Solid. void FillMode(xna::FillMode value); + //Enables or disables multisample antialiasing. The default is true. + bool MultiSampleAntiAlias() const; + //Enables or disables multisample antialiasing. The default is true. + void MultiSampleAntiAlias(bool value); + + //Sets or retrieves the depth bias for polygons, which is the amount of bias to apply to the depth of a primitive + //to alleviate depth testing problems for primitives of similar depth. The default value is 0. + float DepthBias() const; + //Sets or retrieves the depth bias for polygons, which is the amount of bias to apply to the depth of a primitive + //to alleviate depth testing problems for primitives of similar depth. The default value is 0. + void DepthBias(float value); + + //Gets or sets a bias value that takes into account the slope of a polygon. This bias value is applied to coplanar primitives + // to reduce aliasing and other rendering artifacts caused by z-fighting. The default is 0. + float SlopeScaleDepthBias() const; + //Gets or sets a bias value that takes into account the slope of a polygon. This bias value is applied to coplanar primitives + // to reduce aliasing and other rendering artifacts caused by z-fighting. The default is 0. + void SlopeScaleDepthBias(float value); + + //Enables or disables scissor testing. The default is false. + bool ScissorTestEnable() const; + //Enables or disables scissor testing. The default is false. + void ScissorTestEnable(bool value); + + //A built-in state object with settings for not culling any primitives. static uptr CullNone(); + //A built-in state object with settings for culling primitives with clockwise winding order. static uptr CullClockwise(); + //A built-in state object with settings for culling primitives with counter-clockwise winding order. static uptr CullCounterClockwise(); + bool Initialize(); + bool Apply(); + public: struct PlatformImplementation; uptr impl = nullptr; }; + + using PRasterizerState = sptr; } #endif \ No newline at end of file diff --git a/inc/xna/graphics/rendertarget.hpp b/inc/xna/graphics/rendertarget.hpp index 1a41f3d..5c4adc7 100644 --- a/inc/xna/graphics/rendertarget.hpp +++ b/inc/xna/graphics/rendertarget.hpp @@ -11,8 +11,8 @@ namespace xna { RenderTarget2D(sptr const& device); ~RenderTarget2D() override; - bool Initialize(xna_error_nullarg); - bool Apply(xna_error_nullarg); + bool Initialize(); + bool Apply(); public: struct PlatformImplementation; diff --git a/inc/xna/graphics/samplerstate.hpp b/inc/xna/graphics/samplerstate.hpp index a959bdd..7a4aed6 100644 --- a/inc/xna/graphics/samplerstate.hpp +++ b/inc/xna/graphics/samplerstate.hpp @@ -5,43 +5,97 @@ #include "gresource.hpp" namespace xna { - class SamplerState : GraphicsResource { + //Contains sampler state, which determines how to sample texture data. + class SamplerState : public GraphicsResource { public: SamplerState(); SamplerState(sptr const& device); - ~SamplerState() override; - bool Initialize(xna_error_nullarg); - bool Apply(xna_error_nullarg); - void Filter(TextureFilter value); - void AddressU(TextureAddressMode value); - void AddressV(TextureAddressMode value); - void AddressW(TextureAddressMode value); - void Comparison(ComparisonFunction value); - void MipLODBias(float value); - void MinLOD(float value); - void MaxLOD(float value); + + //Gets or sets the maximum anisotropy. The default value is 0. void MaxAnisotropy(Uint value); - TextureFilter Filter() const; - TextureAddressMode AddressU() const; - TextureAddressMode AddressV() const; - TextureAddressMode AddressW() const; - ComparisonFunction Comparison() const; - float MipLODBias() const; - float MinLOD() const; - float MaxLOD() const; + //Gets or sets the maximum anisotropy. The default value is 0. Uint MaxAnisotropy() const; + //Gets or sets the type of filtering during sampling. + void Filter(TextureFilter value); + //Gets or sets the type of filtering during sampling. + TextureFilter Filter() const; + ////Gets or sets the texture-address mode for the u-coordinate. + void AddressU(TextureAddressMode value); + //Gets or sets the texture-address mode for the u-coordinate. + TextureAddressMode AddressU() const; + //Gets or sets the texture-address mode for the v-coordinate. + TextureAddressMode AddressV() const; + //Gets or sets the texture-address mode for the v-coordinate. + void AddressV(TextureAddressMode value); + //Gets or sets the texture-address mode for the w-coordinate. + TextureAddressMode AddressW() const; + ////Gets or sets the texture-address mode for the w-coordinate. + void AddressW(TextureAddressMode value); + //Gets or sets the mipmap LOD bias. The default value is 0. + void MipMapLevelOfDetailBias(float value); + //Gets or sets the mipmap LOD bias. The default value is 0. + float MipMapLevelOfDetailBias() const; + + //Gets or sets the level of detail (LOD) index of the largest map to use. + float MaxMipLevel() const; + //Gets or sets the level of detail (LOD) index of the largest map to use. + void MaxMipLevel(float value); + + //Gets or sets the level of detail (LOD) index of the smaller map to use. + void MinMipLevel(float value); + //Gets or sets the level of detail (LOD) index of the smaller map to use. + float MinMipLevel() const; + + //Contains default state for point filtering and texture coordinate wrapping. static uptr PoinWrap(); + //Contains default state for point filtering and texture coordinate clamping. static uptr PointClamp(); + //Contains default state for linear filtering and texture coordinate wrapping. static uptr LinearWrap(); + //Contains default state for linear filtering and texture coordinate clamping. static uptr LinearClamp(); + //Contains default state for anisotropic filtering and texture coordinate wrapping. static uptr AnisotropicWrap(); + //Contains default state for anisotropic filtering and texture coordinate clamping. static uptr AnisotropicClamp(); + ComparisonFunction Comparison() const; + void Comparison(ComparisonFunction value); + + bool Initialize(); + bool Apply(); + public: struct PlatformImplementation; uptr impl = nullptr; }; + + using PSamplerState = sptr; + + //Collection of SamplerState objects. + class SamplerStateCollection { + public: + SamplerStateCollection(){} + + SamplerStateCollection(size_t size) + : samplers(size){} + + SamplerStateCollection(std::vector const& samplers) + : samplers(samplers) {} + + PSamplerState operator[](size_t index) { + if (index >= samplers.size()) + return nullptr; + + return samplers[index]; + } + + public: + std::vector samplers; + }; + + using PSamplerStateCollection = sptr; } #endif \ No newline at end of file diff --git a/inc/xna/graphics/shader.hpp b/inc/xna/graphics/shader.hpp index 3ec1733..158eb19 100644 --- a/inc/xna/graphics/shader.hpp +++ b/inc/xna/graphics/shader.hpp @@ -10,7 +10,7 @@ namespace xna { Shader(); Shader(sptr const& device); ~Shader() override {} - bool Initialize(DataBuffer& buffer, xna_error_nullarg); + bool Initialize(DataBuffer& buffer); static bool CompileFromFile(WString srcFile, String entryPoint, String profile, DataBuffer& blob); }; @@ -19,7 +19,7 @@ namespace xna { VertexShader(); VertexShader(sptr const& device); ~VertexShader() override; - bool Initialize(DataBuffer& buffer, xna_error_nullarg); + bool Initialize(DataBuffer& buffer); public: struct PlatformImplementation; @@ -31,7 +31,7 @@ namespace xna { PixelShader(); PixelShader(sptr const& device); ~PixelShader() override; - bool Initialize(DataBuffer& buffer, xna_error_nullarg); + bool Initialize(DataBuffer& buffer); public: struct PlatformImplementation; diff --git a/inc/xna/graphics/sprite.hpp b/inc/xna/graphics/sprite.hpp index 039733b..38d6dbd 100644 --- a/inc/xna/graphics/sprite.hpp +++ b/inc/xna/graphics/sprite.hpp @@ -5,12 +5,15 @@ #include "../common/numerics.hpp" #include "../common/color.hpp" #include +#include "../graphics/gresource.hpp" namespace xna { - class SpriteBatch { + //Enables a group of sprites to be drawn using the same settings. + class SpriteBatch : public GraphicsResource { public: - SpriteBatch(GraphicsDevice& device); - ~SpriteBatch(); + SpriteBatch(sptr const& device); + + //Begins a sprite batch operation. void Begin( SpriteSortMode sortMode = SpriteSortMode::Deferred, BlendState* blendState = nullptr, @@ -20,67 +23,74 @@ namespace xna { //Effect Matrix const& transformMatrix = Matrix::Identity() ); + + //Flushes the sprite batch and restores the device state to how it was before Begin was called. void End(); - void Draw(sptr const& texture, Vector2 const& position, Color const& color) { - Draw(*texture, position, color); - } + + // + // Draw - Adds a sprite to a batch of sprites to be rendered. + // + + void Draw(uptr const& texture, Vector2 const& position, Color const& color) { Draw(*texture, position, color); } + void Draw(sptr const& texture, Vector2 const& position, Color const& color) { Draw(*texture, position, color); } void Draw(Texture2D& texture, Vector2 const& position, Color const& color); - void Draw(sptr const& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color) { - Draw(*texture, position, sourceRectangle, color); - } - void Draw(Texture2D& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color); + void Draw(uptr const& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color) { Draw(*texture, position, sourceRectangle, color); } + void Draw(sptr const& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color) { Draw(*texture, position, sourceRectangle, color); } + void Draw(Texture2D& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color); - void Draw(sptr const& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color, - float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth) { - Draw(*texture, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth); - } - void Draw(Texture2D& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color, + void Draw(uptr const& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color, + float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth) { Draw(*texture, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth); } + void Draw(sptr const& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color, + float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth) { Draw(*texture, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth); } + void Draw(Texture2D& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color, float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth); - void Draw(sptr const& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color, - float rotation, Vector2 const& origin, Vector2 const& scale, SpriteEffects effects, float layerDepth) { - Draw(*texture, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth); - } - void Draw(Texture2D& texture, Vector2 const& position, Rectangle const* sourceRectangle, Color const& color, + void Draw(uptr const& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color, + float rotation, Vector2 const& origin, Vector2 const& scale, SpriteEffects effects, float layerDepth) { Draw(*texture, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth); } + void Draw(sptr const& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color, + float rotation, Vector2 const& origin, Vector2 const& scale, SpriteEffects effects, float layerDepth) { Draw(*texture, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth); } + void Draw(Texture2D& texture, Vector2 const& position, std::optional const& sourceRectangle, Color const& color, float rotation, Vector2 const& origin, Vector2 const& scale, SpriteEffects effects, float layerDepth); - void Draw(sptr const& texture, Rectangle const& destinationRectangle, Color const& color) { - Draw(*texture, destinationRectangle, color); - } + void Draw(uptr const& texture, Rectangle const& destinationRectangle, Color const& color) { Draw(*texture, destinationRectangle, color); } + void Draw(sptr const& texture, Rectangle const& destinationRectangle, Color const& color) { Draw(*texture, destinationRectangle, color); } void Draw(Texture2D& texture, Rectangle const& destinationRectangle, Color const& color); - void Draw(sptr const& texture, Rectangle const& destinationRectangle, Rectangle const* sourceRectangle, Color const& color) { - Draw(*texture, destinationRectangle, sourceRectangle, color); - } - void Draw(Texture2D& texture, Rectangle const& destinationRectangle, Rectangle const* sourceRectangle, Color const& color); + void Draw(uptr const& texture, Rectangle const& destinationRectangle, std::optional const& sourceRectangle, Color const& color) { Draw(*texture, destinationRectangle, sourceRectangle, color); } + void Draw(sptr const& texture, Rectangle const& destinationRectangle, std::optional const& sourceRectangle, Color const& color) { Draw(*texture, destinationRectangle, sourceRectangle, color); } + void Draw(Texture2D& texture, Rectangle const& destinationRectangle, std::optional const& sourceRectangle, Color const& color); - void Draw(sptr const& texture, Rectangle const& destinationRectangle, Rectangle const* sourceRectangle, Color const& color, - float rotation, Vector2 const& origin, SpriteEffects effects, float layerDepth) { - Draw(*texture, destinationRectangle, sourceRectangle, color, rotation, origin, effects, layerDepth); - } - void Draw(Texture2D& texture, Rectangle const& destinationRectangle, Rectangle const* sourceRectangle, Color const& color, - float rotation, Vector2 const& origin, SpriteEffects effects, float layerDepth); + void Draw(uptr const& texture, Rectangle const& destinationRectangle, std::optional const& sourceRectangle, Color const& color, + float rotation, Vector2 const& origin, SpriteEffects effects, float layerDepth) { Draw(*texture, destinationRectangle, sourceRectangle, color, rotation, origin, effects, layerDepth); } + void Draw(sptr const& texture, Rectangle const& destinationRectangle, std::optional const& sourceRectangle, Color const& color, + float rotation, Vector2 const& origin, SpriteEffects effects, float layerDepth) { Draw(*texture, destinationRectangle, sourceRectangle, color, rotation, origin, effects, layerDepth); } + void Draw(Texture2D& texture, Rectangle const& destinationRectangle, std::optional const& sourceRectangle, Color const& color, + float rotation, Vector2 const& origin, SpriteEffects effects, float layerDepth); - void Viewport(xna::Viewport const& value); + // + // DrawString - Adds a string to a batch of sprites to be rendered. + // - void DrawString(sptr const& spriteFont, String const& text, Vector2 const& position, Color const& color) { - DrawString(*spriteFont, text, position, color); - } + void DrawString(uptr const& spriteFont, String const& text, Vector2 const& position, Color const& color) { DrawString(*spriteFont, text, position, color); } + void DrawString(sptr const& spriteFont, String const& text, Vector2 const& position, Color const& color) { DrawString(*spriteFont, text, position, color); } void DrawString(SpriteFont& spriteFont, String const& text, Vector2 const& position, Color const& color); + void DrawString(uptr const& spriteFont, String const& text, Vector2 const& position, Color const& color, + float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth) { DrawString(*spriteFont, text, position, color, rotation, origin, scale, effects, layerDepth); } void DrawString(sptr const& spriteFont, String const& text, Vector2 const& position, Color const& color, - float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth) { - DrawString(*spriteFont, text, position, color, rotation, origin, scale, effects, layerDepth); - } + float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth) { DrawString(*spriteFont, text, position, color, rotation, origin, scale, effects, layerDepth); } void DrawString(SpriteFont& spriteFont, String const& text, Vector2 const& position, Color const& color, float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth); + void Viewport(xna::Viewport const& value); + public: struct PlatformImplementation; uptr implementation = nullptr; }; + //Represents a font texture. class SpriteFont { public: SpriteFont( @@ -91,20 +101,21 @@ namespace xna { Int lineSpacing, float spacing, std::vector const& kerning, - std::optional defaultCharacter); - ~SpriteFont(); + std::optional const& defaultCharacter); + + // Returns the width and height of a string. Vector2 MeasureString(String const& text, bool ignoreWhiteSpace = true); - Vector2 MeasureString(WString const& text, bool ignoreWhiteSpace = true); + // Returns the width and height of a string. + Vector2 MeasureString(WString const& text, bool ignoreWhiteSpace = true); - private: - sptr textureValue = nullptr; - std::vector glyphData; - std::vector croppingData; - std::vector characterMap; - Int lineSpacing{0}; - float spacing{0}; - std::vector kerning; - std::optional defaultCharacter; + //Gets or sets the default character for the font. + Char DefaultCharacter() const; + //Gets or sets the default character for the font. + void DefaultCharacter(Char value); + //Gets or sets the vertical distance (in pixels) between the base lines of two consecutive lines of text + Int LineSpacing() const; + //Gets or sets the vertical distance (in pixels) between the base lines of two consecutive lines of text + void LineSpacing(Int value); public: struct PlatformImplementation; diff --git a/inc/xna/graphics/swapchain.hpp b/inc/xna/graphics/swapchain.hpp index bb4d5f1..2674027 100644 --- a/inc/xna/graphics/swapchain.hpp +++ b/inc/xna/graphics/swapchain.hpp @@ -10,7 +10,7 @@ namespace xna { SwapChain(); SwapChain(sptr const& device); ~SwapChain() override; - bool Initialize(xna_error_nullarg); + bool Initialize(); bool Present(bool vsync); bool GetBackBuffer(Texture2D& texture2D); public: diff --git a/inc/xna/graphics/texture.hpp b/inc/xna/graphics/texture.hpp index baea647..e5afae4 100644 --- a/inc/xna/graphics/texture.hpp +++ b/inc/xna/graphics/texture.hpp @@ -20,13 +20,13 @@ namespace xna { Int Width() const; Int Height() const; Rectangle Bounds() const; - bool Initialize(xna_error_nullarg); - void SetData(std::vector const& data, size_t startIndex = 0, size_t elementCount = 0, xna_error_nullarg); - void SetData(std::vector const& data, size_t startIndex = 0, size_t elementCount = 0, xna_error_nullarg); - void SetData(std::vector const& data, size_t startIndex = 0, size_t elementCount = 0, xna_error_nullarg); - void SetData(Int level, Rectangle* rect, std::vector const& data, size_t startIndex, size_t elementCount, xna_error_nullarg); - static sptr FromStream(GraphicsDevice& device, String const& fileName, xna_error_nullarg); - static sptr FromMemory(GraphicsDevice& device, std::vector const& data, xna_error_nullarg); + bool Initialize(); + void SetData(std::vector const& data, size_t startIndex = 0, size_t elementCount = 0); + void SetData(std::vector const& data, size_t startIndex = 0, size_t elementCount = 0); + void SetData(std::vector const& data, size_t startIndex = 0, size_t elementCount = 0); + void SetData(Int level, Rectangle* rect, std::vector const& data, size_t startIndex, size_t elementCount); + static sptr FromStream(GraphicsDevice& device, String const& fileName); + static sptr FromMemory(GraphicsDevice& device, std::vector const& data); public: struct PlatformImplementation; diff --git a/inc/xna/helpers.hpp b/inc/xna/helpers.hpp index 20b509b..b14afec 100644 --- a/inc/xna/helpers.hpp +++ b/inc/xna/helpers.hpp @@ -3,13 +3,20 @@ #include #include -#include +#include "exception.hpp" namespace xna { + //Class for helper functions struct XnaHelper { + + // + // Smart Pointer Comparator + // + template struct is_shared_ptr : std::false_type {}; template struct is_shared_ptr> : std::true_type {}; + //Convert a string to wstring static inline std::wstring ToWString(const std::string& str) { std::wstring wstr; @@ -19,6 +26,7 @@ namespace xna { return wstr; } + //Convert a wstring to string static inline std::string ToString(const std::wstring& wstr) { std::string str; @@ -28,20 +36,23 @@ namespace xna { return str; } + //Returns a hash reporting input values template static constexpr void HashCombine(std::size_t& seed, const T& v) { std::hash hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } + //Returns null if the type is a smart pointer or default value if the type has a default constructor. + //Throws an exception if the object cannot be created template - static inline auto ReturnDefaultOrNull() { + static inline auto ReturnDefaultOrNull(const std::source_location location = std::source_location::current()) { if constexpr (is_shared_ptr::value) return (T)nullptr; else if (std::is_default_constructible::value) return T(); else - throw std::runtime_error("Unable to build object"); + Exception::Throw(ExMessage::BuildObject, location); } }; } diff --git a/inc/xna/input/gamepad.hpp b/inc/xna/input/gamepad.hpp index f77ca95..9e52515 100644 --- a/inc/xna/input/gamepad.hpp +++ b/inc/xna/input/gamepad.hpp @@ -5,6 +5,7 @@ #include "../common/numerics.hpp" namespace xna { + //Structure that defines the position of the left and right triggers on an Xbox Controller. struct GamePadTriggers { constexpr GamePadTriggers() = default; @@ -37,6 +38,7 @@ namespace xna { } }; + //Structure that represents the position of left and right sticks (thumbsticks) on an Xbox Controller. struct GamePadThumbSticks { constexpr GamePadThumbSticks() = default; @@ -69,6 +71,7 @@ namespace xna { } }; + //Identifies which directions on the directional pad of an Xbox Controller are being pressed. struct GamePadDPad { constexpr GamePadDPad() = default; @@ -83,6 +86,7 @@ namespace xna { ButtonState Left{}; }; + //Identifies whether buttons on an Xbox Controller are pressed or released. struct GamePadButtons { constexpr GamePadButtons() = default; @@ -146,6 +150,7 @@ namespace xna { using GamePadId = uint64_t; #endif + //Describes the capabilities of an Xbox Controller, including controller type, and identifies if the controller supports voice. struct GamePadCapabilities { constexpr GamePadCapabilities() = default; @@ -156,6 +161,7 @@ namespace xna { GamePadId Id{}; }; + //Represents specific information about the state of an Xbox Controller, including the current state of buttons and sticks. struct GamePadState { constexpr GamePadState() = default; @@ -229,22 +235,30 @@ namespace xna { GamePadTriggers Triggers{}; }; + //Allows retrieval of user interaction with an Xbox Controller and setting of controller vibration motors. class GamePad { public: + //Gets the current state of a game pad controller. As an option, it specifies a dead zone processing method for the analog sticks. static GamePadState GetState(PlayerIndex index); + //Gets the current state of a game pad controller. As an option, it specifies a dead zone processing method for the analog sticks. static GamePadState GetState(PlayerIndex index, GamePadDeadZone deadZone); + + //Retrieves the capabilities of an Xbox 360 Controller. static GamePadCapabilities GetCapabilities(PlayerIndex index); + //Sets the vibration motor speeds on an Xbox 360 Controller. static bool SetVibration(PlayerIndex index, float leftMotor, float rightMotor, float leftTrigger = 0, float rightTrigger = 0); + + GamePad() = delete; + GamePad(GamePad&) = delete; + GamePad(GamePad&&) = delete; + + private: + friend class Game; static void Initialize(); public: struct PlatformImplementation; - inline static uptr impl = nullptr; - - private: - GamePad(); - GamePad(GamePad&&); - GamePad(GamePad&); + inline static uptr impl = nullptr; }; } diff --git a/inc/xna/input/keyboard.hpp b/inc/xna/input/keyboard.hpp index 152c1ed..7957664 100644 --- a/inc/xna/input/keyboard.hpp +++ b/inc/xna/input/keyboard.hpp @@ -4,9 +4,13 @@ #include "../default.hpp" namespace xna { + //Represents a state of keystrokes recorded by a keyboard input device. struct KeyboardState { + // + //same implementation of the DirectX::Keyboard::State structure + // public: - bool IsKeyDown(Keys key) const { + constexpr bool IsKeyDown(Keys key) const { const auto k = static_cast(key); if (k <= 0xfe) @@ -18,7 +22,7 @@ namespace xna { return false; } - bool IsKeyUp(Keys key) const { + constexpr bool IsKeyUp(Keys key) const { return !IsKeyDown(key); } @@ -210,13 +214,21 @@ namespace xna { bool Reserved26 : 1; }; + //Allows retrieval of keystrokes from a keyboard input device. class Keyboard { public: + //Returns the current keyboard or Chatpad state. static KeyboardState GetState(); - //static bool IsConnected(); - static void Initialize(); static bool IsConnected(); + Keyboard() = delete; + Keyboard(Keyboard&) = delete; + Keyboard(Keyboard&&) = delete; + + private: + friend class Game; + static void Initialize(); + public: struct PlatformImplementation; inline static uptr impl = nullptr; diff --git a/inc/xna/input/mouse.hpp b/inc/xna/input/mouse.hpp index 940969d..2f8277f 100644 --- a/inc/xna/input/mouse.hpp +++ b/inc/xna/input/mouse.hpp @@ -15,19 +15,28 @@ namespace xna { int ScroolWheelValue{ 0 }; }; + //Allows retrieval of position and button clicks from a mouse input device. class Mouse { public: + //Gets the current state of the mouse, including mouse position and buttons pressed. static MouseState GetState(); + static bool IsConnected(); static bool IsVisible(); static void IsVisible(bool value); - static void ResetScrollWheel(); + static void ResetScrollWheel(); + Mouse() = delete; + Mouse(Mouse&) = delete; + Mouse(Mouse&&) = delete; + + private: + friend class Game; static void Initialize(); public: struct PlatformImplementation; - inline static uptr impl = nullptr; + inline static uptr impl = nullptr; }; } diff --git a/inc/xna/platform-dx/dx.hpp b/inc/xna/platform-dx/dx.hpp new file mode 100644 index 0000000..ce86e07 --- /dev/null +++ b/inc/xna/platform-dx/dx.hpp @@ -0,0 +1,1120 @@ +#ifndef XNA_PLATFORMDX_DX_HPP +#define XNA_PLATFORMDX_DX_HPP + +//--------------------------------// +// DX INCLUDES +//--------------------------------// + +//DirectX +#if defined(_XBOX_ONE) && defined(_TITLE) +#include +#define NO_D3D11_DEBUG_NAME +#endif +#include "dxgi.h" +#include "d3d11.h" +#include +#include +//HSLS AND EFFECTS +#include +#include +#include "effects11/d3dx11effect.h" +//DirectXTK +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//Windows +#define NOMINMAX +#include +#include +#include +#include +#include + +//--------------------------------// +// USINGS +//--------------------------------// + +template +using comptr = Microsoft::WRL::ComPtr; + +//--------------------------------// +// OTHERS INCLUDES +//--------------------------------// + +#include "../default.hpp" +#include "../exception.hpp" +#include "../graphics/blendstate.hpp" +#include "../graphics/adapter.hpp" +#include "../graphics/device.hpp" +#include "../graphics/adapter.hpp" +#include "../graphics/blendstate.hpp" +#include "../graphics/buffer.hpp" +#include "../graphics/depthstencilstate.hpp" +#include "../graphics/displaymode.hpp" +#include "../graphics/sprite.hpp" +#include "../graphics/effect.hpp" +#include "../graphics/samplerstate.hpp" +#include "../input/gamepad.hpp" +#include "../input/keyboard.hpp" +#include "../input/mouse.hpp" +#include "../graphics/rasterizerstate.hpp" +#include "../graphics/presentparams.hpp" +#include "../graphics/shader.hpp" +#include "../graphics/swapchain.hpp" +#include "../graphics/texture.hpp" +#include "../graphics/rendertarget.hpp" +#include "../game/window.hpp" +#include "../audio/audioengine.hpp" +#include "../audio/soundeffect.hpp" +#include "../graphics/viewport.hpp" +#include "../common/color.hpp" +#include "../game/game.hpp" +#include +#include +#include + +//--------------------------------// +// CLASSES +//--------------------------------// + +namespace xna { + //==============================================// + //================ DXHELPERS ================// + //==============================================// + + struct DxHelpers { + static constexpr void SpriteSortToDx(SpriteSortMode value, DirectX::SpriteSortMode& target) { + target = static_cast(static_cast(value)); + } + + static constexpr DXGI_FORMAT SurfaceFormatToDx(SurfaceFormat format) + { + switch (format) + { + case SurfaceFormat::Color://21 + return DXGI_FORMAT_R8G8B8A8_UNORM; + case SurfaceFormat::Bgr565: //23 + return DXGI_FORMAT_B5G6R5_UNORM; + case SurfaceFormat::Bgra5551://25 + return DXGI_FORMAT_B5G5R5A1_UNORM; + case SurfaceFormat::Bgra4444://26 + return DXGI_FORMAT_B4G4R4A4_UNORM; + case SurfaceFormat::Dxt1://827611204 + return DXGI_FORMAT_BC1_UNORM; + case SurfaceFormat::Dxt3://861165636 + return DXGI_FORMAT_BC2_UNORM; + case SurfaceFormat::Dxt5://894720068 + return DXGI_FORMAT_BC3_UNORM; + case SurfaceFormat::NormalizedByte2://60 + return DXGI_FORMAT_R8G8_SNORM; + case SurfaceFormat::NormalizedByte4://63 + return DXGI_FORMAT_R8G8B8A8_SNORM; + case SurfaceFormat::Rgba1010102://31 + return DXGI_FORMAT_R10G10B10A2_UNORM; + case SurfaceFormat::Rg32://34 + return DXGI_FORMAT_R16G16_UNORM; + case SurfaceFormat::Rgba64://36 + return DXGI_FORMAT_R16G16B16A16_UNORM; + case SurfaceFormat::Alpha8://28 + return DXGI_FORMAT_A8_UNORM; + case SurfaceFormat::Single://114 + return DXGI_FORMAT_R32_FLOAT; + case SurfaceFormat::Vector2://115 + return DXGI_FORMAT_R32G32_FLOAT; + case SurfaceFormat::Vector4://116 + return DXGI_FORMAT_R32G32B32A32_FLOAT; + case SurfaceFormat::HalfSingle://111 + return DXGI_FORMAT_R16_FLOAT; + case SurfaceFormat::HalfVector2://112 + return DXGI_FORMAT_R16G16_FLOAT; + case SurfaceFormat::HalfVector4://113 + return DXGI_FORMAT_R16G16B16A16_FLOAT; + case SurfaceFormat::HdrBlendable://113 + return DXGI_FORMAT_R16G16B16A16_FLOAT; + default://0 + return DXGI_FORMAT_UNKNOWN; + } + } + + static constexpr SurfaceFormat ConvertDXGIFORMATToSurface(DXGI_FORMAT format) { + switch (format) + { + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: + return SurfaceFormat::Color; + case DXGI_FORMAT_B5G6R5_UNORM: + return SurfaceFormat::Bgr565; + case DXGI_FORMAT_B5G5R5A1_UNORM: + return SurfaceFormat::Bgra5551; + case DXGI_FORMAT_B4G4R4A4_UNORM: + return SurfaceFormat::Bgra4444; + case DXGI_FORMAT_BC2_UNORM: + return SurfaceFormat::Dxt3; + case DXGI_FORMAT_BC3_UNORM: + return SurfaceFormat::Dxt5; + case DXGI_FORMAT_R8G8_SNORM: + return SurfaceFormat::NormalizedByte2; + case DXGI_FORMAT_R8G8B8A8_SNORM: + return SurfaceFormat::NormalizedByte4; + case DXGI_FORMAT_R10G10B10A2_UNORM: + return SurfaceFormat::Rgba1010102; + case DXGI_FORMAT_R16G16_UNORM: + return SurfaceFormat::Rg32; + case DXGI_FORMAT_R16G16B16A16_UNORM: + return SurfaceFormat::Rgba64; + case DXGI_FORMAT_A8_UNORM: + return SurfaceFormat::Alpha8; + case DXGI_FORMAT_R32_FLOAT: + return SurfaceFormat::Single; + case DXGI_FORMAT_R32G32_FLOAT: + return SurfaceFormat::Vector2; + case DXGI_FORMAT_R32G32B32A32_FLOAT: + return SurfaceFormat::Vector4; + case DXGI_FORMAT_R16_FLOAT: + return SurfaceFormat::HalfSingle; + case DXGI_FORMAT_R16G16_FLOAT: + return SurfaceFormat::HalfVector2; + case DXGI_FORMAT_R16G16B16A16_FLOAT: + return SurfaceFormat::HalfVector4; + default: + return SurfaceFormat::Unknown; + } + } + + static constexpr Blend ConvertBlendDx(D3D11_BLEND blend) { + switch (blend) { + case D3D11_BLEND_ZERO: + return Blend::Zero; + case D3D11_BLEND_ONE: + return Blend::One; + case D3D11_BLEND_SRC_COLOR: + return Blend::SourceColor; + case D3D11_BLEND_INV_SRC_COLOR: + return Blend::InverseSourceColor; + case D3D11_BLEND_SRC_ALPHA: + return Blend::SourceAlpha; + case D3D11_BLEND_INV_SRC_ALPHA: + return Blend::InverseSourceAlpha; + case D3D11_BLEND_DEST_ALPHA: + return Blend::DestinationAlpha; + case D3D11_BLEND_INV_DEST_ALPHA: + return Blend::InverseDestinationAlpha; + case D3D11_BLEND_DEST_COLOR: + return Blend::DestinationColor; + case D3D11_BLEND_INV_DEST_COLOR: + return Blend::InverseDestinationColor; + case D3D11_BLEND_SRC_ALPHA_SAT: + return Blend::SourceAlphaSaturation; + case D3D11_BLEND_BLEND_FACTOR: + return Blend::BlendFactor; + case D3D11_BLEND_INV_BLEND_FACTOR: + return Blend::InverseBlendFactor; + case D3D11_BLEND_SRC1_COLOR: + return Blend::Source1Color; + case D3D11_BLEND_INV_SRC1_COLOR: + return Blend::InverseSource1Color; + case D3D11_BLEND_SRC1_ALPHA: + return Blend::Source1Alpha; + case D3D11_BLEND_INV_SRC1_ALPHA: + return Blend::InverseSource1Alpha; + default: + return Blend::Zero; + } + } + + static constexpr D3D11_BLEND ConvertBlend(Blend blend) { + switch (blend) + { + case xna::Blend::Zero: + return D3D11_BLEND_ZERO; + case xna::Blend::One: + return D3D11_BLEND_ONE; + case xna::Blend::SourceColor: + return D3D11_BLEND_SRC_COLOR; + case xna::Blend::InverseSourceColor: + return D3D11_BLEND_INV_SRC_COLOR; + case xna::Blend::SourceAlpha: + return D3D11_BLEND_SRC_ALPHA; + case xna::Blend::InverseSourceAlpha: + return D3D11_BLEND_INV_SRC_ALPHA; + case xna::Blend::DestinationAlpha: + return D3D11_BLEND_DEST_ALPHA; + case xna::Blend::InverseDestinationAlpha: + return D3D11_BLEND_INV_DEST_ALPHA; + case xna::Blend::DestinationColor: + return D3D11_BLEND_DEST_COLOR; + case xna::Blend::InverseDestinationColor: + return D3D11_BLEND_INV_DEST_COLOR; + case xna::Blend::SourceAlphaSaturation: + return D3D11_BLEND_SRC_ALPHA_SAT; + case xna::Blend::BlendFactor: + return D3D11_BLEND_BLEND_FACTOR; + case xna::Blend::InverseBlendFactor: + return D3D11_BLEND_INV_BLEND_FACTOR; + case xna::Blend::Source1Color: + return D3D11_BLEND_SRC1_COLOR; + case xna::Blend::InverseSource1Color: + return D3D11_BLEND_INV_SRC1_COLOR; + case xna::Blend::Source1Alpha: + return D3D11_BLEND_SRC1_ALPHA; + case xna::Blend::InverseSource1Alpha: + return D3D11_BLEND_INV_SRC1_ALPHA; + default: + return D3D11_BLEND_ZERO; + } + } + + static constexpr D3D11_BLEND_OP ConvertOperation(BlendOperation op) { + return static_cast(static_cast(op) + 1); + } + + static constexpr BlendOperation ConvertOperationDx(D3D11_BLEND_OP op) { + return static_cast(static_cast(op) - 1); + } + + static constexpr D3D11_COLOR_WRITE_ENABLE ConvertColorWrite(ColorWriteChannels colorWrite) { + switch (colorWrite) + { + case xna::ColorWriteChannels::Red: + return D3D11_COLOR_WRITE_ENABLE_RED; + case xna::ColorWriteChannels::Green: + return D3D11_COLOR_WRITE_ENABLE_GREEN; + case xna::ColorWriteChannels::Blue: + return D3D11_COLOR_WRITE_ENABLE_BLUE; + case xna::ColorWriteChannels::Alpha: + return D3D11_COLOR_WRITE_ENABLE_ALPHA; + case xna::ColorWriteChannels::All: + return D3D11_COLOR_WRITE_ENABLE_ALL; + default: + return D3D11_COLOR_WRITE_ENABLE_ALL; + } + } + + static constexpr void ConvertAddressMode(TextureAddressMode value, D3D11_TEXTURE_ADDRESS_MODE& target) { + target = static_cast(static_cast(value) + 1); + } + + static constexpr void ConvertAddressMode(D3D11_TEXTURE_ADDRESS_MODE value, TextureAddressMode& target) { + target = static_cast(value - 1); + } + }; + + //==============================================// + //================ STEPTIMER ================// + //==============================================// + + // Helper class for animation and simulation timing. + class StepTimer + { + public: + StepTimer() noexcept(false) : + m_elapsedTicks(0), + m_totalTicks(0), + m_leftOverTicks(0), + m_frameCount(0), + m_framesPerSecond(0), + m_framesThisSecond(0), + m_qpcSecondCounter(0), + m_isFixedTimeStep(false), + m_targetElapsedTicks(TicksPerSecond / 60) + { + if (!QueryPerformanceFrequency(&m_qpcFrequency)) + { + throw std::exception(); + } + + if (!QueryPerformanceCounter(&m_qpcLastTime)) + { + throw std::exception(); + } + + // Initialize max delta to 1/10 of a second. + m_qpcMaxDelta = static_cast(m_qpcFrequency.QuadPart / 10); + } + + // Get elapsed time since the previous Update call. + uint64_t GetElapsedTicks() const noexcept { return m_elapsedTicks; } + double GetElapsedSeconds() const noexcept { return TicksToSeconds(m_elapsedTicks); } + + // Get total time since the start of the program. + uint64_t GetTotalTicks() const noexcept { return m_totalTicks; } + double GetTotalSeconds() const noexcept { return TicksToSeconds(m_totalTicks); } + + // Get total number of updates since start of the program. + uint32_t GetFrameCount() const noexcept { return m_frameCount; } + + // Get the current framerate. + uint32_t GetFramesPerSecond() const noexcept { return m_framesPerSecond; } + + // Set whether to use fixed or variable timestep mode. + void SetFixedTimeStep(bool isFixedTimestep) noexcept { m_isFixedTimeStep = isFixedTimestep; } + + // Set how often to call Update when in fixed timestep mode. + void SetTargetElapsedTicks(uint64_t targetElapsed) noexcept { m_targetElapsedTicks = targetElapsed; } + void SetTargetElapsedSeconds(double targetElapsed) noexcept { m_targetElapsedTicks = SecondsToTicks(targetElapsed); } + + // Integer format represents time using 10,000,000 ticks per second. + static constexpr uint64_t TicksPerSecond = 10000000; + + static constexpr double TicksToSeconds(uint64_t ticks) noexcept { return static_cast(ticks) / TicksPerSecond; } + static constexpr uint64_t SecondsToTicks(double seconds) noexcept { return static_cast(seconds * TicksPerSecond); } + + // After an intentional timing discontinuity (for instance a blocking IO operation) + // call this to avoid having the fixed timestep logic attempt a set of catch-up + // Update calls. + + void ResetElapsedTime() + { + if (!QueryPerformanceCounter(&m_qpcLastTime)) + { + throw std::exception(); + } + + m_leftOverTicks = 0; + m_framesPerSecond = 0; + m_framesThisSecond = 0; + m_qpcSecondCounter = 0; + } + + // Update timer state, calling the specified Update function the appropriate number of times. + template + void Tick(const TUpdate& update) + { + // Query the current time. + LARGE_INTEGER currentTime; + + if (!QueryPerformanceCounter(¤tTime)) + { + throw std::exception(); + } + + uint64_t timeDelta = static_cast(currentTime.QuadPart - m_qpcLastTime.QuadPart); + + m_qpcLastTime = currentTime; + m_qpcSecondCounter += timeDelta; + + // Clamp excessively large time deltas (e.g. after paused in the debugger). + if (timeDelta > m_qpcMaxDelta) + { + timeDelta = m_qpcMaxDelta; + } + + // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp. + timeDelta *= TicksPerSecond; + timeDelta /= static_cast(m_qpcFrequency.QuadPart); + + const uint32_t lastFrameCount = m_frameCount; + + if (m_isFixedTimeStep) + { + // Fixed timestep update logic + + // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp + // the clock to exactly match the target value. This prevents tiny and irrelevant errors + // from accumulating over time. Without this clamping, a game that requested a 60 fps + // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually + // accumulate enough tiny errors that it would drop a frame. It is better to just round + // small deviations down to zero to leave things running smoothly. + + if (static_cast(std::abs(static_cast(timeDelta - m_targetElapsedTicks))) < TicksPerSecond / 4000) + { + timeDelta = m_targetElapsedTicks; + } + + m_leftOverTicks += timeDelta; + + while (m_leftOverTicks >= m_targetElapsedTicks) + { + m_elapsedTicks = m_targetElapsedTicks; + m_totalTicks += m_targetElapsedTicks; + m_leftOverTicks -= m_targetElapsedTicks; + m_frameCount++; + + update(); + } + } + else + { + // Variable timestep update logic. + m_elapsedTicks = timeDelta; + m_totalTicks += timeDelta; + m_leftOverTicks = 0; + m_frameCount++; + + update(); + } + + // Track the current framerate. + if (m_frameCount != lastFrameCount) + { + m_framesThisSecond++; + } + + if (m_qpcSecondCounter >= static_cast(m_qpcFrequency.QuadPart)) + { + m_framesPerSecond = m_framesThisSecond; + m_framesThisSecond = 0; + m_qpcSecondCounter %= static_cast(m_qpcFrequency.QuadPart); + } + } + + private: + // Source timing data uses QPC units. + LARGE_INTEGER m_qpcFrequency; + LARGE_INTEGER m_qpcLastTime; + uint64_t m_qpcMaxDelta; + + // Derived timing data uses a canonical tick format. + uint64_t m_elapsedTicks; + uint64_t m_totalTicks; + uint64_t m_leftOverTicks; + + // Members for tracking the framerate. + uint32_t m_frameCount; + uint32_t m_framesPerSecond; + uint32_t m_framesThisSecond; + uint64_t m_qpcSecondCounter; + + // Members for configuring fixed timestep mode. + bool m_isFixedTimeStep; + uint64_t m_targetElapsedTicks; + }; + + + //==============================================// + //================ IMPL ================// + //==============================================// + + struct SpriteFont::PlatformImplementation { + uptr _dxSpriteFont{ nullptr }; + }; + + struct SpriteBatch::PlatformImplementation { + sptr _dxspriteBatch = nullptr; + }; + + struct GraphicsAdapter::PlatformImplementation { + ~PlatformImplementation() { + if (dxadapter) { + dxadapter->Release(); + dxadapter = nullptr; + } + } + + IDXGIAdapter1* dxadapter = nullptr; + private: + friend class GraphicsAdapter; + Uint _index{ 0 }; + sptr _currentDisplayMode = nullptr; + + public: + bool GetOutput(UINT slot, IDXGIOutput*& output); + }; + + struct BlendRenderTarget { + bool Enabled{ true }; + Blend Source{ Blend::SourceAlpha }; + Blend Destination{ Blend::InverseSourceAlpha }; + BlendOperation Operation{ BlendOperation::Add }; + Blend SourceAlpha{ Blend::One }; + Blend DestinationAlpha{ Blend::Zero }; + BlendOperation OperationAlpha{ BlendOperation::Add }; + ColorWriteChannels WriteMask{ ColorWriteChannels::All }; + + constexpr BlendRenderTarget() = default; + }; + + struct BlendState::PlatformImplementation { + ~PlatformImplementation() { + if (dxBlendState) { + dxBlendState->Release(); + dxBlendState = nullptr; + } + } + + ID3D11BlendState* dxBlendState = nullptr; + D3D11_BLEND_DESC dxDescription{}; + float blendFactor[4]{ 1.0F, 1.0F, 1.0F, 1.0F }; + UINT sampleMask{ 0xffffffff }; + }; + + struct ConstantBuffer::PlatformImplementation { + ~PlatformImplementation() { + if (_buffer) { + _buffer->Release(); + _buffer = nullptr; + } + } + + D3D11_BUFFER_DESC _description{}; + D3D11_SUBRESOURCE_DATA _subResource{}; + ID3D11Buffer* _buffer = nullptr; + DirectX::XMMATRIX _worldViewProjection{}; + }; + + struct DataBuffer::PlatformImplementation { + ~PlatformImplementation() { + if (_blob) { + _blob->Release(); + _blob = nullptr; + } + } + + ID3DBlob* _blob = nullptr; + + void Set(ID3DBlob*& blob) { + _blob = blob; + } + }; + + struct DepthStencilState::PlatformImplementation { + ~PlatformImplementation() { + if (dxDepthStencil) { + dxDepthStencil->Release(); + dxDepthStencil = nullptr; + } + } + + ID3D11DepthStencilState* dxDepthStencil = nullptr; + D3D11_DEPTH_STENCIL_DESC dxDescription{}; + }; + + struct DisplayModeRefreshRate { + constexpr DisplayModeRefreshRate() = default; + + constexpr DisplayModeRefreshRate(DXGI_RATIONAL const& dxrational) { + Numerator = dxrational.Numerator; + Denominator = dxrational.Denominator; + } + constexpr DisplayModeRefreshRate(Uint numerator, Uint denominator) + : Numerator(numerator), Denominator(denominator) {} + + Uint Numerator{ 0 }; + Uint Denominator{ 0 }; + + constexpr bool operator==(const DisplayModeRefreshRate& other) const + { + return Numerator == other.Numerator && Denominator == other.Denominator; + } + }; + + struct DisplayModeDescription { + DisplayModeScanlineOrder _scanlineOrdering{ DisplayModeScanlineOrder::Unspecified }; + DisplayModeScaling _scaling{ DisplayModeScaling::Unspecified }; + DisplayModeRefreshRate _refreshRate{}; + + constexpr bool operator==(const DisplayModeDescription& other) const + { + return _scanlineOrdering == other._scanlineOrdering && _scaling == other._scaling && _refreshRate == other._refreshRate; + } + }; + + struct DisplayMode::PlatformImplementation { + std::vector Descriptions; + }; + + struct GamePad::PlatformImplementation { + uptr _dxGamePad = unew(); + + void Suspend() const { + if (_dxGamePad) + _dxGamePad->Suspend(); + } + + void Resume() const { + if (_dxGamePad) + _dxGamePad->Resume(); + } + }; + + struct IndexBuffer::PlatformImplementation { + ~PlatformImplementation() { + if (dxBuffer) { + dxBuffer->Release(); + dxBuffer = nullptr; + } + } + + ID3D11Buffer* dxBuffer = nullptr; + }; + + struct Keyboard::PlatformImplementation { + uptr _dxKeyboard = unew(); + + void ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) const { + if (_dxKeyboard) + _dxKeyboard->ProcessMessage(message, wParam, lParam); + } + }; + + struct Mouse::PlatformImplementation { + uptr _dxMouse = unew(); + + void ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) const { + if (_dxMouse) + _dxMouse->ProcessMessage(message, wParam, lParam); + } + }; + + struct RasterizerState::PlatformImplementation { + ~PlatformImplementation() { + if (dxRasterizerState) { + dxRasterizerState->Release(); + dxRasterizerState = nullptr; + } + } + + ID3D11RasterizerState* dxRasterizerState = nullptr; + D3D11_RASTERIZER_DESC dxDescription{}; + }; + + struct SamplerState::PlatformImplementation { + ~PlatformImplementation() { + if (_samplerState) { + _samplerState->Release(); + _samplerState = nullptr; + } + } + + ID3D11SamplerState* _samplerState = nullptr; + D3D11_SAMPLER_DESC _description{}; + }; + + struct VertexShader::PlatformImplementation { + ~PlatformImplementation() { + if (_vertexShader) { + _vertexShader->Release(); + _vertexShader = nullptr; + } + } + + ID3D11VertexShader* _vertexShader = nullptr; + }; + + struct PixelShader::PlatformImplementation { + ~PlatformImplementation() { + if (_pixelShader) { + _pixelShader->Release(); + _pixelShader = nullptr; + } + } + + ID3D11PixelShader* _pixelShader = nullptr; + }; + + struct SwapChain::PlatformImplementation { + ~PlatformImplementation() { + if (dxSwapChain) { + dxSwapChain->Release(); + dxSwapChain = nullptr; + } + } + + IDXGISwapChain1* dxSwapChain{ nullptr }; + DXGI_SWAP_CHAIN_DESC1 dxDescription{}; + DXGI_SWAP_CHAIN_FULLSCREEN_DESC dxFullScreenDescription{}; + + bool GetBackBuffer(ID3D11Texture2D*& texture2D) { + if (!dxSwapChain) + return false; + + const auto hr = dxSwapChain->GetBuffer(0, __uuidof(texture2D), (void**)(&texture2D)); + + return !FAILED(hr); + } + }; + + struct Texture2D::PlatformImplementation { + ~PlatformImplementation() { + if (dxTexture2D) { + dxTexture2D->Release(); + dxTexture2D = nullptr; + } + + if (dxShaderResource) { + dxShaderResource->Release(); + dxShaderResource = nullptr; + } + } + + ID3D11Texture2D* dxTexture2D{ nullptr }; + ID3D11ShaderResourceView* dxShaderResource{ nullptr }; + D3D11_SUBRESOURCE_DATA dxSubResource{}; + D3D11_TEXTURE2D_DESC dxDescription{}; + D3D11_SHADER_RESOURCE_VIEW_DESC dxShaderDescription{}; + }; + + struct RenderTarget2D::PlatformImplementation { + ~PlatformImplementation() { + if (_renderTargetView) { + _renderTargetView->Release(); + _renderTargetView = nullptr; + } + } + + ID3D11RenderTargetView* _renderTargetView = nullptr; + D3D11_RENDER_TARGET_VIEW_DESC _renderTargetDesc{}; + }; + + struct VertexBuffer::PlatformImplementation { + ~PlatformImplementation() { + if (dxBuffer) { + dxBuffer->Release(); + dxBuffer = nullptr; + } + } + + ID3D11Buffer* dxBuffer = nullptr; + UINT size{ 0 }; + }; + + struct VertexInputLayout::PlatformImplementation { + ~PlatformImplementation() { + if (_inputLayout) { + _inputLayout->Release(); + _inputLayout = nullptr; + } + } + + ID3D11InputLayout* _inputLayout{ nullptr }; + std::vector _description{}; + }; + + enum class GameWindowMode : UINT { + Fullscreen = WS_POPUP | WS_VISIBLE, + Windowed = WS_OVERLAPPED | WS_SYSMENU | WS_VISIBLE, + Borderless = WS_EX_TOPMOST | WS_POPUP | WS_VISIBLE, + }; + + struct GameWindow::PlatformImplementation { + public: + constexpr void Mode(GameWindowMode mode) { + _windowStyle = static_cast(mode); + } + + constexpr GameWindowMode Mode() const { + return static_cast(_windowStyle); + } + + void Position(int width, int height, bool update = true); + void Size(int width, int height, bool update = true); + + inline HINSTANCE HInstance() const { + return _hInstance; + } + + inline HWND WindowHandle() const { + return _windowHandle; + } + + constexpr int Width() const { + return _windowWidth; + } + + constexpr int Height() const { + return _windowHeight; + } + + inline void Icon(unsigned int icon) { + _windowIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(icon)); + } + + inline void Icon(HICON icon) { + _windowIcon = icon; + } + + inline void Cursor(unsigned int cursor) { + _windowCursor = LoadCursor(GetModuleHandle(NULL), MAKEINTRESOURCE(cursor)); + } + + inline void Cursor(HCURSOR cursor) { + _windowCursor = cursor; + } + + constexpr float CenterX() const { + return _windowCenterX; + } + + constexpr float CenterY() const { + return _windowCenterY; + } + + inline void CursorVisibility(bool visible) const { + ShowCursor(visible); + } + + inline void Close() { + PostMessage(_windowHandle, WM_DESTROY, 0, 0); + } + + constexpr COLORREF Color() const { + return _windowColor; + } + + constexpr void Color(COLORREF color) { + _windowColor = color; + } + + constexpr void Color(BYTE r, BYTE g, BYTE b) { + _windowColor = RGB(r, g, b); + } + + bool Create(); + bool Update(); + + static LRESULT CALLBACK WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + + private: + friend class GameWindow; + + HINSTANCE _hInstance{ nullptr }; + HWND _windowHandle{ nullptr }; + int _windowWidth{ 800 }; + int _windowHeight{ 480 }; + HICON _windowIcon{ nullptr }; + HCURSOR _windowCursor{ nullptr }; + COLORREF _windowColor{ RGB(0,0,0) }; + String _windowTitle{ "Xna++ Game Development" }; + DWORD _windowStyle{ 0 }; + int _windowPosX{ 0 }; + int _windowPosY{ 0 }; + float _windowCenterX{ 0 }; + float _windowCenterY{ 0 }; + + inline void setPosition() { + _windowPosX = GetSystemMetrics(SM_CXSCREEN) / 2 - _windowWidth / 2; + _windowPosY = GetSystemMetrics(SM_CYSCREEN) / 2 - _windowHeight / 2; + } + + inline void setCenter() { + _windowCenterX = _windowWidth / 2.0f; + _windowCenterY = _windowHeight / 2.0f; + } + }; + + struct AudioEngine::PlatformImplementation { + PlatformImplementation() { + _dxAudioEngine = unew( +#ifdef _DEBUG + DirectX::AudioEngine_Debug +#endif + ); + } + + ~PlatformImplementation() { + if (_dxAudioEngine) { + _dxAudioEngine->Suspend(); + } + } + + uptr _dxAudioEngine = nullptr; + }; + + struct GraphicsDevice::PlatformImplementation { + PlatformImplementation() { + _blendState = xna::BlendState::Opaque(); + _depthStencilState = xna::DepthStencilState::Default(); + _rasterizerState = xna::RasterizerState::CullCounterClockwise(); + _samplerStates = snew(); + } + + ~PlatformImplementation() { + if (_device) { + _device->Release(); + _device = nullptr; + } + + if (_context) { + _context->Release(); + _device = nullptr; + } + + if (_factory) { + _factory->Release(); + _factory = nullptr; + } + } + + private: + void InitializeAndApplyStates(PGraphicsDevice const& device) { + _blendState->Bind(device); + _blendState->Initialize(); + _blendState->Apply(); + + _rasterizerState->Bind(device); + _rasterizerState->Initialize(); + _rasterizerState->Apply(); + + _depthStencilState->Bind(device); + _depthStencilState->Initialize(); + _depthStencilState->Apply(); + } + + public: + ID3D11Device* _device = nullptr; + ID3D11DeviceContext* _context = nullptr; + IDXGIFactory1* _factory = nullptr; + + PBlendState _blendState = nullptr; + PRasterizerState _rasterizerState = nullptr; + PDepthStencilState _depthStencilState = nullptr; + PSamplerStateCollection _samplerStates = nullptr; + Int _multiSampleMask = 0xffffffff; + + sptr _swapChain = nullptr; + sptr _adapter = nullptr; + sptr _renderTarget2D = nullptr; + sptr _gameWindow = nullptr; + xna::Viewport _viewport{}; + sptr _presentationParameters; + D3D_FEATURE_LEVEL _featureLevel{ D3D_FEATURE_LEVEL::D3D_FEATURE_LEVEL_11_0 }; + + private: + friend class GraphicsDevice; + float _backgroundColor[4] = { 0, 0, 0, 0 }; + bool _usevsync{ true }; + }; + + struct Game::PlatformImplementation { + private: + friend class Game; + + xna::StepTimer _stepTimer{}; + }; + + struct SoundEffectInstance::PlatformImplementation { + uptr _dxInstance = nullptr; + }; + + struct SoundEffect::PlatformImplementation { + ~PlatformImplementation() { + } + + uptr _dxSoundEffect = nullptr; + }; + + struct Effect::PlatformImplementation { + ~PlatformImplementation() { + if (dxEffect) { + dxEffect->Release(); + dxEffect = nullptr; + } + } + + ID3DX11Effect* dxEffect = nullptr; + }; + + struct EffectAnnotation::PlatformImplementation { + ~PlatformImplementation() { + if (dxVariable) { + dxVariable->Release(); + dxVariable = nullptr; + } + } + + ID3DX11EffectVariable* dxVariable = nullptr; + }; + + struct EffectPass::PlatformImplementation { + ~PlatformImplementation() { + if (dxPass) { + dxPass->Release(); + dxPass = nullptr; + } + + if (dxContext) { + dxContext->Release(); + dxContext = nullptr; + } + } + + ID3DX11EffectPass* dxPass = nullptr; + ID3D11DeviceContext* dxContext = nullptr; + }; + + struct EffectTechnique::PlatformImplementation { + ~PlatformImplementation() { + if (dxTechnique) { + dxTechnique->Release(); + dxTechnique = nullptr; + } + + if (dxContext) { + dxContext->Release(); + dxContext = nullptr; + } + } + + ID3DX11EffectTechnique* dxTechnique = nullptr; + ID3D11DeviceContext* dxContext = nullptr; + }; + + struct EffectParameter::PlatformImplementation { + PlatformImplementation(){} + + PlatformImplementation(ID3DX11EffectVariable* value) { + dxVariable = value; + dxVariable->AddRef(); + } + + ~PlatformImplementation() { + if (dxVariable) { + dxVariable->Release(); + dxVariable = nullptr; + } + } + + ID3DX11EffectVariable* dxVariable = nullptr; + }; + + template + inline bool IndexBuffer::Initialize(std::vector const& data) { + if (!impl || !m_device || !m_device->impl->_device || data.empty()) { + Exception::Throw(ExMessage::InitializeComponent); + } + + const auto hr = DirectX::CreateStaticBuffer(m_device->impl->_device, data.data(), data.size(), sizeof(T), D3D11_BIND_INDEX_BUFFER, &impl->dxBuffer); + + if (FAILED(hr)) { + Exception::Throw(ExMessage::CreateComponent); + } + + return true; + } + + template + inline bool VertexBuffer::Initialize(std::vector const& data) { + if (!impl || !m_device || !m_device->impl->_device || data.empty()) { + Exception::Throw(ExMessage::InitializeComponent); + } + + const auto hr = DirectX::CreateStaticBuffer(m_device->impl->_device, data.data(), data.size(), sizeof(T), D3D11_BIND_VERTEX_BUFFER, &impl->dxBuffer); + + if (FAILED(hr)) { + Exception::Throw(ExMessage::CreateComponent); + } + + impl->size = sizeof(T); + + return true; + } +} +#endif \ No newline at end of file diff --git a/inc/xna/platform-dx/headers.hpp b/inc/xna/platform-dx/headers.hpp deleted file mode 100644 index 6009b28..0000000 --- a/inc/xna/platform-dx/headers.hpp +++ /dev/null @@ -1,36 +0,0 @@ -//DirectX -#include "dxgi.h" -#include "d3d11.h" -#include -#include -//HSLS -#include -//DirectXTK -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -//Windows -#define NOMINMAX -#include -#include -#include -#include -#include \ No newline at end of file diff --git a/inc/xna/platform-dx/helpers.hpp b/inc/xna/platform-dx/helpers.hpp deleted file mode 100644 index 9d564c0..0000000 --- a/inc/xna/platform-dx/helpers.hpp +++ /dev/null @@ -1,173 +0,0 @@ -#include "headers.hpp" -#include "../graphics/blendstate.hpp" -#include "../graphics/adapter.hpp" - -namespace xna { - struct DxHelpers { - static constexpr DXGI_FORMAT ConvertSurfaceToDXGIFORMAT(SurfaceFormat format) - { - switch (format) - { - case SurfaceFormat::Color://21 - return DXGI_FORMAT_R8G8B8A8_UNORM; - case SurfaceFormat::Bgr565: //23 - return DXGI_FORMAT_B5G6R5_UNORM; - case SurfaceFormat::Bgra5551://25 - return DXGI_FORMAT_B5G5R5A1_UNORM; - case SurfaceFormat::Bgra4444://26 - return DXGI_FORMAT_B4G4R4A4_UNORM; - case SurfaceFormat::Dxt1://827611204 - return DXGI_FORMAT_BC1_UNORM; - case SurfaceFormat::Dxt3://861165636 - return DXGI_FORMAT_BC2_UNORM; - case SurfaceFormat::Dxt5://894720068 - return DXGI_FORMAT_BC3_UNORM; - case SurfaceFormat::NormalizedByte2://60 - return DXGI_FORMAT_R8G8_SNORM; - case SurfaceFormat::NormalizedByte4://63 - return DXGI_FORMAT_R8G8B8A8_SNORM; - case SurfaceFormat::Rgba1010102://31 - return DXGI_FORMAT_R10G10B10A2_UNORM; - case SurfaceFormat::Rg32://34 - return DXGI_FORMAT_R16G16_UNORM; - case SurfaceFormat::Rgba64://36 - return DXGI_FORMAT_R16G16B16A16_UNORM; - case SurfaceFormat::Alpha8://28 - return DXGI_FORMAT_A8_UNORM; - case SurfaceFormat::Single://114 - return DXGI_FORMAT_R32_FLOAT; - case SurfaceFormat::Vector2://115 - return DXGI_FORMAT_R32G32_FLOAT; - case SurfaceFormat::Vector4://116 - return DXGI_FORMAT_R32G32B32A32_FLOAT; - case SurfaceFormat::HalfSingle://111 - return DXGI_FORMAT_R16_FLOAT; - case SurfaceFormat::HalfVector2://112 - return DXGI_FORMAT_R16G16_FLOAT; - case SurfaceFormat::HalfVector4://113 - return DXGI_FORMAT_R16G16B16A16_FLOAT; - case SurfaceFormat::HdrBlendable://113 - return DXGI_FORMAT_R16G16B16A16_FLOAT; - default://0 - return DXGI_FORMAT_UNKNOWN; - } - } - - static constexpr SurfaceFormat ConvertDXGIFORMATToSurface(DXGI_FORMAT format) { - switch (format) - { - case DXGI_FORMAT_R8G8B8A8_UNORM: - case DXGI_FORMAT_B8G8R8A8_UNORM: - return SurfaceFormat::Color; - case DXGI_FORMAT_B5G6R5_UNORM: - return SurfaceFormat::Bgr565; - case DXGI_FORMAT_B5G5R5A1_UNORM: - return SurfaceFormat::Bgra5551; - case DXGI_FORMAT_B4G4R4A4_UNORM: - return SurfaceFormat::Bgra4444; - case DXGI_FORMAT_BC2_UNORM: - return SurfaceFormat::Dxt3; - case DXGI_FORMAT_BC3_UNORM: - return SurfaceFormat::Dxt5; - case DXGI_FORMAT_R8G8_SNORM: - return SurfaceFormat::NormalizedByte2; - case DXGI_FORMAT_R8G8B8A8_SNORM: - return SurfaceFormat::NormalizedByte4; - case DXGI_FORMAT_R10G10B10A2_UNORM: - return SurfaceFormat::Rgba1010102; - case DXGI_FORMAT_R16G16_UNORM: - return SurfaceFormat::Rg32; - case DXGI_FORMAT_R16G16B16A16_UNORM: - return SurfaceFormat::Rgba64; - case DXGI_FORMAT_A8_UNORM: - return SurfaceFormat::Alpha8; - case DXGI_FORMAT_R32_FLOAT: - return SurfaceFormat::Single; - case DXGI_FORMAT_R32G32_FLOAT: - return SurfaceFormat::Vector2; - case DXGI_FORMAT_R32G32B32A32_FLOAT: - return SurfaceFormat::Vector4; - case DXGI_FORMAT_R16_FLOAT: - return SurfaceFormat::HalfSingle; - case DXGI_FORMAT_R16G16_FLOAT: - return SurfaceFormat::HalfVector2; - case DXGI_FORMAT_R16G16B16A16_FLOAT: - return SurfaceFormat::HalfVector4; - default: - return SurfaceFormat::Unknown; - } - } - - static constexpr D3D11_BLEND ConvertBlend(Blend blend) { - switch (blend) - { - case xna::Blend::Zero: - return D3D11_BLEND_ZERO; - case xna::Blend::One: - return D3D11_BLEND_ONE; - case xna::Blend::SourceColor: - return D3D11_BLEND_SRC_COLOR; - case xna::Blend::InverseSourceColor: - return D3D11_BLEND_INV_SRC_COLOR; - case xna::Blend::SourceAlpha: - return D3D11_BLEND_SRC_ALPHA; - case xna::Blend::InverseSourceAlpha: - return D3D11_BLEND_INV_SRC_ALPHA; - case xna::Blend::DestinationAlpha: - return D3D11_BLEND_DEST_ALPHA; - case xna::Blend::InverseDestinationAlpha: - return D3D11_BLEND_INV_DEST_ALPHA; - case xna::Blend::DestinationColor: - return D3D11_BLEND_DEST_COLOR; - case xna::Blend::InverseDestinationColor: - return D3D11_BLEND_INV_DEST_COLOR; - case xna::Blend::SourceAlphaSaturation: - return D3D11_BLEND_SRC_ALPHA_SAT; - case xna::Blend::BlendFactor: - return D3D11_BLEND_BLEND_FACTOR; - case xna::Blend::InverseBlendFactor: - return D3D11_BLEND_INV_BLEND_FACTOR; - case xna::Blend::Source1Color: - return D3D11_BLEND_SRC1_COLOR; - case xna::Blend::InverseSource1Color: - return D3D11_BLEND_INV_SRC1_COLOR; - case xna::Blend::Source1Alpha: - return D3D11_BLEND_SRC1_ALPHA; - case xna::Blend::InverseSource1Alpha: - return D3D11_BLEND_INV_SRC1_ALPHA; - default: - return D3D11_BLEND_ZERO; - } - } - - static constexpr D3D11_BLEND_OP ConvertOperation(BlendOperation op) { - return static_cast(static_cast(op) + 1); - } - - static constexpr D3D11_COLOR_WRITE_ENABLE ConvertColorWrite(ColorWriteChannels colorWrite) { - switch (colorWrite) - { - case xna::ColorWriteChannels::Red: - return D3D11_COLOR_WRITE_ENABLE_RED; - case xna::ColorWriteChannels::Green: - return D3D11_COLOR_WRITE_ENABLE_GREEN; - case xna::ColorWriteChannels::Blue: - return D3D11_COLOR_WRITE_ENABLE_BLUE; - case xna::ColorWriteChannels::Alpha: - return D3D11_COLOR_WRITE_ENABLE_ALPHA; - case xna::ColorWriteChannels::All: - return D3D11_COLOR_WRITE_ENABLE_ALL; - default: - return D3D11_COLOR_WRITE_ENABLE_ALL; - } - } - - static constexpr void ConvertAddressMode(TextureAddressMode value, D3D11_TEXTURE_ADDRESS_MODE& target) { - target = static_cast(static_cast(value) + 1); - } - - static constexpr void ConvertAddressMode(D3D11_TEXTURE_ADDRESS_MODE value, TextureAddressMode& target) { - target = static_cast(value - 1); - } - }; -} \ No newline at end of file diff --git a/inc/xna/platform-dx/implementations.hpp b/inc/xna/platform-dx/implementations.hpp deleted file mode 100644 index 2d1eefd..0000000 --- a/inc/xna/platform-dx/implementations.hpp +++ /dev/null @@ -1,522 +0,0 @@ -#ifndef XNA_PLATFORM_DX_IMPLEMENTATIONS_HPP -#define XNA_PLATFORM_DX_IMPLEMENTATIONS_HPP - -#include "headers.hpp" -#include "stepTimer.hpp" -#include "../graphics/device.hpp" -#include "../graphics/adapter.hpp" -#include "../graphics/blendstate.hpp" -#include "../graphics/buffer.hpp" -#include "../graphics/depthstencilstate.hpp" -#include "../graphics/displaymode.hpp" -#include "../graphics/sprite.hpp" -#include "../graphics/samplerstate.hpp" -#include "../input/gamepad.hpp" -#include "../input/keyboard.hpp" -#include "../input/mouse.hpp" -#include "../graphics/rasterizerstate.hpp" -#include "../graphics/presentparams.hpp" -#include "../graphics/shader.hpp" -#include "../graphics/swapchain.hpp" -#include "../graphics/texture.hpp" -#include "../graphics/rendertarget.hpp" -#include "../game/window.hpp" -#include "../audio/audioengine.hpp" -#include "../audio/soundeffect.hpp" -#include "../graphics/viewport.hpp" -#include "../common/color.hpp" -#include "../game/game.hpp" - -namespace xna { - struct SpriteFont::PlatformImplementation { - sptr _dxSpriteFont = nullptr; - }; - - struct SpriteBatch::PlatformImplementation { - sptr _dxspriteBatch = nullptr; - }; - - struct GraphicsAdapter::PlatformImplementation { - ~PlatformImplementation() { - if (dxadapter) { - dxadapter->Release(); - dxadapter = nullptr; - } - } - - IDXGIAdapter1* dxadapter = nullptr; - private: - friend class GraphicsAdapter; - Uint _index{ 0 }; - sptr _currentDisplayMode = nullptr; - - public: - bool GetOutput(UINT slot, IDXGIOutput*& output); - }; - - struct BlendRenderTarget { - bool Enabled{ true }; - Blend Source{ Blend::SourceAlpha }; - Blend Destination{ Blend::InverseSourceAlpha }; - BlendOperation Operation{ BlendOperation::Add }; - Blend SourceAlpha{ Blend::One }; - Blend DestinationAlpha{ Blend::Zero }; - BlendOperation OperationAlpha{ BlendOperation::Add }; - ColorWriteChannels WriteMask{ ColorWriteChannels::All }; - - constexpr BlendRenderTarget() = default; - }; - - struct BlendState::PlatformImplementation { - ~PlatformImplementation() { - if (dxBlendState) { - dxBlendState->Release(); - dxBlendState = nullptr; - } - } - - ID3D11BlendState* dxBlendState = nullptr; - D3D11_BLEND_DESC dxDescription{}; - float blendFactor[4]{ 1.0F, 1.0F, 1.0F, 1.0F }; - UINT sampleMask{ 0xffffffff }; - }; - - struct ConstantBuffer::PlatformImplementation { - ~PlatformImplementation() { - if (_buffer) { - _buffer->Release(); - _buffer = nullptr; - } - } - - D3D11_BUFFER_DESC _description{}; - D3D11_SUBRESOURCE_DATA _subResource{}; - ID3D11Buffer* _buffer = nullptr; - DirectX::XMMATRIX _worldViewProjection{}; - }; - - struct DataBuffer::PlatformImplementation { - ~PlatformImplementation() { - if (_blob) { - _blob->Release(); - _blob = nullptr; - } - } - - ID3DBlob* _blob = nullptr; - - void Set(ID3DBlob*& blob) { - _blob = blob; - } - }; - - struct DepthStencilState::PlatformImplementation { - ~PlatformImplementation() { - if (dxDepthStencil) { - dxDepthStencil->Release(); - dxDepthStencil = nullptr; - } - } - - ID3D11DepthStencilState* dxDepthStencil = nullptr; - D3D11_DEPTH_STENCIL_DESC dxDescription{}; - }; - - struct DisplayModeRefreshRate { - constexpr DisplayModeRefreshRate() = default; - - constexpr DisplayModeRefreshRate(DXGI_RATIONAL const& dxrational) { - Numerator = dxrational.Numerator; - Denominator = dxrational.Denominator; - } - constexpr DisplayModeRefreshRate(Uint numerator, Uint denominator) - : Numerator(numerator), Denominator(denominator) {} - - Uint Numerator{ 0 }; - Uint Denominator{ 0 }; - - constexpr bool operator==(const DisplayModeRefreshRate& other) const - { - return Numerator == other.Numerator && Denominator == other.Denominator; - } - }; - - struct DisplayModeDescription { - DisplayModeScanlineOrder _scanlineOrdering{ DisplayModeScanlineOrder::Unspecified }; - DisplayModeScaling _scaling{ DisplayModeScaling::Unspecified }; - DisplayModeRefreshRate _refreshRate{}; - - constexpr bool operator==(const DisplayModeDescription& other) const - { - return _scanlineOrdering == other._scanlineOrdering && _scaling == other._scaling && _refreshRate == other._refreshRate; - } - }; - - struct DisplayMode::PlatformImplementation { - std::vector Descriptions; - }; - - struct GamePad::PlatformImplementation { - inline static uptr _dxGamePad = nullptr; - - void Suspend() { - if (_dxGamePad) - _dxGamePad->Suspend(); - } - - void Resume() { - if (_dxGamePad) - _dxGamePad->Resume(); - } - }; - - struct IndexBuffer::PlatformImplementation { - ~PlatformImplementation() { - if (dxBuffer) { - dxBuffer->Release(); - dxBuffer = nullptr; - } - } - - ID3D11Buffer* dxBuffer = nullptr; - }; - - struct Keyboard::PlatformImplementation { - inline static uptr _dxKeyboard = nullptr; - - void ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) { - if (_dxKeyboard) - _dxKeyboard->ProcessMessage(message, wParam, lParam); - } - }; - - struct Mouse::PlatformImplementation { - inline static uptr _dxMouse = nullptr; - - void ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) { - if (_dxMouse) - _dxMouse->ProcessMessage(message, wParam, lParam); - } - }; - - struct RasterizerState::PlatformImplementation { - ~PlatformImplementation() { - if (dxRasterizerState) { - dxRasterizerState->Release(); - dxRasterizerState = nullptr; - } - } - - ID3D11RasterizerState* dxRasterizerState = nullptr; - D3D11_RASTERIZER_DESC dxDescription{}; - }; - - struct SamplerState::PlatformImplementation { - ~PlatformImplementation() { - if (_samplerState) { - _samplerState->Release(); - _samplerState = nullptr; - } - } - - ID3D11SamplerState* _samplerState = nullptr; - D3D11_SAMPLER_DESC _description{}; - }; - - struct VertexShader::PlatformImplementation { - ~PlatformImplementation() { - if (_vertexShader) { - _vertexShader->Release(); - _vertexShader = nullptr; - } - } - - ID3D11VertexShader* _vertexShader = nullptr; - }; - - struct PixelShader::PlatformImplementation { - ~PlatformImplementation() { - if (_pixelShader) { - _pixelShader->Release(); - _pixelShader = nullptr; - } - } - - ID3D11PixelShader* _pixelShader = nullptr; - }; - - struct SwapChain::PlatformImplementation { - IDXGISwapChain1* dxSwapChain{ nullptr }; - DXGI_SWAP_CHAIN_DESC1 dxDescription{}; - DXGI_SWAP_CHAIN_FULLSCREEN_DESC dxFullScreenDescription{}; - - bool GetBackBuffer(ID3D11Texture2D*& texture2D) { - if (!dxSwapChain) - return false; - - const auto hr = dxSwapChain->GetBuffer(0, __uuidof(texture2D), (void**)(&texture2D)); - - return !FAILED(hr); - } - }; - - struct Texture2D::PlatformImplementation { - ~PlatformImplementation() { - if (dxTexture2D) { - dxTexture2D->Release(); - dxTexture2D = nullptr; - } - - if (dxShaderResource) { - dxShaderResource->Release(); - dxShaderResource = nullptr; - } - } - - ID3D11Texture2D* dxTexture2D{ nullptr }; - ID3D11ShaderResourceView* dxShaderResource{ nullptr }; - D3D11_SUBRESOURCE_DATA dxSubResource{}; - D3D11_TEXTURE2D_DESC dxDescription{}; - D3D11_SHADER_RESOURCE_VIEW_DESC dxShaderDescription{}; - }; - - struct RenderTarget2D::PlatformImplementation { - ~PlatformImplementation() { - if (_renderTargetView) { - _renderTargetView->Release(); - _renderTargetView = nullptr; - } - } - - ID3D11RenderTargetView* _renderTargetView = nullptr; - D3D11_RENDER_TARGET_VIEW_DESC _renderTargetDesc{}; - }; - - struct VertexBuffer::PlatformImplementation { - ~PlatformImplementation() { - if (dxBuffer) { - dxBuffer->Release(); - dxBuffer = nullptr; - } - } - - ID3D11Buffer* dxBuffer = nullptr; - UINT size{ 0 }; - }; - - struct VertexInputLayout::PlatformImplementation { - ~PlatformImplementation() { - if (_inputLayout) { - _inputLayout->Release(); - _inputLayout = nullptr; - } - } - - ID3D11InputLayout* _inputLayout{ nullptr }; - std::vector _description{}; - }; - - enum class GameWindowMode : UINT { - Fullscreen = WS_POPUP | WS_VISIBLE, - Windowed = WS_OVERLAPPED | WS_SYSMENU | WS_VISIBLE, - Borderless = WS_EX_TOPMOST | WS_POPUP | WS_VISIBLE, - }; - - struct GameWindow::PlatformImplementation { - public: - constexpr void Mode(GameWindowMode mode) { - _windowStyle = static_cast(mode); - } - - constexpr GameWindowMode Mode() const { - return static_cast(_windowStyle); - } - - void Position(int width, int height, bool update = true); - void Size(int width, int height, bool update = true); - - inline HINSTANCE HInstance() const { - return _hInstance; - } - - inline HWND WindowHandle() const { - return _windowHandle; - } - - constexpr int Width() const { - return _windowWidth; - } - - constexpr int Height() const { - return _windowHeight; - } - - inline void Icon(unsigned int icon) { - _windowIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(icon)); - } - - inline void Icon(HICON icon) { - _windowIcon = icon; - } - - inline void Cursor(unsigned int cursor) { - _windowCursor = LoadCursor(GetModuleHandle(NULL), MAKEINTRESOURCE(cursor)); - } - - inline void Cursor(HCURSOR cursor) { - _windowCursor = cursor; - } - - constexpr float CenterX() const { - return _windowCenterX; - } - - constexpr float CenterY() const { - return _windowCenterY; - } - - inline void CursorVisibility(bool visible) const { - ShowCursor(visible); - } - - inline void Close() { - PostMessage(_windowHandle, WM_DESTROY, 0, 0); - } - - constexpr COLORREF Color() const { - return _windowColor; - } - - constexpr void Color(COLORREF color) { - _windowColor = color; - } - - constexpr void Color(BYTE r, BYTE g, BYTE b) { - _windowColor = RGB(r, g, b); - } - - bool Create(); - bool Update(); - - static LRESULT CALLBACK WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); - - private: - friend class GameWindow; - - HINSTANCE _hInstance{ nullptr }; - HWND _windowHandle{ nullptr }; - int _windowWidth{ 800 }; - int _windowHeight{ 480 }; - HICON _windowIcon{ nullptr }; - HCURSOR _windowCursor{ nullptr }; - COLORREF _windowColor{ RGB(0,0,0) }; - String _windowTitle{ "Xna++ Game Development" }; - DWORD _windowStyle{ 0 }; - int _windowPosX{ 0 }; - int _windowPosY{ 0 }; - float _windowCenterX{ 0 }; - float _windowCenterY{ 0 }; - - inline void setPosition() { - _windowPosX = GetSystemMetrics(SM_CXSCREEN) / 2 - _windowWidth / 2; - _windowPosY = GetSystemMetrics(SM_CYSCREEN) / 2 - _windowHeight / 2; - } - - inline void setCenter() { - _windowCenterX = _windowWidth / 2.0f; - _windowCenterY = _windowHeight / 2.0f; - } - }; - - struct AudioEngine::PlatformImplementation { - PlatformImplementation() { - _dxAudioEngine = unew( -#ifdef _DEBUG - DirectX::AudioEngine_Debug -#endif - ); - } - - ~PlatformImplementation() { - if (_dxAudioEngine) { - _dxAudioEngine->Suspend(); - } - } - - uptr _dxAudioEngine = nullptr; - }; - - struct GraphicsDevice::PlatformImplementation { - ID3D11Device* _device{ nullptr }; - ID3D11DeviceContext* _context{ nullptr }; - IDXGIFactory1* _factory = nullptr; - sptr _swapChain{ nullptr }; - sptr _adapter{ nullptr }; - sptr _renderTarget2D{ nullptr }; - sptr _blendState{ nullptr }; - xna::Viewport _viewport{}; - sptr _presentationParameters; - D3D_FEATURE_LEVEL _featureLevel{ D3D_FEATURE_LEVEL::D3D_FEATURE_LEVEL_11_0 }; - - private: - friend class GraphicsDevice; - float _backgroundColor[4] = { 0, 0, 0, 0 }; - bool _usevsync{ true }; - }; - - struct Game::PlatformImplementation { - private: - friend class Game; - - xna::StepTimer _stepTimer{}; - }; - - struct SoundEffectInstance::PlatformImplementation { - uptr _dxInstance = nullptr; - }; - - struct SoundEffect::PlatformImplementation { - ~PlatformImplementation() { - } - - uptr _dxSoundEffect = nullptr; - }; - - template - inline bool IndexBuffer::Initialize(std::vector const& data, xna_error_ptr_arg) { - if (!impl || !m_device || !m_device->impl->_device || data.empty()) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; - } - - const auto hr = DirectX::CreateStaticBuffer(m_device->impl->_device, data.data(), data.size(), sizeof(T), D3D11_BIND_INDEX_BUFFER, &impl->dxBuffer); - - if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; - } - - return true; - } - - template - inline bool VertexBuffer::Initialize(std::vector const& data, xna_error_ptr_arg) { - if (!impl || !m_device || !m_device->impl->_device || data.empty()) { - xna_error_apply(err, XnaErrorCode::INVALID_OPERATION); - return false; - } - - const auto hr = DirectX::CreateStaticBuffer(m_device->impl->_device, data.data(), data.size(), sizeof(T), D3D11_BIND_VERTEX_BUFFER, &impl->dxBuffer); - - if (FAILED(hr)) { - xna_error_apply(err, XnaErrorCode::FAILED_OPERATION); - return false; - } - - impl->size = sizeof(T); - - return true; - } -} - -#endif \ No newline at end of file diff --git a/inc/xna/platform-dx/init.hpp b/inc/xna/platform-dx/init.hpp index 7a27a07..b047fe9 100644 --- a/inc/xna/platform-dx/init.hpp +++ b/inc/xna/platform-dx/init.hpp @@ -36,7 +36,7 @@ namespace xna { template static void insertActivadorReader() { ContentTypeReaderActivador::SetActivador(typeof(), []() -> sptr { - auto obj = New (); + auto obj = snew(); return reinterpret_pointer_cast(obj); }); } diff --git a/inc/xna/platform-dx/steptimer.hpp b/inc/xna/platform-dx/steptimer.hpp deleted file mode 100644 index cf9bdfd..0000000 --- a/inc/xna/platform-dx/steptimer.hpp +++ /dev/null @@ -1,195 +0,0 @@ -#ifndef XNA_PLATFORM_DX_STEPTIMER_HPP -#define XNA_PLATFORM_DX_STEPTIMER_HPP -// -// StepTimer.h - A simple timer that provides elapsed time information -// -// https://github.com/microsoft/DirectXTK/wiki/StepTimer - -#pragma once - -#include -#include -#include -#include "headers.hpp" - -namespace xna -{ - // Helper class for animation and simulation timing. - class StepTimer - { - public: - StepTimer() noexcept(false) : - m_elapsedTicks(0), - m_totalTicks(0), - m_leftOverTicks(0), - m_frameCount(0), - m_framesPerSecond(0), - m_framesThisSecond(0), - m_qpcSecondCounter(0), - m_isFixedTimeStep(false), - m_targetElapsedTicks(TicksPerSecond / 60) - { - if (!QueryPerformanceFrequency(&m_qpcFrequency)) - { - throw std::exception(); - } - - if (!QueryPerformanceCounter(&m_qpcLastTime)) - { - throw std::exception(); - } - - // Initialize max delta to 1/10 of a second. - m_qpcMaxDelta = static_cast(m_qpcFrequency.QuadPart / 10); - } - - // Get elapsed time since the previous Update call. - uint64_t GetElapsedTicks() const noexcept { return m_elapsedTicks; } - double GetElapsedSeconds() const noexcept { return TicksToSeconds(m_elapsedTicks); } - - // Get total time since the start of the program. - uint64_t GetTotalTicks() const noexcept { return m_totalTicks; } - double GetTotalSeconds() const noexcept { return TicksToSeconds(m_totalTicks); } - - // Get total number of updates since start of the program. - uint32_t GetFrameCount() const noexcept { return m_frameCount; } - - // Get the current framerate. - uint32_t GetFramesPerSecond() const noexcept { return m_framesPerSecond; } - - // Set whether to use fixed or variable timestep mode. - void SetFixedTimeStep(bool isFixedTimestep) noexcept { m_isFixedTimeStep = isFixedTimestep; } - - // Set how often to call Update when in fixed timestep mode. - void SetTargetElapsedTicks(uint64_t targetElapsed) noexcept { m_targetElapsedTicks = targetElapsed; } - void SetTargetElapsedSeconds(double targetElapsed) noexcept { m_targetElapsedTicks = SecondsToTicks(targetElapsed); } - - // Integer format represents time using 10,000,000 ticks per second. - static constexpr uint64_t TicksPerSecond = 10000000; - - static constexpr double TicksToSeconds(uint64_t ticks) noexcept { return static_cast(ticks) / TicksPerSecond; } - static constexpr uint64_t SecondsToTicks(double seconds) noexcept { return static_cast(seconds * TicksPerSecond); } - - // After an intentional timing discontinuity (for instance a blocking IO operation) - // call this to avoid having the fixed timestep logic attempt a set of catch-up - // Update calls. - - void ResetElapsedTime() - { - if (!QueryPerformanceCounter(&m_qpcLastTime)) - { - throw std::exception(); - } - - m_leftOverTicks = 0; - m_framesPerSecond = 0; - m_framesThisSecond = 0; - m_qpcSecondCounter = 0; - } - - // Update timer state, calling the specified Update function the appropriate number of times. - template - void Tick(const TUpdate& update) - { - // Query the current time. - LARGE_INTEGER currentTime; - - if (!QueryPerformanceCounter(¤tTime)) - { - throw std::exception(); - } - - uint64_t timeDelta = static_cast(currentTime.QuadPart - m_qpcLastTime.QuadPart); - - m_qpcLastTime = currentTime; - m_qpcSecondCounter += timeDelta; - - // Clamp excessively large time deltas (e.g. after paused in the debugger). - if (timeDelta > m_qpcMaxDelta) - { - timeDelta = m_qpcMaxDelta; - } - - // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp. - timeDelta *= TicksPerSecond; - timeDelta /= static_cast(m_qpcFrequency.QuadPart); - - const uint32_t lastFrameCount = m_frameCount; - - if (m_isFixedTimeStep) - { - // Fixed timestep update logic - - // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp - // the clock to exactly match the target value. This prevents tiny and irrelevant errors - // from accumulating over time. Without this clamping, a game that requested a 60 fps - // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually - // accumulate enough tiny errors that it would drop a frame. It is better to just round - // small deviations down to zero to leave things running smoothly. - - if (static_cast(std::abs(static_cast(timeDelta - m_targetElapsedTicks))) < TicksPerSecond / 4000) - { - timeDelta = m_targetElapsedTicks; - } - - m_leftOverTicks += timeDelta; - - while (m_leftOverTicks >= m_targetElapsedTicks) - { - m_elapsedTicks = m_targetElapsedTicks; - m_totalTicks += m_targetElapsedTicks; - m_leftOverTicks -= m_targetElapsedTicks; - m_frameCount++; - - update(); - } - } - else - { - // Variable timestep update logic. - m_elapsedTicks = timeDelta; - m_totalTicks += timeDelta; - m_leftOverTicks = 0; - m_frameCount++; - - update(); - } - - // Track the current framerate. - if (m_frameCount != lastFrameCount) - { - m_framesThisSecond++; - } - - if (m_qpcSecondCounter >= static_cast(m_qpcFrequency.QuadPart)) - { - m_framesPerSecond = m_framesThisSecond; - m_framesThisSecond = 0; - m_qpcSecondCounter %= static_cast(m_qpcFrequency.QuadPart); - } - } - - private: - // Source timing data uses QPC units. - LARGE_INTEGER m_qpcFrequency; - LARGE_INTEGER m_qpcLastTime; - uint64_t m_qpcMaxDelta; - - // Derived timing data uses a canonical tick format. - uint64_t m_elapsedTicks; - uint64_t m_totalTicks; - uint64_t m_leftOverTicks; - - // Members for tracking the framerate. - uint32_t m_frameCount; - uint32_t m_framesPerSecond; - uint32_t m_framesThisSecond; - uint64_t m_qpcSecondCounter; - - // Members for configuring fixed timestep mode. - bool m_isFixedTimeStep; - uint64_t m_targetElapsedTicks; - }; -} - -#endif diff --git a/inc/xna/platform-dx/xna-dx.hpp b/inc/xna/platform-dx/xna-dx.hpp deleted file mode 100644 index 7bf56eb..0000000 --- a/inc/xna/platform-dx/xna-dx.hpp +++ /dev/null @@ -1,4 +0,0 @@ -#include "headers.hpp" -#include "implementations.hpp" -#include "init.hpp" -#include "steptimer.hpp" \ No newline at end of file diff --git a/inc/xna/platforminit.hpp b/inc/xna/platforminit.hpp index 9c869b7..10071c6 100644 --- a/inc/xna/platforminit.hpp +++ b/inc/xna/platforminit.hpp @@ -2,7 +2,10 @@ #define XNA_PLATFORMINIT_HPP namespace xna { + //Exposes functions that must be implemented by the platform struct Platform { + //Initialization function, which must be implemented by the platform, + //and be called before the game is executed static void Init(); }; } diff --git a/inc/xna/types.hpp b/inc/xna/types.hpp index b58a932..12c673a 100644 --- a/inc/xna/types.hpp +++ b/inc/xna/types.hpp @@ -8,8 +8,14 @@ #include #include #include +#include namespace xna { + + // + // C# standard types + // + using Sbyte = int8_t; using Byte = uint8_t; using Short = int16_t; @@ -20,6 +26,10 @@ namespace xna { using Ulong = uint64_t; using Char = char16_t; + // + // C# Min and Max Value + // + constexpr Sbyte SbyteMaxValue = (std::numeric_limits::max)(); constexpr Sbyte SbyteMinValue = (std::numeric_limits::min)(); constexpr Byte ByteMaxValue = (std::numeric_limits::max)(); @@ -47,29 +57,27 @@ namespace xna { // About strings: https://stackoverflow.com/questions/402283/stdwstring-vs-stdstring // + //Same as std::string using String = std::string; - using WString = std::wstring; + + //Same as std::wstring + using WString = std::wstring; + //Same as std::shared_ptr template using sptr = std::shared_ptr; + + //Same as std::unique_ptr template - using uptr = std::unique_ptr; - - template - inline std::shared_ptr<_Ty> New(_Types&&... _Args) { - return std::make_shared<_Ty>(std::forward<_Types>(_Args)...); - } - - template - inline std::unique_ptr<_Ty> uNew(_Types&&... _Args) { - return std::make_unique<_Ty>(std::forward<_Types>(_Args)...); - } - + using uptr = std::unique_ptr; + + //Same as std::make_shared template inline std::shared_ptr<_Ty> snew(_Types&&... _Args) { return std::make_shared<_Ty>(std::forward<_Types>(_Args)...); } + //Same as std::make_unique template inline std::unique_ptr<_Ty> unew(_Types&&... _Args) { return std::make_unique<_Ty>(std::forward<_Types>(_Args)...); diff --git a/inc/xna/xna.hpp b/inc/xna/xna.hpp index 09c8323..fe1fe83 100644 --- a/inc/xna/xna.hpp +++ b/inc/xna/xna.hpp @@ -1,8 +1,8 @@ #define NOMINMAX -#include "xnaerror.hpp" #include "types.hpp" #include "helpers.hpp" #include "enums.hpp" +#include "exception.hpp" #include "audio/audioengine.hpp" #include "audio/soundeffect.hpp" #include "common/color.hpp" @@ -53,4 +53,4 @@ #include "input/keyboard.hpp" #include "input/mouse.hpp" #include "platforminit.hpp" -#include "platform-dx/xna-dx.hpp" \ No newline at end of file +#include "xna/platform-dx/dx.hpp" \ No newline at end of file diff --git a/inc/xna/xnaerror.hpp b/inc/xna/xnaerror.hpp deleted file mode 100644 index dcdf274..0000000 --- a/inc/xna/xnaerror.hpp +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef XNA_XNAERROR_HPP -#define XNA_XNAERROR_HPP - -namespace xna { - enum class XnaErrorCode { - NONE, - ARGUMENT_OUT_OF_RANGE, - ARGUMENT_IS_NULL, - INVALID_OPERATION, - FAILED_OPERATION, - OVERFLOW_OPERATION, - NULL_CAST, - BAD_CAST, - STREAM_ERROR, - UNINTIALIZED_RESOURCE, - END_OF_FILE, - BAD_TYPE, - WARNING_INITIALIZED_RESOURCE - }; - - inline void xna_error_apply(XnaErrorCode* source, XnaErrorCode const& value) { - if (source != nullptr) - *source = value; - } - - inline bool xna_error_haserros(XnaErrorCode* source) { - return source != nullptr && *source != XnaErrorCode::NONE; - } - -#define xna_error_nullarg XnaErrorCode* err = nullptr -#define xna_error_ptr_arg XnaErrorCode* err -} - -#endif \ No newline at end of file diff --git a/samples/01_blank/xna.cpp b/samples/01_blank/xna.cpp index 3ed637b..c14c086 100644 --- a/samples/01_blank/xna.cpp +++ b/samples/01_blank/xna.cpp @@ -15,7 +15,7 @@ namespace xna { void Initialize() override { auto game = reinterpret_cast(this); - graphics = New(game->shared_from_this()); + graphics = snew(game->shared_from_this()); graphics->Initialize(); std::any device = graphicsDevice; @@ -25,7 +25,7 @@ namespace xna { } void LoadContent() override { - spriteBatch = New(*graphicsDevice); + spriteBatch = snew(graphicsDevice); auto texture = Content()->Load("Idle"); Game::LoadContent(); } diff --git a/samples/02_PlatfformerStarterKit/animation.cpp b/samples/02_PlatfformerStarterKit/animation.cpp index 350e1dc..bea1bc9 100644 --- a/samples/02_PlatfformerStarterKit/animation.cpp +++ b/samples/02_PlatfformerStarterKit/animation.cpp @@ -34,6 +34,6 @@ namespace PlatformerStarterKit { const auto source = xna::Rectangle(frameIndex * animation->Texture()->Height(), 0, animation->Texture()->Height(), animation->Texture()->Height()); // Draw the current frame. - spriteBatch.Draw(animation->Texture(), position, &source, xna::Colors::White, 0.0f, Origin(), 1.0f, spriteEffects, 0.0f); + spriteBatch.Draw(animation->Texture(), position, source, xna::Colors::White, 0.0f, Origin(), 1.0f, spriteEffects, 0.0f); } } \ No newline at end of file diff --git a/samples/02_PlatfformerStarterKit/game.cpp b/samples/02_PlatfformerStarterKit/game.cpp index dfcc7a5..d7ee920 100644 --- a/samples/02_PlatfformerStarterKit/game.cpp +++ b/samples/02_PlatfformerStarterKit/game.cpp @@ -21,7 +21,7 @@ namespace PlatformerStarterKit { void Initialize() override { auto game = reinterpret_cast(this); - graphics = New(game->shared_from_this()); + graphics = snew(game->shared_from_this()); graphics->Initialize(); std::any device = graphicsDevice; @@ -31,7 +31,7 @@ namespace PlatformerStarterKit { } void LoadContent() override { - spriteBatch = New(*graphicsDevice); + spriteBatch = snew(graphicsDevice); // Load fonts hudFont = Content()->Load("Fonts/Hud"); diff --git a/samples/02_PlatfformerStarterKit/gem.cpp b/samples/02_PlatfformerStarterKit/gem.cpp index 8c78095..26fde9b 100644 --- a/samples/02_PlatfformerStarterKit/gem.cpp +++ b/samples/02_PlatfformerStarterKit/gem.cpp @@ -34,6 +34,6 @@ namespace PlatformerStarterKit { void Gem::Draw(xna::GameTime const& gameTime, xna::SpriteBatch& spriteBatch) { - spriteBatch.Draw(texture, Position(), nullptr, Color, 0.0f, origin, 1.0f, xna::SpriteEffects::None, 0.0f); + spriteBatch.Draw(texture, Position(), std::nullopt, Color, 0.0f, origin, 1.0f, xna::SpriteEffects::None, 0.0f); } } \ No newline at end of file diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index b164777..45257e9 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -3,5 +3,5 @@ # # Add source to this project's executable. -#add_subdirectory ("01_blank") +add_subdirectory ("01_blank") add_subdirectory ("02_PlatfformerStarterKit")