1
0
mirror of https://github.com/borgesdan/xn65 synced 2024-12-29 21:54:47 +01:00

Merge pull request #8 from borgesdan/develop

Develop
This commit is contained in:
Danilo Borges 2024-06-24 15:11:30 -03:00 committed by GitHub
commit 587960d0f2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
74 changed files with 4465 additions and 1573 deletions

View File

@ -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)

View File

@ -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

View File

@ -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"
)

View File

@ -3,7 +3,7 @@
namespace xna {
sptr<Stream> ContentManager::OpenStream(String const& assetName) const {
const String filePath = _rootDirectory + "\\" + assetName + contentExtension;
const auto stream = New<FileStream>(filePath, FileMode::Open);
const auto stream = snew<FileStream>(filePath, FileMode::Open);
if (stream->IsClosed())
return nullptr;

View File

@ -157,7 +157,7 @@ namespace xna {
void ContentTypeReaderManager::initMaps()
{
if (targetTypeToReader.empty() && readerTypeToReader.empty()) {
auto typeReader = New<ObjectReader>();
auto typeReader = snew<ObjectReader>();
auto contentTypeReader = reinterpret_pointer_cast<ContentTypeReader>(typeReader);
targetTypeToReader.insert({ typeof<Object>(), contentTypeReader});

View File

@ -0,0 +1,18 @@
#include "xna/graphics/gresource.hpp"
namespace xna {
GraphicsResource::GraphicsResource(sptr<GraphicsDevice> const& device) : m_device(device) {}
sptr<GraphicsDevice> GraphicsResource::Device() const {
return m_device;
}
bool GraphicsResource::Bind(sptr<GraphicsDevice> const& device) {
if (!device || device == m_device)
return false;
m_device = device;
return true;
}
}

View File

@ -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<DisplayModeCollection> createDisplayModeCollection(std::vector<DXGI_MODE_DESC> const& source);
GraphicsAdapter::GraphicsAdapter() {
impl = uNew<PlatformImplementation>();
}
GraphicsAdapter::~GraphicsAdapter() {
impl = nullptr;
impl = unew<PlatformImplementation>();
}
uptr<GraphicsAdapter> 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<GraphicsAdapter>();
auto adp = unew<GraphicsAdapter>();
adp->impl->_index = 0;
adp->impl->dxadapter = pAdapter;
@ -40,39 +34,17 @@ namespace xna {
return nullptr;
}
void GraphicsAdapter::Adapters(std::vector<sptr<GraphicsAdapter>>& 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<GraphicsAdapter>();
adp->impl->_index = count;
adp->impl->dxadapter = pAdapter;
adapters.push_back(adp);
}
pFactory->Release();
pFactory = nullptr;
}
void GraphicsAdapter::Adapters(std::vector<uptr<GraphicsAdapter>>& 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<GraphicsAdapter>();
auto adp = unew<GraphicsAdapter>();
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<SurfaceFormat>(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<DisplayModeCollection>();
return unew<DisplayModeCollection>();
std::vector<DXGI_MODE_DESC> buffer(numModes);
pOutput->GetDisplayModeList(format, 0, &numModes, buffer.data());
@ -231,7 +203,7 @@ namespace xna {
return createDisplayModeCollection(buffer);
}
return uNew<DisplayModeCollection>();
return unew<DisplayModeCollection>();
}
sptr<DisplayMode> 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<SurfaceFormat>(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<DisplayModeCollection> createDisplayModeCollection(std::vector<DXGI_MODE_DESC> const& source) {
auto collection = uNew<DisplayModeCollection>();
auto collection = unew<DisplayModeCollection>();
DisplayMode currentDisplayMode;
std::vector<sptr<DisplayMode>> displayList;
sptr<DisplayMode> pDisplay = nullptr;
@ -308,7 +280,7 @@ namespace xna {
pDisplay->impl->Descriptions.push_back(description);
}
else {
pDisplay = New<DisplayMode>();
pDisplay = snew<DisplayMode>();
pDisplay->Width = modedesc.Width;
pDisplay->Height = modedesc.Height;
pDisplay->Format = DxHelpers::ConvertDXGIFORMATToSurface(modedesc.Format);

View File

@ -1,4 +1,4 @@
#include "xna/platform-dx/implementations.hpp"
#include "xna/platform-dx/dx.hpp"
namespace xna {
void AudioEngine::Initialize() {

View File

@ -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<PlatformImplementation>();
}
BlendState::BlendState() : BlendState(nullptr) {}
BlendState::BlendState(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
impl = uNew<PlatformImplementation>();
impl = unew<PlatformImplementation>();
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<Int>(impl->sampleMask);
}
void BlendState::MultiSampleMast(Int value) {
impl->sampleMask = static_cast<UINT>(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> BlendState::Opaque() {
auto blendState = uNew<BlendState>();
auto blendState = unew<BlendState>();
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> BlendState::AlphaBlend() {
auto blendState = std::unique_ptr<BlendState>(new BlendState());
auto blendState = unew<BlendState>();
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> BlendState::Additive() {
auto blendState = std::unique_ptr<BlendState>(new BlendState());
auto blendState = unew<BlendState>();
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> BlendState::NonPremultiplied() {
auto blendState = std::unique_ptr<BlendState>(new BlendState());
auto blendState = unew<BlendState>();
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;

View File

@ -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<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
ConstantBuffer::ConstantBuffer(sptr<GraphicsDevice> const& device) : GraphicsResource(device){
impl = uNew<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
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<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
DataBuffer::DataBuffer(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
impl = uNew<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
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<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
IndexBuffer::IndexBuffer(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
impl = uNew<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
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<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
VertexBuffer::VertexBuffer(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
impl = uNew<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
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<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
VertexInputLayout::VertexInputLayout(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
impl = uNew<PlatformImplementation>();
impl = unew<PlatformImplementation>();
}
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;

View File

@ -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<PlatformImplementation>();
impl = unew<PlatformImplementation>();
impl->dxDescription = defaultDesc();
}
DepthStencilState::DepthStencilState(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
impl = uNew<PlatformImplementation>();
impl = unew<PlatformImplementation>();
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> DepthStencilState::None() {
auto stencil = uNew<DepthStencilState>();
auto stencil = unew<DepthStencilState>();
stencil->impl->dxDescription.DepthEnable = false;
stencil->impl->dxDescription.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
@ -90,7 +81,7 @@ namespace xna {
}
uptr<DepthStencilState> DepthStencilState::Default() {
auto stencil = uNew<DepthStencilState>();
auto stencil = unew<DepthStencilState>();
stencil->impl->dxDescription.DepthEnable = true;
stencil->impl->dxDescription.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
@ -98,31 +89,31 @@ namespace xna {
}
uptr<DepthStencilState> DepthStencilState::DepthRead() {
auto stencil = uNew<DepthStencilState>();
auto stencil = unew<DepthStencilState>();
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<D3D11_DEPTH_WRITE_MASK>(value);
}
void DepthStencilState::DepthCompareFunction(ComparisonFunction value) {
void DepthStencilState::DepthBufferFunction(ComparisonFunction value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.DepthFunc = static_cast<D3D11_COMPARISON_FUNC>(_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<UINT8>(value);
}
@ -130,64 +121,64 @@ namespace xna {
impl->dxDescription.StencilWriteMask = static_cast<UINT8>(value);
}
void DepthStencilState::StencilFrontFacePass(StencilOperation value) {
void DepthStencilState::StencilPass(StencilOperation value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.FrontFace.StencilPassOp = static_cast<D3D11_STENCIL_OP>(_value);
}
void DepthStencilState::StencilFrontFaceFail(StencilOperation value) {
void DepthStencilState::StencilFail(StencilOperation value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.FrontFace.StencilFailOp = static_cast<D3D11_STENCIL_OP>(_value);
}
void DepthStencilState::StencilFrontFaceDepthFail(StencilOperation value) {
void DepthStencilState::StencilDepthBufferFail(StencilOperation value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.FrontFace.StencilDepthFailOp = static_cast<D3D11_STENCIL_OP>(_value);
}
void DepthStencilState::StencilFrontFaceCompare(ComparisonFunction value) {
void DepthStencilState::StencilFunction(ComparisonFunction value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.FrontFace.StencilFunc = static_cast<D3D11_COMPARISON_FUNC>(_value);
}
void DepthStencilState::StencilBackFacePass(StencilOperation value) {
void DepthStencilState::CounterClockwiseStencilPass(StencilOperation value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.BackFace.StencilPassOp = static_cast<D3D11_STENCIL_OP>(_value);
}
void DepthStencilState::StencilBackFaceFail(StencilOperation value) {
void DepthStencilState::CounterClockwiseStencilFail(StencilOperation value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.BackFace.StencilFailOp = static_cast<D3D11_STENCIL_OP>(_value);
}
void DepthStencilState::StencilBackFaceDepthFail(StencilOperation value) {
void DepthStencilState::CounterClockwiseStencilDepthBufferFail(StencilOperation value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.BackFace.StencilDepthFailOp = static_cast<D3D11_STENCIL_OP>(_value);
}
void DepthStencilState::StencilBackFaceCompare(ComparisonFunction value) {
void DepthStencilState::CounterClockwiseStencilFunction(ComparisonFunction value) {
const auto _value = static_cast<int>(value) + 1;
impl->dxDescription.BackFace.StencilFunc = static_cast<D3D11_COMPARISON_FUNC>(_value);
}
bool DepthStencilState::DepthEnabled() const {
bool DepthStencilState::DepthBufferEnable() const {
return impl->dxDescription.DepthEnable;
}
bool DepthStencilState::DepthWriteEnabled() const {
bool DepthStencilState::DepthBufferWriteEnable() const {
return static_cast<bool>(impl->dxDescription.DepthWriteMask);
}
ComparisonFunction DepthStencilState::DepthCompareFunction() const {
ComparisonFunction DepthStencilState::DepthBufferFunction() const {
const auto _value = static_cast<int>(impl->dxDescription.DepthFunc) - 1;
return static_cast<ComparisonFunction>(_value);
}
bool DepthStencilState::StencilEnabled() const {
bool DepthStencilState::StencilEnable() const {
return impl->dxDescription.StencilEnable;
}
Int DepthStencilState::StencilReadMask() const {
Int DepthStencilState::StencilMask() const {
return static_cast<int>(impl->dxDescription.StencilReadMask);
}
@ -195,42 +186,42 @@ namespace xna {
return static_cast<int>(impl->dxDescription.StencilWriteMask);
}
StencilOperation DepthStencilState::StencilFrontFacePass() const {
StencilOperation DepthStencilState::StencilPass() const {
const auto _value = static_cast<int>(impl->dxDescription.FrontFace.StencilPassOp) - 1;
return static_cast<StencilOperation>(_value);
}
StencilOperation DepthStencilState::StencilFrontFaceFail() const {
StencilOperation DepthStencilState::StencilFail() const {
const auto _value = static_cast<int>(impl->dxDescription.FrontFace.StencilFailOp) - 1;
return static_cast<StencilOperation>(_value);
}
StencilOperation DepthStencilState::StencilFrontFaceDepthFail() const {
StencilOperation DepthStencilState::StencilDepthBufferFail() const {
const auto _value = static_cast<int>(impl->dxDescription.FrontFace.StencilDepthFailOp) - 1;
return static_cast<StencilOperation>(_value);
}
ComparisonFunction DepthStencilState::StencilFrontFaceCompare() const {
ComparisonFunction DepthStencilState::StencilFunction() const {
const auto _value = static_cast<int>(impl->dxDescription.FrontFace.StencilFunc) - 1;
return static_cast<ComparisonFunction>(_value);
}
StencilOperation DepthStencilState::StencilBackFacePass() const {
StencilOperation DepthStencilState::CounterClockwiseStencilPass() const {
const auto _value = static_cast<int>(impl->dxDescription.BackFace.StencilPassOp) - 1;
return static_cast<StencilOperation>(_value);
}
StencilOperation DepthStencilState::StencilBackFaceFail() const {
StencilOperation DepthStencilState::CounterClockwiseStencilFail() const {
const auto _value = static_cast<int>(impl->dxDescription.BackFace.StencilFailOp) - 1;
return static_cast<StencilOperation>(_value);
}
StencilOperation DepthStencilState::StencilBackFaceDepthFail() const {
StencilOperation DepthStencilState::CounterClockwiseStencilDepthBufferFail() const {
const auto _value = static_cast<int>(impl->dxDescription.BackFace.StencilDepthFailOp) - 1;
return static_cast<StencilOperation>(_value);
}
ComparisonFunction DepthStencilState::StencilBackFaceCompare() const {
ComparisonFunction DepthStencilState::CounterClockwiseStencilFunction() const {
const auto _value = static_cast<int>(impl->dxDescription.BackFace.StencilFunc) - 1;
return static_cast<ComparisonFunction>(_value);
}

View File

@ -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<PlatformImplementation>();
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<PlatformImplementation>();
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<float>(bounds.Width),
static_cast<float>(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<xna::SwapChain>(_this);
impl->_swapChain = snew<xna::SwapChain>(_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<RenderTarget2D>(_this);
impl->_renderTarget2D = snew<RenderTarget2D>(_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<GraphicsAdapter> 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<xna::BlendState> GraphicsDevice::BlendState() const {
return impl->_blendState;
}
void GraphicsDevice::BlendState(sptr<xna::BlendState> const& value) {
impl->_blendState = value;
}
sptr<xna::DepthStencilState> GraphicsDevice::DepthStencilState() const {
return impl->_depthStencilState;
}
void GraphicsDevice::DepthStencilState(sptr<xna::DepthStencilState> const& value) {
impl->_depthStencilState = value;
}
sptr<xna::RasterizerState> GraphicsDevice::RasterizerState() const {
return impl->_rasterizerState;
}
void GraphicsDevice::RasterizerState(sptr<xna::RasterizerState> const& value) {
impl->_rasterizerState = value;
}
sptr<SamplerStateCollection> GraphicsDevice::SamplerStates() const {
return impl->_samplerStates;
}
Int GraphicsDevice::MultiSampleMask() const {
return impl->_multiSampleMask;
}
void GraphicsDevice::MultiSampleMask(Int value) {
impl->_multiSampleMask = value;
}
}

View File

@ -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<PlatformImplementation>();
}
DisplayMode::~DisplayMode() {
impl = nullptr;
}
impl = unew<PlatformImplementation>();
}
size_t DisplayModeCollection::SurfaceCount(SurfaceFormat format) const
{

View File

@ -0,0 +1,781 @@
#include "xna/graphics/effect.hpp"
#include "xna/platform-dx/dx.hpp"
namespace xna {
Effect::Effect(sptr<GraphicsDevice> const& device, std::vector<Byte> const& effectCode) :
GraphicsResource(device) {
if (!device)
throw std::invalid_argument("Effect::Effect: invalid argument (device).");
impl = unew<PlatformImplementation>();
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<EffectTechnique>();
technique->impl->dxContext = m_device->impl->_context;
technique->impl->dxContext->AddRef();
tech->Release();
tech = nullptr;
return technique;
}
EffectAnnotation::EffectAnnotation() {
impl = unew<PlatformImplementation>();
}
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<Int>(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<Int>(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<Int>(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<PlatformImplementation>();
}
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<EffectAnnotationCollection>();
std::vector<PEffectAnnotation> list(annotCount);
for (size_t i = 0; i < annotCount; ++i) {
auto current = impl->dxPass->GetAnnotationByIndex(i);
auto annotation = snew<EffectAnnotation>();
annotation->impl->dxVariable = current;
annotation->impl->dxVariable->AddRef();
current->Release();
current = nullptr;
list[i] = annotation;
}
auto collection = snew<EffectAnnotationCollection>(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<PlatformImplementation>();
}
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<EffectAnnotationCollection>();
std::vector<PEffectAnnotation> list(annotCount);
for (size_t i = 0; i < annotCount; ++i) {
auto current = impl->dxTechnique->GetAnnotationByIndex(i);
auto annotation = snew<EffectAnnotation>();
annotation->impl->dxVariable = current;
annotation->impl->dxVariable->AddRef();
current->Release();
current = nullptr;
list[i] = annotation;
}
auto collection = snew<EffectAnnotationCollection>(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<EffectPassCollection>();
std::vector<PEffectPass> list(passCount);
for (size_t i = 0; i < passCount; ++i) {
auto current = impl->dxTechnique->GetPassByIndex(i);
auto pass = snew<EffectPass>();
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<EffectPassCollection>(list);
return collection;
}
EffectParameter::EffectParameter() {
impl = unew<PlatformImplementation>();
}
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<EffectAnnotationCollection>();
std::vector<PEffectAnnotation> list(annotCount);
for (size_t i = 0; i < annotCount; ++i) {
auto current = impl->dxVariable->GetAnnotationByIndex(i);
auto annotation = snew<EffectAnnotation>();
annotation->impl->dxVariable = current;
annotation->impl->dxVariable->AddRef();
current->Release();
current = nullptr;
list[i] = annotation;
}
auto collection = snew<EffectAnnotationCollection>(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<Int>(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<Int>(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<EffectParameterCollection> EffectParameter::Elements() const {
uint32_t index = 0;
auto collection = snew<EffectParameterCollection>();
while (true) {
auto el = impl->dxVariable->GetElement(index);
if (!el)
break;
auto efparam = snew<EffectParameter>();
efparam->impl->dxVariable = el;
efparam->impl->dxVariable->AddRef();
el->Release();
el = nullptr;
}
return collection;
}
sptr<EffectParameterCollection> EffectParameter::StructureMembers() const {
uint32_t index = 0;
auto collection = snew<EffectParameterCollection>();
while (true) {
auto member = impl->dxVariable->GetMemberByIndex(index);
if (!member)
break;
auto efparam = snew<EffectParameter>();
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<bool> EffectParameter::GetValueBooleanArray(size_t count) const {
auto scalar = impl->dxVariable->AsScalar();
auto arr = std::make_unique<bool[]>(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<bool> 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<Int> EffectParameter::GetValueInt32Array(size_t count) const {
auto scalar = impl->dxVariable->AsScalar();
std::vector<Int> 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<Matrix> EffectParameter::GetValueMatrixArray(size_t count) const {
auto matrix = impl->dxVariable->AsMatrix();
const auto elements = count * 16;
auto arr = std::make_unique<float[]>(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<Matrix> 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;
}
}

View File

@ -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<PlatformImplementation>();
services = New<GameServiceContainer>();
services = snew<GameServiceContainer>();
auto iservice = reinterpret_pointer_cast<IServiceProvider>(services);
_contentManager = New<ContentManager>(services, "");
_contentManager = snew<ContentManager>(services, "");
_contentManager->_gameServices = iservice;
_gameWindow = New<GameWindow>();
_gameWindow = snew<GameWindow>();
_gameWindow->impl->Color(146, 150, 154);
_gameWindow->Title("XN65");
_gameWindow->impl->Size(
GraphicsDeviceManager::DefaultBackBufferWidth,
GraphicsDeviceManager::DefaultBackBufferHeight, false);
_gameComponents = New<GameComponentCollection>();
_gameComponents = snew<GameComponentCollection>();
}
Game::~Game() {

View File

@ -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<PlatformImplementation>();
impl->_dxGamePad = uNew<DirectX::GamePad>();
impl = unew<PlatformImplementation>();
}
GamePadState GamePad::GetState(PlayerIndex index) {

View File

@ -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<Game> const& game) : _game(game)
@ -83,12 +83,11 @@ namespace xna {
}
bool initDevice(GraphicsDeviceInformation& info, Game& game, sptr<GraphicsDevice>& device)
{
auto& window = info.Window;
device = New<GraphicsDevice>(info);
{
device = snew<GraphicsDevice>(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;
}

View File

@ -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() {

View File

@ -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<PlatformImplementation>();
impl->_dxKeyboard = uNew<DirectX::Keyboard>();
impl = unew<PlatformImplementation>();
}
bool Keyboard::IsConnected() {

View File

@ -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<PlatformImplementation>();
impl->_dxMouse = uNew<DirectX::Mouse>();
impl = unew<PlatformImplementation>();
}
}

View File

@ -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<PlatformImplementation>();
}
RasterizerState::RasterizerState() : RasterizerState(nullptr){}
RasterizerState::RasterizerState(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
impl = unew<PlatformImplementation>();
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> RasterizerState::CullNone()
{
auto raster = uNew<RasterizerState>();
auto raster = unew<RasterizerState>();
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> RasterizerState::CullClockwise()
{
auto raster = uNew<RasterizerState>();
auto raster = unew<RasterizerState>();
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> RasterizerState::CullCounterClockwise()
{
auto raster = uNew<RasterizerState>();
auto raster = unew<RasterizerState>();
raster->impl->dxDescription.FillMode = D3D11_FILL_SOLID;
raster->impl->dxDescription.CullMode = D3D11_CULL_MODE::D3D11_CULL_BACK;
raster->impl->dxDescription.DepthClipEnable = true;

View File

@ -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;

View File

@ -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<PlatformImplementation>();
}
SamplerState::SamplerState() : SamplerState(nullptr){}
SamplerState::SamplerState(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
impl = unew<PlatformImplementation>();
}
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<D3D11_COMPARISON_FUNC>(static_cast<int>(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<ComparisonFunction>(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;
}

View File

@ -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;

View File

@ -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;

View File

@ -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 <stdexcept>
#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<Vector3> const& kerning,
std::optional<Char> defaultCharacter) :
textureValue(texture), glyphData(glyphs), croppingData(cropping),
characterMap(charMap), lineSpacing(lineSpacing), spacing(spacing),
kerning(kerning), defaultCharacter(defaultCharacter)
std::optional<Char> 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<DxGlyph> 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<LONG>(glyphs[i].Left());
g.Subrect.right = static_cast<LONG>(glyphs[i].Right());
g.Subrect.top = static_cast<LONG>(glyphs[i].Top());
g.Subrect.bottom = static_cast<LONG>(glyphs[i].Bottom());
g.Character = static_cast<Uint>(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<float>(cropping[i].Y);
g.XAdvance = kerning[i].Z + spacing;
}
else {
g.XOffset = 0;
g.YOffset = 0;
g.XAdvance = spacing;
}
dxGlyps[i] = g;
}
impl = uNew<PlatformImplementation>();
impl = unew<PlatformImplementation>();
impl->_dxSpriteFont = unew<DxSpriteFont>(
//ID3D11ShaderResourceView* texture
texture->impl->dxShaderResource,
@ -68,14 +76,7 @@ namespace xna {
const auto defChar = static_cast<wchar_t>(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<DirectX::SpriteSortMode>(static_cast<int>(value));
Char SpriteFont::DefaultCharacter() const {
const auto defChar = impl->_dxSpriteFont->GetDefaultCharacter();
return static_cast<Char>(defChar);
}
void SpriteFont::DefaultCharacter(Char value) {
const auto defChar = static_cast<wchar_t>(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<Int>(space);
}
void SpriteFont::LineSpacing(Int value) {
impl->_dxSpriteFont->SetLineSpacing(static_cast<float>(value));
}
SpriteBatch::SpriteBatch(sptr<GraphicsDevice> const& device) : GraphicsResource(device) {
if (!device->impl->_context)
return;
implementation = uNew<PlatformImplementation>();
implementation->_dxspriteBatch = New<DxSpriteBatch>(device.impl->_context);
implementation = unew<PlatformImplementation>();
implementation->_dxspriteBatch = snew<DxSpriteBatch>(
//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<Rectangle> 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<Rectangle> 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<Rectangle> 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<Rectangle> 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<Rectangle> 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;

View File

@ -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<UINT>(parameters->BackBufferWidth);
impl->dxDescription.Height = static_cast<UINT>(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;

View File

@ -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> Texture2D::FromStream(GraphicsDevice& device, String const& fileName, xna_error_ptr_arg)
sptr<Texture2D> Texture2D::FromStream(GraphicsDevice& device, String const& fileName)
{
auto _this = device.shared_from_this();
auto texture2d = New<Texture2D>(_this);
auto texture2d = snew<Texture2D>(_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<UINT>(width);
impl->dxDescription.Height = static_cast<UINT>(height);
impl->dxDescription.MipLevels = static_cast<UINT>(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<Uint> const& data, size_t startIndex, size_t elementCount, xna_error_ptr_arg)
void Texture2D::SetData(std::vector<Uint> 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<Byte> const& data, size_t startIndex, size_t elementCount, xna_error_ptr_arg)
void Texture2D::SetData(std::vector<Byte> 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<UINT> 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<Byte> const& data, size_t startIndex, size_t elementCount, xna_error_ptr_arg)
void Texture2D::SetData(Int level, Rectangle* rect, std::vector<Byte> 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<UINT> 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<Color> const& data, size_t startIndex, size_t elementCount, xna_error_ptr_arg)
void Texture2D::SetData(std::vector<Color> 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<UINT> finalData(elementCount);
@ -303,13 +279,13 @@ namespace xna {
++finalDataIndex;
}
internalSetData(*impl, *m_device, finalData.data(), err);
internalSetData(*impl, *m_device, finalData.data());
}
sptr<Texture2D> Texture2D::FromMemory(GraphicsDevice& device, std::vector<Byte> const& data, xna_error_ptr_arg)
sptr<Texture2D> Texture2D::FromMemory(GraphicsDevice& device, std::vector<Byte> const& data)
{
auto _this = device.shared_from_this();
auto texture2d = New<Texture2D>(_this);
auto texture2d = snew<Texture2D>(_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;

View File

@ -1,4 +1,4 @@
#include "xna/platform-dx/implementations.hpp"
#include "xna/platform-dx/dx.hpp"
namespace xna {
GameWindow::GameWindow() {

BIN
inc/effects11/Effects11.lib Normal file

Binary file not shown.

1212
inc/effects11/d3dx11effect.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,7 @@
#include <cmath>
#include "../default.hpp"
#include <optional>
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<Rectangle>() const {
return std::make_optional<Rectangle>(X, Y, Width, Height);
}
constexpr Int Left() const { return X; }
constexpr Int Right() const { return X + Width; }
constexpr Int Top() const { return Y; }

View File

@ -28,7 +28,7 @@ namespace xna {
if (a_device.has_value())
device = std::any_cast<sptr<GraphicsDevice>>(a_device);
auto texture2D = New<Texture2D>(device, width, height, mipMaps, format);
auto texture2D = snew<Texture2D>(device, width, height, mipMaps, format);
for (size_t level = 0; level < mipMaps; ++level) {
auto elementCount = input.ReadInt32();

View File

@ -3,7 +3,6 @@
#include "../types.hpp"
#include "../enums.hpp"
#include "../xnaerror.hpp"
#include <fstream>
#include <filesystem>

View File

@ -51,7 +51,7 @@ namespace xna {
template <class T>
inline sptr<Type> typeof() {
if (std::is_arithmetic<T>::value) {
auto primitiveType = New<Type>();
auto primitiveType = snew<Type>();
primitiveType->fullName = typeid(T).name();
primitiveType->isPrimitive = true;
primitiveType->isValueType = true;
@ -59,7 +59,7 @@ namespace xna {
}
if (std::is_enum<T>::value) {
auto enumType = New<Type>();
auto enumType = snew<Type>();
enumType->fullName = typeid(T).name();
enumType->isValueType = true;
enumType->isEnum = true;
@ -67,14 +67,14 @@ namespace xna {
}
if (std::is_pointer<T>::value) {
auto pointerType = New<Type>();
auto pointerType = snew<Type>();
pointerType->fullName = typeid(T).name();
pointerType->isPointer = true;
return pointerType;
}
if (std::is_class<T>::value) {
auto classType = New<Type>();
auto classType = snew<Type>();
classType->fullName = typeid(T).name();
classType->isClass = true;

View File

@ -2,4 +2,4 @@
#include "forward.hpp"
#include "enums.hpp"
#include "helpers.hpp"
#include "xnaerror.hpp"
#include "exception.hpp"

View File

@ -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,

48
inc/xna/exception.hpp Normal file
View File

@ -0,0 +1,48 @@
#ifndef XNA_EXCEPTION_HPP
#define XNA_EXCEPTION_HPP
#include <stdexcept>
#include <string>
#include <source_location>
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

View File

@ -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;

View File

@ -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<DisplayModeCollection> SupportedDisplayModes() const;
//Returns a collection of supported display modes for the current adapter.
uptr<DisplayModeCollection> SupportedDisplayModes(SurfaceFormat surfaceFormat) const;
//Gets the current display mode.
sptr<DisplayMode> CurrentDisplayMode();
//Gets the current display mode.
void CurrentDisplayMode(SurfaceFormat surfaceFormat, Uint width, Uint height);
//Gets the default adapter.
static uptr<GraphicsAdapter> DefaultAdapter();
static void Adapters(std::vector<sptr<GraphicsAdapter>>& adapters);
//Collection of available adapters on the system.
static void Adapters(std::vector<uptr<GraphicsAdapter>>& adapters);
public:

View File

@ -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<GraphicsDevice> const& device);
~BlendState() override;
bool Initialize(xna_error_nullarg) ;
void AlphaToCoverageEnable(bool value) ;
void IndependentBlendEnable(bool value) ;
void RenderTargets(std::vector<BlendRenderTarget> 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<BlendRenderTarget> 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<BlendState> Opaque();
//A built-in state object with settings for alpha blend,
//that is blending the source and destination data using alpha.
static uptr<BlendState> 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<BlendState> 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<BlendState> NonPremultiplied();
public:
struct PlatformImplementation;
uptr<PlatformImplementation> impl = nullptr;
};
using PBlendState = sptr<BlendState>;
}
#endif

View File

@ -10,7 +10,7 @@ namespace xna {
ConstantBuffer();
ConstantBuffer(sptr<GraphicsDevice> const&);
~ConstantBuffer() override;
bool Initialize(xna_error_nullarg);
bool Initialize();
public:
struct PlatformImplementation;
@ -22,7 +22,7 @@ namespace xna {
DataBuffer();
DataBuffer(sptr<GraphicsDevice> const&);
~DataBuffer() override;
bool Initialize(xna_error_nullarg);
bool Initialize();
public:
struct PlatformImplementation;
@ -36,8 +36,8 @@ namespace xna {
~IndexBuffer() override;
template <typename T>
bool Initialize(std::vector<T> const& data, xna_error_nullarg);
bool Apply(xna_error_nullarg);
bool Initialize(std::vector<T> const& data);
bool Apply();
public:
struct PlatformImplementation;
@ -50,8 +50,8 @@ namespace xna {
VertexBuffer(sptr<GraphicsDevice> const&);
~VertexBuffer();
template <typename T>
bool Initialize(std::vector<T> const& data, xna_error_nullarg);
bool Apply(xna_error_nullarg);
bool Initialize(std::vector<T> const& data);
bool Apply();
public:
struct PlatformImplementation;
@ -64,7 +64,7 @@ namespace xna {
VertexInputLayout(sptr<GraphicsDevice> const&);
~VertexInputLayout();
bool Initialize(DataBuffer& blob, xna_error_nullarg);
bool Initialize(DataBuffer& blob);
public:
struct PlatformImplementation;

View File

@ -5,54 +5,95 @@
#include "gresource.hpp"
namespace xna {
//Contains depth-stencil state for the device.
class DepthStencilState : public GraphicsResource {
public:
DepthStencilState();
DepthStencilState(sptr<GraphicsDevice> 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<DepthStencilState> None();
//A built-in state object with default settings for using a depth stencil buffer.
static uptr<DepthStencilState> Default();
//A built-in state object with settings for enabling a read-only depth stencil buffer.
static uptr<DepthStencilState> DepthRead();
bool Initialize();
bool Apply();
public:
struct PlatformImplementation;
uptr<PlatformImplementation> impl = nullptr;
};
using PDepthStencilState = sptr<DepthStencilState>;
}
#endif

View File

@ -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<GraphicsDevice> {
public:
GraphicsDevice();
GraphicsDevice(GraphicsDeviceInformation const& info);
~GraphicsDevice();
//Gets the graphics adapter.
sptr<GraphicsAdapter> 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<xna::BlendState> 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<xna::BlendState> const& value);
//Gets or sets a system-defined instance of a depth-stencil state object. The default value is DepthStencilState.Default.
sptr<xna::DepthStencilState> DepthStencilState() const;
//Gets or sets a system-defined instance of a depth-stencil state object. The default value is DepthStencilState.Default.
void DepthStencilState(sptr<xna::DepthStencilState> const& value);
//Gets or sets rasterizer state. The default value is RasterizerState.CullCounterClockwise.
sptr<xna::RasterizerState> RasterizerState() const;
//Gets or sets rasterizer state. The default value is RasterizerState.CullCounterClockwise.
void RasterizerState(sptr<xna::RasterizerState> const& value);
//Retrieves a collection of SamplerState objects for the current GraphicsDevice.
sptr<SamplerStateCollection> 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<GraphicsAdapter> Adapter() const;
void Adapter(sptr<GraphicsAdapter> 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<PlatformImplementation> impl = nullptr;
};
using PGraphicsDevice = sptr<GraphicsDevice>;
}
#endif

View File

@ -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<PlatformImplementation> impl;
};
//Manipulates a collection of DisplayMode structures.
class DisplayModeCollection {
public:
constexpr DisplayModeCollection() = default;

300
inc/xna/graphics/effect.hpp Normal file
View File

@ -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<PlatformImplementation> impl;
public:
EffectAnnotation();
};
using PEffectAnnotation = sptr<EffectAnnotation>;
class EffectAnnotationCollection {
public:
EffectAnnotationCollection() {}
EffectAnnotationCollection(std::vector<PEffectAnnotation> 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<PEffectAnnotation> data;
};
using PEffectAnnotationCollection = sptr<EffectAnnotationCollection>;
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<PlatformImplementation> impl;
public:
EffectPass();
};
using PEffectPass = sptr<EffectPass>;
class EffectPassCollection {
public:
EffectPassCollection() {}
EffectPassCollection(std::vector<PEffectPass> 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<PEffectPass> data;
};
using PEffectPassCollection = sptr<EffectPassCollection>;
class EffectTechnique {
public:
PEffectAnnotationCollection Annotations() const;
String Name() const;
PEffectPassCollection Passes() const;
public:
struct PlatformImplementation;
uptr<PlatformImplementation> impl;
public:
EffectTechnique();
};
using PEffectTechnique = sptr<EffectTechnique>;
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<EffectParameterCollection> Elements() const;
//Gets the collection of structure members.
sptr<EffectParameterCollection> StructureMembers() const;
bool GetValueBoolean() const;
std::vector<bool> GetValueBooleanArray(size_t count) const;
Int GetValueInt32() const;
std::vector <Int> GetValueInt32Array(size_t count) const;
Matrix GetValueMatrix() const;
std::vector <Matrix> GetValueMatrixArray(size_t count) const;
Matrix GetValueMatrixTranspose() const;
std::vector <Matrix> GetValueMatrixTransposeArray(size_t count) const;
Quaternion GetValueQuaternion() const;
std::vector <Quaternion> GetValueQuaternionArray() const;
float GetValueSingle() const;
std::vector<float> GetValueSingleArray() const;
String GetValueString() const;
sptr<Texture2D> GetValueTexture2D() const;
sptr<Texture3D> GetValueTexture3D() const;
sptr<TextureCube> GetValueTextureCube() const;
Vector2 GetValueVector2() const;
std::vector <Vector2> GetValueVector2Array() const;
Vector3 GetValueVector3() const;
std::vector <Vector3> GetValueVector3Array() const;
Vector4 GetValueVector4() const;
std::vector <Vector4> GetValueVector4Array() const;
void SetValue(bool value);
void SetValue(std::vector<bool> const& value);
void SetValue(Int value);
void SetValue(std::vector<Int> const& value);
void SetValue(float value);
void SetValue(std::vector<float> const& value);
void SetValue(Matrix const& value);
void SetValue(std::vector<Matrix> const& value);
void SetValue(Quaternion const& value);
void SetValue(std::vector<Quaternion> const& value);
void SetValue(Vector2 const& value);
void SetValue(std::vector<Vector2> const& value);
void SetValue(Vector3 const& value);
void SetValue(std::vector<Vector3> const& value);
void SetValue(Vector4 const& value);
void SetValue(std::vector<Vector4> const& value);
void SetValue(String const& value);
void SetValue(sptr<Texture> const& value);
void SetValueTranspose(Matrix const& value);
void SetValueTranspose(std::vector<Matrix> const& value);
public:
struct PlatformImplementation;
uptr<PlatformImplementation> impl;
public:
EffectParameter();
};
using PEffectParameter = sptr<EffectParameter>;
class EffectParameterCollection {
public:
EffectParameterCollection() {}
EffectParameterCollection(std::vector<PEffectParameter> 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<PEffectParameter> data;
};
using PEffectPassCollection = sptr<EffectPassCollection>;
class Effect : public GraphicsResource {
Effect(sptr<GraphicsDevice> const& device, std::vector<Byte> const& effectCode);
PEffectTechnique CurrentTechnique() const;
public:
struct PlatformImplementation;
uptr<PlatformImplementation> 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

View File

@ -4,20 +4,17 @@
#include "../default.hpp"
namespace xna {
//Queries and prepares resources.
class GraphicsResource {
public:
GraphicsResource(sptr<GraphicsDevice> const& device) : m_device(device){}
GraphicsResource(sptr<GraphicsDevice> const& device);
virtual ~GraphicsResource(){}
virtual bool Bind(sptr<GraphicsDevice> const& device) {
if (!device || device == m_device)
return false;
virtual bool Bind(sptr<GraphicsDevice> const& device);
m_device = device;
return true;
}
//Gets the GraphicsDevice associated with this GraphicsResource.
sptr<xna::GraphicsDevice> Device() const;
protected:
sptr<GraphicsDevice> m_device = nullptr;

View File

@ -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<GraphicsDevice> 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<RasterizerState> CullNone();
//A built-in state object with settings for culling primitives with clockwise winding order.
static uptr<RasterizerState> CullClockwise();
//A built-in state object with settings for culling primitives with counter-clockwise winding order.
static uptr<RasterizerState> CullCounterClockwise();
bool Initialize();
bool Apply();
public:
struct PlatformImplementation;
uptr<PlatformImplementation> impl = nullptr;
};
using PRasterizerState = sptr<RasterizerState>;
}
#endif

View File

@ -11,8 +11,8 @@ namespace xna {
RenderTarget2D(sptr<GraphicsDevice> const& device);
~RenderTarget2D() override;
bool Initialize(xna_error_nullarg);
bool Apply(xna_error_nullarg);
bool Initialize();
bool Apply();
public:
struct PlatformImplementation;

View File

@ -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<GraphicsDevice> 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<SamplerState> PoinWrap();
//Contains default state for point filtering and texture coordinate clamping.
static uptr<SamplerState> PointClamp();
//Contains default state for linear filtering and texture coordinate wrapping.
static uptr<SamplerState> LinearWrap();
//Contains default state for linear filtering and texture coordinate clamping.
static uptr<SamplerState> LinearClamp();
//Contains default state for anisotropic filtering and texture coordinate wrapping.
static uptr<SamplerState> AnisotropicWrap();
//Contains default state for anisotropic filtering and texture coordinate clamping.
static uptr<SamplerState> AnisotropicClamp();
ComparisonFunction Comparison() const;
void Comparison(ComparisonFunction value);
bool Initialize();
bool Apply();
public:
struct PlatformImplementation;
uptr<PlatformImplementation> impl = nullptr;
};
using PSamplerState = sptr<SamplerState>;
//Collection of SamplerState objects.
class SamplerStateCollection {
public:
SamplerStateCollection(){}
SamplerStateCollection(size_t size)
: samplers(size){}
SamplerStateCollection(std::vector<PSamplerState> const& samplers)
: samplers(samplers) {}
PSamplerState operator[](size_t index) {
if (index >= samplers.size())
return nullptr;
return samplers[index];
}
public:
std::vector<PSamplerState> samplers;
};
using PSamplerStateCollection = sptr<SamplerStateCollection>;
}
#endif

View File

@ -10,7 +10,7 @@ namespace xna {
Shader();
Shader(sptr<GraphicsDevice> 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<GraphicsDevice> 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<GraphicsDevice> const& device);
~PixelShader() override;
bool Initialize(DataBuffer& buffer, xna_error_nullarg);
bool Initialize(DataBuffer& buffer);
public:
struct PlatformImplementation;

View File

@ -5,12 +5,15 @@
#include "../common/numerics.hpp"
#include "../common/color.hpp"
#include <optional>
#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<GraphicsDevice> 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<Texture2D> 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<Texture2D> const& texture, Vector2 const& position, Color const& color) { Draw(*texture, position, color); }
void Draw(sptr<Texture2D> 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<Texture2D> 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<Texture2D> const& texture, Vector2 const& position, std::optional<Rectangle> const& sourceRectangle, Color const& color) { Draw(*texture, position, sourceRectangle, color); }
void Draw(sptr<Texture2D> const& texture, Vector2 const& position, std::optional<Rectangle> const& sourceRectangle, Color const& color) { Draw(*texture, position, sourceRectangle, color); }
void Draw(Texture2D& texture, Vector2 const& position, std::optional<Rectangle> const& sourceRectangle, Color const& color);
void Draw(sptr<Texture2D> 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<Texture2D> const& texture, Vector2 const& position, std::optional<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(sptr<Texture2D> const& texture, Vector2 const& position, std::optional<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, std::optional<Rectangle> const& sourceRectangle, Color const& color,
float rotation, Vector2 const& origin, float scale, SpriteEffects effects, float layerDepth);
void Draw(sptr<Texture2D> 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<Texture2D> const& texture, Vector2 const& position, std::optional<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(sptr<Texture2D> const& texture, Vector2 const& position, std::optional<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, std::optional<Rectangle> const& sourceRectangle, Color const& color,
float rotation, Vector2 const& origin, Vector2 const& scale, SpriteEffects effects, float layerDepth);
void Draw(sptr<Texture2D> const& texture, Rectangle const& destinationRectangle, Color const& color) {
Draw(*texture, destinationRectangle, color);
}
void Draw(uptr<Texture2D> const& texture, Rectangle const& destinationRectangle, Color const& color) { Draw(*texture, destinationRectangle, color); }
void Draw(sptr<Texture2D> 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<Texture2D> 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<Texture2D> const& texture, Rectangle const& destinationRectangle, std::optional<Rectangle> const& sourceRectangle, Color const& color) { Draw(*texture, destinationRectangle, sourceRectangle, color); }
void Draw(sptr<Texture2D> const& texture, Rectangle const& destinationRectangle, std::optional<Rectangle> const& sourceRectangle, Color const& color) { Draw(*texture, destinationRectangle, sourceRectangle, color); }
void Draw(Texture2D& texture, Rectangle const& destinationRectangle, std::optional<Rectangle> const& sourceRectangle, Color const& color);
void Draw(sptr<Texture2D> 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<Texture2D> const& texture, Rectangle const& destinationRectangle, std::optional<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(sptr<Texture2D> const& texture, Rectangle const& destinationRectangle, std::optional<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, std::optional<Rectangle> 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<SpriteFont> const& spriteFont, String const& text, Vector2 const& position, Color const& color) {
DrawString(*spriteFont, text, position, color);
}
void DrawString(uptr<SpriteFont> const& spriteFont, String const& text, Vector2 const& position, Color const& color) { DrawString(*spriteFont, text, position, color); }
void DrawString(sptr<SpriteFont> 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<SpriteFont> 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<SpriteFont> 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<PlatformImplementation> implementation = nullptr;
};
//Represents a font texture.
class SpriteFont {
public:
SpriteFont(
@ -91,20 +101,21 @@ namespace xna {
Int lineSpacing,
float spacing,
std::vector<Vector3> const& kerning,
std::optional<Char> defaultCharacter);
~SpriteFont();
std::optional<Char> 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<Texture2D> textureValue = nullptr;
std::vector<Rectangle> glyphData;
std::vector<Rectangle> croppingData;
std::vector<Char> characterMap;
Int lineSpacing{0};
float spacing{0};
std::vector<Vector3> kerning;
std::optional<Char> 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;

View File

@ -10,7 +10,7 @@ namespace xna {
SwapChain();
SwapChain(sptr<GraphicsDevice> const& device);
~SwapChain() override;
bool Initialize(xna_error_nullarg);
bool Initialize();
bool Present(bool vsync);
bool GetBackBuffer(Texture2D& texture2D);
public:

View File

@ -20,13 +20,13 @@ namespace xna {
Int Width() const;
Int Height() const;
Rectangle Bounds() const;
bool Initialize(xna_error_nullarg);
void SetData(std::vector<Color> const& data, size_t startIndex = 0, size_t elementCount = 0, xna_error_nullarg);
void SetData(std::vector<Uint> const& data, size_t startIndex = 0, size_t elementCount = 0, xna_error_nullarg);
void SetData(std::vector<Byte> const& data, size_t startIndex = 0, size_t elementCount = 0, xna_error_nullarg);
void SetData(Int level, Rectangle* rect, std::vector<Byte> const& data, size_t startIndex, size_t elementCount, xna_error_nullarg);
static sptr<Texture2D> FromStream(GraphicsDevice& device, String const& fileName, xna_error_nullarg);
static sptr<Texture2D> FromMemory(GraphicsDevice& device, std::vector<Byte> const& data, xna_error_nullarg);
bool Initialize();
void SetData(std::vector<Color> const& data, size_t startIndex = 0, size_t elementCount = 0);
void SetData(std::vector<Uint> const& data, size_t startIndex = 0, size_t elementCount = 0);
void SetData(std::vector<Byte> const& data, size_t startIndex = 0, size_t elementCount = 0);
void SetData(Int level, Rectangle* rect, std::vector<Byte> const& data, size_t startIndex, size_t elementCount);
static sptr<Texture2D> FromStream(GraphicsDevice& device, String const& fileName);
static sptr<Texture2D> FromMemory(GraphicsDevice& device, std::vector<Byte> const& data);
public:
struct PlatformImplementation;

View File

@ -3,13 +3,20 @@
#include <string>
#include <utility>
#include <stdexcept>
#include "exception.hpp"
namespace xna {
//Class for helper functions
struct XnaHelper {
//
// Smart Pointer Comparator
//
template<typename T> struct is_shared_ptr : std::false_type {};
template<typename T> struct is_shared_ptr<std::shared_ptr<T>> : 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 <class T>
static constexpr void HashCombine(std::size_t& seed, const T& v) {
std::hash<T> 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<typename T>
static inline auto ReturnDefaultOrNull() {
static inline auto ReturnDefaultOrNull(const std::source_location location = std::source_location::current()) {
if constexpr (is_shared_ptr<T>::value)
return (T)nullptr;
else if (std::is_default_constructible<T>::value)
return T();
else
throw std::runtime_error("Unable to build object");
Exception::Throw(ExMessage::BuildObject, location);
}
};
}

View File

@ -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<PlatformImplementation> impl = nullptr;
private:
GamePad();
GamePad(GamePad&&);
GamePad(GamePad&);
inline static uptr<PlatformImplementation> impl = nullptr;
};
}

View File

@ -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<unsigned char>(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<PlatformImplementation> impl = nullptr;

View File

@ -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<PlatformImplementation> impl = nullptr;
inline static uptr<PlatformImplementation> impl = nullptr;
};
}

1120
inc/xna/platform-dx/dx.hpp Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +0,0 @@
//DirectX
#include "dxgi.h"
#include "d3d11.h"
#include <d3d11_1.h>
#include <d3d11_2.h>
//HSLS
#include <d3dcompiler.h>
//DirectXTK
#include <DirectXMath.h>
#include <Audio.h>
#include <BufferHelpers.h>
#include <CommonStates.h>
#include <DDSTextureLoader.h>
#include <DirectXHelpers.h>
#include <Effects.h>
#include <GamePad.h>
#include <GeometricPrimitive.h>
#include <GraphicsMemory.h>
#include <Keyboard.h>
#include <Model.h>
#include <Mouse.h>
#include <PostProcess.h>
#include <PrimitiveBatch.h>
#include <ScreenGrab.h>
#include <SimpleMath.h>
#include <SpriteBatch.h>
#include <SpriteFont.h>
#include <VertexTypes.h>
#include <WICTextureLoader.h>
//Windows
#define NOMINMAX
#include <Windows.h>
#include <windowsx.h>
#include <Windows.Foundation.h>
#include <wrl\wrappers\corewrappers.h>
#include <wrl\client.h>

View File

@ -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<D3D11_BLEND_OP>(static_cast<int>(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<D3D11_TEXTURE_ADDRESS_MODE>(static_cast<int>(value) + 1);
}
static constexpr void ConvertAddressMode(D3D11_TEXTURE_ADDRESS_MODE value, TextureAddressMode& target) {
target = static_cast<TextureAddressMode>(value - 1);
}
};
}

View File

@ -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<DirectX::SpriteFont> _dxSpriteFont = nullptr;
};
struct SpriteBatch::PlatformImplementation {
sptr<DirectX::SpriteBatch> _dxspriteBatch = nullptr;
};
struct GraphicsAdapter::PlatformImplementation {
~PlatformImplementation() {
if (dxadapter) {
dxadapter->Release();
dxadapter = nullptr;
}
}
IDXGIAdapter1* dxadapter = nullptr;
private:
friend class GraphicsAdapter;
Uint _index{ 0 };
sptr<DisplayMode> _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<DisplayModeDescription> Descriptions;
};
struct GamePad::PlatformImplementation {
inline static uptr<DirectX::GamePad> _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<DirectX::Keyboard> _dxKeyboard = nullptr;
void ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) {
if (_dxKeyboard)
_dxKeyboard->ProcessMessage(message, wParam, lParam);
}
};
struct Mouse::PlatformImplementation {
inline static uptr<DirectX::Mouse> _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<D3D11_INPUT_ELEMENT_DESC> _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<int>(mode);
}
constexpr GameWindowMode Mode() const {
return static_cast<GameWindowMode>(_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<DirectX::AudioEngine>(
#ifdef _DEBUG
DirectX::AudioEngine_Debug
#endif
);
}
~PlatformImplementation() {
if (_dxAudioEngine) {
_dxAudioEngine->Suspend();
}
}
uptr<DirectX::AudioEngine> _dxAudioEngine = nullptr;
};
struct GraphicsDevice::PlatformImplementation {
ID3D11Device* _device{ nullptr };
ID3D11DeviceContext* _context{ nullptr };
IDXGIFactory1* _factory = nullptr;
sptr<SwapChain> _swapChain{ nullptr };
sptr<GraphicsAdapter> _adapter{ nullptr };
sptr<RenderTarget2D> _renderTarget2D{ nullptr };
sptr<BlendState> _blendState{ nullptr };
xna::Viewport _viewport{};
sptr<xna::PresentationParameters> _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<DirectX::SoundEffectInstance> _dxInstance = nullptr;
};
struct SoundEffect::PlatformImplementation {
~PlatformImplementation() {
}
uptr<DirectX::SoundEffect> _dxSoundEffect = nullptr;
};
template <typename T>
inline bool IndexBuffer::Initialize(std::vector<T> 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 <typename T>
inline bool VertexBuffer::Initialize(std::vector<T> 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

View File

@ -36,7 +36,7 @@ namespace xna {
template <typename T>
static void insertActivadorReader() {
ContentTypeReaderActivador::SetActivador(typeof<T>(), []() -> sptr<ContentTypeReader> {
auto obj = New <T>();
auto obj = snew<T>();
return reinterpret_pointer_cast<ContentTypeReader>(obj);
});
}

View File

@ -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 <cmath>
#include <cstdint>
#include <exception>
#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<uint64_t>(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<double>(ticks) / TicksPerSecond; }
static constexpr uint64_t SecondsToTicks(double seconds) noexcept { return static_cast<uint64_t>(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<typename TUpdate>
void Tick(const TUpdate& update)
{
// Query the current time.
LARGE_INTEGER currentTime;
if (!QueryPerformanceCounter(&currentTime))
{
throw std::exception();
}
uint64_t timeDelta = static_cast<uint64_t>(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<uint64_t>(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<uint64_t>(std::abs(static_cast<int64_t>(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<uint64_t>(m_qpcFrequency.QuadPart))
{
m_framesPerSecond = m_framesThisSecond;
m_framesThisSecond = 0;
m_qpcSecondCounter %= static_cast<uint64_t>(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

View File

@ -1,4 +0,0 @@
#include "headers.hpp"
#include "implementations.hpp"
#include "init.hpp"
#include "steptimer.hpp"

View File

@ -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();
};
}

View File

@ -8,8 +8,14 @@
#include <memory>
#include <utility>
#include <cassert>
#include <optional>
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<Sbyte>::max)();
constexpr Sbyte SbyteMinValue = (std::numeric_limits<Sbyte>::min)();
constexpr Byte ByteMaxValue = (std::numeric_limits<Byte>::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 <typename T>
using sptr = std::shared_ptr<T>;
//Same as std::unique_ptr
template <typename T>
using uptr = std::unique_ptr<T>;
template <class _Ty, class... _Types>
inline std::shared_ptr<_Ty> New(_Types&&... _Args) {
return std::make_shared<_Ty>(std::forward<_Types>(_Args)...);
}
template <class _Ty, class... _Types>
inline std::unique_ptr<_Ty> uNew(_Types&&... _Args) {
return std::make_unique<_Ty>(std::forward<_Types>(_Args)...);
}
using uptr = std::unique_ptr<T>;
//Same as std::make_shared
template <class _Ty, class... _Types>
inline std::shared_ptr<_Ty> snew(_Types&&... _Args) {
return std::make_shared<_Ty>(std::forward<_Types>(_Args)...);
}
//Same as std::make_unique
template <class _Ty, class... _Types>
inline std::unique_ptr<_Ty> unew(_Types&&... _Args) {
return std::make_unique<_Ty>(std::forward<_Types>(_Args)...);

View File

@ -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"
#include "xna/platform-dx/dx.hpp"

View File

@ -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

View File

@ -15,7 +15,7 @@ namespace xna {
void Initialize() override {
auto game = reinterpret_cast<Game*>(this);
graphics = New<GraphicsDeviceManager>(game->shared_from_this());
graphics = snew<GraphicsDeviceManager>(game->shared_from_this());
graphics->Initialize();
std::any device = graphicsDevice;
@ -25,7 +25,7 @@ namespace xna {
}
void LoadContent() override {
spriteBatch = New<SpriteBatch>(*graphicsDevice);
spriteBatch = snew<SpriteBatch>(graphicsDevice);
auto texture = Content()->Load<PTexture2D>("Idle");
Game::LoadContent();
}

View File

@ -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);
}
}

View File

@ -21,7 +21,7 @@ namespace PlatformerStarterKit {
void Initialize() override {
auto game = reinterpret_cast<Game*>(this);
graphics = New<GraphicsDeviceManager>(game->shared_from_this());
graphics = snew<GraphicsDeviceManager>(game->shared_from_this());
graphics->Initialize();
std::any device = graphicsDevice;
@ -31,7 +31,7 @@ namespace PlatformerStarterKit {
}
void LoadContent() override {
spriteBatch = New<SpriteBatch>(*graphicsDevice);
spriteBatch = snew<SpriteBatch>(graphicsDevice);
// Load fonts
hudFont = Content()->Load<PSpriteFont>("Fonts/Hud");

View File

@ -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);
}
}

View File

@ -3,5 +3,5 @@
#
# Add source to this project's executable.
#add_subdirectory ("01_blank")
add_subdirectory ("01_blank")
add_subdirectory ("02_PlatfformerStarterKit")