• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
KingofNoobs

DX11
Sluggish D3D on Init and Live Devices

0 posts in this topic

Hello,

I have finally gotten my object oriented engine base to render a 2d image. I have also done this by following and amending tutorial 2 from the directx sdk documentation, and it worked smoothly in the tutorial (i.e. one source file, no objects).

In my oo program, there are live devices on shutdown and significant sluggishness in response. It takes a few seconds for the window to respond to movements on a top of the line system.

I will spend all day tomorrow finding out what the bug is here, but maybe one of you could spot it even faster? I have posted the source below in text and attached the entire project in .zip form as well.

Thanks in advance for your help.


/////////////////////////////////////////////////////////////////////////////////////////////
// Filename: D3DClass.cpp
// (c) Dave Ottley, 2012. All rights reserved.
/////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////
// INCLUDES
///////////////////////////
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <assert.h>
#include <vector>
#include <memory>
#include <d3dcompiler.h>
#include <d3d11.h>
#include <D3DX11.h>
///////////////////////////
// MY INCLUDES
///////////////////////////
#include "D3DClass.h"
#include "Constants.h"
#include "WindowsClass.h"
#include "Util.h"
#include "WICTextureLoader.h"

#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dx11.lib")
#pragma comment(lib, "dxerr.lib")
#pragma comment(lib, "d3dcompiler.lib")
/////////////////////////////////////////////////////////////////////////////////////////////
//
// CONSTRUCTOR / GET INSTANCE
//
/////////////////////////////////////////////////////////////////////////////////////////////
D3DClass::D3DClass()
:
mDevice(0),
mContext(0),
mSwapChain(0),
mRenderTargetView(0),
mDepthStencilView(0),
mDepthStencilBuffer(0),
mDepthEnabledStencilState(0),
mDepthDisabledStencilState(0),
mRasterizerState(0),
mVRam(0),
mRefreshNumerator(0),
mRefreshDenominator(0),
mPixelShader(0),
mVertexShader(0),
mSamplerLinear(0),
mAtlas(0),
mVertexBuffer(0),
mIndexBuffer(0),
mVertexLayout(0),
mVSBlob(0),
mPSBlob(0),
mVSync(VSYNC),
mFullscreen(FULL_SCREEN),
mNearPlane(NEAR_PLANE),
mFarPlane(FAR_PLANE),
mFeatureLevel(D3D_FEATURE_LEVEL_9_1),
mDriverType(D3D_DRIVER_TYPE_NULL)
{
ZeroMemory(mDriverTypeName, 200);
ZeroMemory(mFeatureLevelName, 200);

for(int i = 0; i < 256; ++i)
{
mVideoCardDescription[i] = 0;
}
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
mCameraPos = XMFLOAT4(0.0f, 0.0f, -10.0f, 1.0f);
mCameraTarget = XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f);
XMMATRIX I = XMMatrixIdentity();
XMStoreFloat4x4(&mIWorld, I);
XMMATRIX O = XMMatrixOrthographicLH((float) WindowsCls->GetScreenWidth(), (float)WindowsCls->GetScreenHeight(), mNearPlane, mFarPlane);
XMStoreFloat4x4(&mOrtho, O);
XMMATRIX P = XMMatrixPerspectiveFovLH(FOV_ANGLE, GetAspectRatio(), mNearPlane, mFarPlane);
XMStoreFloat4x4(&mProj, P);
XMMATRIX V = XMMatrixLookAtLH(XMLoadFloat4(&mCameraPos), XMLoadFloat4(&mCameraTarget), up);
XMStoreFloat4x4(&mView, V);

}
D3DClass * D3DClass::GetInstance()
{
static D3DClass theOne;
return &theOne;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// DESTRUCTOR / SHUTDOWN
//
/////////////////////////////////////////////////////////////////////////////////////////////
D3DClass::~D3DClass()
{

}
void D3DClass::Shutdown()
{
HRESULT hr = 0;
//Disable full screen before shutting down.
mSwapChain->SetFullscreenState(FALSE, NULL);
//Release all COM objects
ReleaseCOM(mVertexBuffer);
ReleaseCOM(mIndexBuffer);
ReleaseCOM(mVertexLayout);
ReleaseCOM(mVertexShader);
ReleaseCOM(mPixelShader);
ReleaseCOM(mAtlas);
//ReleaseCOM(mVSBlob);
//ReleaseCOM(mPSBlob);
ReleaseCOM(mRasterizerState);
ReleaseCOM(mDepthDisabledStencilState);
ReleaseCOM(mDepthEnabledStencilState);
ReleaseCOM(mDepthStencilBuffer);
ReleaseCOM(mDepthStencilView);
ReleaseCOM(mRenderTargetView);
ReleaseCOM(mSwapChain);
ReleaseCOM(mContext);
ReleaseCOM(mDevice);
ReleaseCOM(mSamplerLinear);

}

/////////////////////////////////////////////////////////////////////////////////////////////
//
// INITIALIZE
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::Initialize()
{
if(!SetVideoCardInfo())
return false;
if(!CreateDeviceAndSwapChain())
return false;
if(!LoadCompiledShadersFromFile() )
return false;
if(!CreateRenderTargetView())
return false;
if(!CreateDepthStencilView())
return true;
if(!SetRasterizerState())
return false;
if(!CreateSamplerState())
return false;
if(!LoadMasterTextureAtlas())
return false;
if(!CreateBuffers())
return false;
SetViewport();
SetPrimitiveTopology();
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// ON RESIZE
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::OnResize()
{
//...
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// SET VIDEO CARD INFO
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::SetVideoCardInfo()
{
HRESULT result;
IDXGIFactory * factory;
IDXGIAdapter * adapter;
IDXGIOutput * adapterOutput;
unsigned int numModes, stringLength;
DXGI_MODE_DESC * displayModeList;
DXGI_ADAPTER_DESC adapterDesc;
// Create a DirectX graphics interface factory.
result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
if(FAILED(result))
{
return false;
}
// Use the factory to create an adapter for the primary graphics interface (video card).
result = factory->EnumAdapters(0, &adapter);
if(FAILED(result))
{
return false;
}
// Enumerate the primary adapter output (monitor).
result = adapter->EnumOutputs(0, &adapterOutput);
if(FAILED(result))
{
return false;
}
// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
if(FAILED(result))
{
return false;
}
// Create a list to hold all the possible display modes for this monitor/video card combination.
displayModeList = new DXGI_MODE_DESC[numModes];
if(!displayModeList)
{
return false;
}
// Now fill the display mode list structures.
result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
if(FAILED(result))
{
return false;
}
// Now go through all the display modes and find the one that matches the screen width and height.
// When a match is found store the numerator and denominator of the refresh rate for that monitor.
for(UINT i=0; i<numModes; i++)
{
if(displayModeList[i].Width == (unsigned int)WindowsCls->GetScreenWidth() )
{
if(displayModeList[i].Height == (unsigned int)WindowsCls->GetScreenHeight() )
{
mRefreshNumerator = displayModeList[i].RefreshRate.Numerator;
mRefreshDenominator = displayModeList[i].RefreshRate.Denominator;
}
}
}
// Get the adapter (video card) description.
result = adapter->GetDesc(&adapterDesc);
if(FAILED(result))
{
return false;
}
// Store the dedicated video card memory in megabytes.
mVRam = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
// Convert the name of the video card to a character array and store it.
int error = wcstombs_s(&stringLength, mVideoCardDescription, 128, adapterDesc.Description, 256);
if(error != 0)
{
return false;
}
// Release the display mode list.
delete [] displayModeList;
displayModeList = 0;
// Release the adapter output.
ReleaseCOM(adapterOutput);
// Release the adapter.
ReleaseCOM(adapter);
// Release the factory.
ReleaseCOM(factory);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// CREATE DEVICE AND SWAP CHAIN
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateDeviceAndSwapChain()
{
// Variables
HRESULT result;
DXGI_SWAP_CHAIN_DESC swapChainDesc;
UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0, //try first
D3D_FEATURE_LEVEL_10_1, //and so on...
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1,
};
UINT numFeatureLevels = ARRAYSIZE( featureLevels );
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE, //try first
D3D_DRIVER_TYPE_WARP, //and so on...
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE( driverTypes );
// Initialize the swap chain description.
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Width = WindowsCls->GetScreenWidth();
swapChainDesc.BufferDesc.Height = WindowsCls->GetScreenHeight();
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
if(mVSync)
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = mRefreshNumerator;
swapChainDesc.BufferDesc.RefreshRate.Denominator = mRefreshDenominator;
}
else
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = WindowsCls->GetHwnd();
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.Windowed = !mFullscreen;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = 0;
// Create the swap chain, Direct3D device, and Direct3D device context.
for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
{
mDriverType = driverTypes[driverTypeIndex];
result = D3D11CreateDeviceAndSwapChain( NULL,
mDriverType,
NULL,
createDeviceFlags,
featureLevels,
numFeatureLevels,
D3D11_SDK_VERSION,
&swapChainDesc,
&mSwapChain,
&mDevice,
&mFeatureLevel,
&mContext);
if( SUCCEEDED(result))
{
switch(driverTypeIndex)
{
case 0:
wcscpy_s(mDriverTypeName, L"Hardware");
break;
case 1:
wcscpy_s(mDriverTypeName, L"WARP");
break;
default:
wcscpy_s(mDriverTypeName, L"Reference");
break;
}
switch(mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_11_0");
break;
case D3D_FEATURE_LEVEL_10_1:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_1");
break;
case D3D_FEATURE_LEVEL_10_0:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_0");
break;
case D3D_FEATURE_LEVEL_9_3:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_0");
break;
case D3D_FEATURE_LEVEL_9_2:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_0");
break;
case D3D_FEATURE_LEVEL_9_1:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_0");
break;
default:
wcscpy_s(mFeatureLevelName, L"Unsupported Feature Level");
break;
}
}
}
MakeWindowAssociation();
if(FAILED(result))
{
return false;
}
return true;
}

/////////////////////////////////////////////////////////////////////////////////////////////
//
// CREATE RENDER TARGET VIEW
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateRenderTargetView()
{
HRESULT result;
ID3D11Texture2D* backBufferPtr;
// Get the pointer to the back buffer.
result = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
if(FAILED(result))
{
return false;
}
// Create the render target view with the back buffer pointer.
result = mDevice->CreateRenderTargetView(backBufferPtr, NULL, &mRenderTargetView);
if(FAILED(result))
{
return false;
}
// Release pointer to the back buffer as we no longer need it.
ReleaseCOM(backBufferPtr);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// CREATE DEPTH STENCIL VIEW
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateDepthStencilView()
{
HRESULT result;
D3D11_TEXTURE2D_DESC depthBufferDesc;
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
// Initialize the description of the depth buffer.
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
// Set up the description of the depth buffer.
depthBufferDesc.Width = WindowsCls->GetScreenWidth();
depthBufferDesc.Height = WindowsCls->GetScreenHeight();
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
// Create the texture for the depth buffer using the filled out description.
result = mDevice->CreateTexture2D(&depthBufferDesc, NULL, &mDepthStencilBuffer);
if(FAILED(result))
{
return false;
}
// Initialize the description of the stencil state.
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
// Set up the description of the stencil state.
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
// Stencil operations if pixel is front-facing.
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Stencil operations if pixel is back-facing.
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create the depth stencil state.
result = mDevice->CreateDepthStencilState(&depthStencilDesc, &mDepthEnabledStencilState);
if(FAILED(result))
{
return false;
}

// Clear the second depth stencil state before setting the parameters.
ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
// Now create a second depth stencil state which turns off the Z buffer for 2D rendering. The only difference is
// that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
depthDisabledStencilDesc.DepthEnable = false;
depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthDisabledStencilDesc.StencilEnable = true;
depthDisabledStencilDesc.StencilReadMask = 0xFF;
depthDisabledStencilDesc.StencilWriteMask = 0xFF;
depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create the state using the device.
result = mDevice->CreateDepthStencilState(&depthDisabledStencilDesc, &mDepthDisabledStencilState);
if(FAILED(result))
{
return false;
}
// Set the depth stencil state.
mContext->OMSetDepthStencilState(mDepthDisabledStencilState, 1);
// Initialize the depth stencil view.
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
// Set up the depth stencil view description.
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
// Create the depth stencil view.
result = mDevice->CreateDepthStencilView(mDepthStencilBuffer, &depthStencilViewDesc, &mDepthStencilView);
if(FAILED(result))
{
return false;
}
// Bind the render target view and depth stencil view to the output render pipeline.
mContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);

return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// SET RASTERIZER STATE
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::SetRasterizerState()
{
HRESULT result;
D3D11_RASTERIZER_DESC rasterDesc;
// Setup the raster description which will determine how and what polygons will be drawn.
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;
// Create the rasterizer state from the description we just filled out.
result = mDevice->CreateRasterizerState(&rasterDesc, &mRasterizerState);
if(FAILED(result))
{
return false;
}
// Now set the rasterizer state.
mContext->RSSetState(mRasterizerState);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// SET VIEWPORT
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::SetViewport()
{
D3D11_VIEWPORT viewport;
// Setup the viewport for rendering.
viewport.Width = (float)WindowsCls->GetScreenWidth();
viewport.Height = (float)WindowsCls->GetScreenHeight();
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
// Create the viewport.
mContext->RSSetViewports(1, &viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// CLEAR OLD SCREEN WITH PINK FOR DEBUGGING
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::ClearScreen()
{
//float ClearColor[4] = { 0.0f, 0.125f, 0.6f, 1.0f };
// Clear the back buffer.
mContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::Magenta) );

// Clear the depth buffer.
mContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// PREPARE THE SCREEN FOR PRESENTATION
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::UpdateD3DFrame()
{
//...
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// PRESENT SCREEN
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::Present()
{
HRESULT hr;
// Set vertex and pixel shaders, primitive topology, samplers, and master texture
GetContext()->VSSetShader(mVertexShader, NULL, 0);
GetContext()->PSSetShader(mPixelShader, NULL, 0);
GetContext()->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
GetContext()->PSSetShaderResources( 0, 1, &mAtlas );
GetContext()->PSSetSamplers( 0, 1, &mSamplerLinear);
GetContext()->DrawIndexed( 6, 0, 0 );
// Present the back buffer to the screen since rendering is complete.
if(mVSync)
{
// Lock to screen refresh rate.
// OCCLUDED NEVER HAPPENING
hr = mSwapChain->Present(1, 0);
if(hr == DXGI_STATUS_OCCLUDED)
ApplicationCls->Pause();
}
else
{
// Present as fast as possible.
// OCCLUDED NEVER HAPPENING
hr = mSwapChain->Present(0, 0);
if(hr == DXGI_STATUS_OCCLUDED)
ApplicationCls->Pause();
}
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// TURN Z BUFFER ON
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::TurnZBufferOn()
{
mContext->OMSetDepthStencilState(mDepthEnabledStencilState, 1);
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// TURN Z BUFFER OFF
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::TurnZBufferOff()
{
mContext->OMSetDepthStencilState(mDepthDisabledStencilState, 1);
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// GET ASPECT RATIO
//
/////////////////////////////////////////////////////////////////////////////////////////////
const float D3DClass::GetAspectRatio() const
{
return (float) WindowsCls->GetScreenWidth() / WindowsCls->GetScreenHeight();
}

/////////////////////////////////////////////////////////////////////////////////////////////
//
// GET VIDEO CARD INFO
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::GetVideoCardInfo(char* cardName, int& memory) const
{
strcpy_s(cardName, 128, mVideoCardDescription);
memory = mVRam;
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// GETTERS
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
projectionMatrix = XMLoadFloat4x4(&mProj);
return;
}

void D3DClass::GetIWorldMatrix(XMMATRIX& worldMatrix)
{
worldMatrix = XMLoadFloat4x4(&mIWorld);
return;
}

void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix)
{
orthoMatrix = XMLoadFloat4x4(&mOrtho);
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Disallow Alt-Enter detect. Custom Define.
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::MakeWindowAssociation()
{
//COM queries to get at the correct IDXGIFactory instance used to create the device
//Query Interface
IDXGIDevice * dxgiDevice = 0;
mDevice->QueryInterface(__uuidof(IDXGIDevice), (void**) &dxgiDevice);
if(!dxgiDevice)
return false;
//Query Adapter
IDXGIAdapter * dxgiAdapter = 0;
dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**) &dxgiAdapter);
if(!dxgiAdapter)
return false;
//Finally get the IDXGIFactory interface.
IDXGIFactory * dxgiFactory = 0;
dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**) &dxgiFactory);
if(!dxgiFactory)
return false;
//Disallow Automatic Alt-Enter detect, custom define.
HR(dxgiFactory->MakeWindowAssociation(WindowsCls->GetHwnd(), DXGI_MWA_NO_WINDOW_CHANGES) );
//Release our acquired COM interfaces (because we are done with them).
ReleaseCOM(dxgiDevice);
ReleaseCOM(dxgiAdapter);
ReleaseCOM(dxgiFactory);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Load all shaders from pre-compiled .cso files in Assets
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::LoadCompiledShadersFromFile()
{
HRESULT hr = 0;
//Load compiled shaders into memory
LoadShaderFromFile(VS_NAME, &mVSBlob );
LoadShaderFromFile(PS_NAME, &mPSBlob );
hr = GetDevice()->CreateVertexShader(mVSBlob->GetBufferPointer(), mVSBlob->GetBufferSize(), 0, &mVertexShader);
hr = GetDevice()->CreatePixelShader(mPSBlob->GetBufferPointer(), mPSBlob->GetBufferSize(), 0, &mPixelShader);
if(!CreateLayout(mVSBlob->GetBufferPointer(), mVSBlob->GetBufferSize()) )
return false;

ReleaseCOM(mVSBlob);
ReleaseCOM(mPSBlob);
return true;
}
bool D3DClass::LoadShaderFromFile(const wchar_t * filename, ID3DBlob ** blob)
{
HRESULT hr = 0;
std::wstring fullpath(AppendCurrentDirectory(filename) );
//MessageBox(WindowsCls->GetHwnd(), buffer, 0, 0);


std::ifstream fin(fullpath.c_str(), std::ios::binary);
assert(fin);

fin.seekg(0, std::ios_base::end);

int size = (int)fin.tellg();
fin.seekg(0, std::ios_base::beg);
hr = D3DCreateBlob(size, blob);
fin.read((char*) (*blob)->GetBufferPointer(), (*blob)->GetBufferSize());
fin.close();
return true;
}
std::wstring D3DClass::AppendCurrentDirectory(const wchar_t * filename)
{
wchar_t buffer[1000];
GetCurrentDirectory(1000, buffer);
wcsncat_s(buffer, filename, wcslen(filename) );
return std::wstring(buffer);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Create the sampler state
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateSamplerState()
{
D3D11_SAMPLER_DESC sampDesc;
HRESULT hr = 0;
ZeroMemory( &sampDesc, sizeof(sampDesc) );
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
hr = GetDevice()->CreateSamplerState( &sampDesc, &mSamplerLinear );
if( FAILED( hr ) )
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Load one master texture atlas for the game (may expand later)
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::LoadMasterTextureAtlas()
{
HRESULT hr = 0;
std::wstring fullpath(AppendCurrentDirectory(MASTER_ATLAS_FILENAME) );
hr = D3DX11CreateShaderResourceViewFromFile( GetDevice(), fullpath.c_str(), NULL, NULL, &mAtlas, NULL );

//hr = CreateWICTextureFromFile(GetDevice(), GetContext(), MASTER_ATLAS_FILENAME, 0, &mAtlas, 0);
if( FAILED( hr ) )
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Create Vertex and Index Buffers
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateBuffers()
{
HRESULT hr = 0;
// Create vertex buffer
SimpleVertex vertices[] =
{

{ XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f) },
{ XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f) },
{ XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f) },
{ XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f) },
};
D3D11_BUFFER_DESC bd;
ZeroMemory( &bd, sizeof(bd) );
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( SimpleVertex ) * 4;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory( &InitData, sizeof(InitData) );
InitData.pSysMem = vertices;
hr = GetDevice()->CreateBuffer( &bd, &InitData, &mVertexBuffer );
if( FAILED( hr ) )
return false;
// Create index buffer
WORD indices[] =
{
0,1,2,
0,2,3,
};
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( WORD ) * 6; // 6 vertices needed
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
InitData.pSysMem = indices;
hr = GetDevice()->CreateBuffer( &bd, &InitData, &mIndexBuffer );
if( FAILED( hr ) )
return false;
// Set index buffer
GetContext()->IASetIndexBuffer( mIndexBuffer, DXGI_FORMAT_R16_UINT, 0 );
// Set vertex buffer
UINT stride = sizeof( SimpleVertex );
UINT offset = 0;
GetContext()->IASetVertexBuffers( 0, 1, &mVertexBuffer, &stride, &offset );
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Create Input Layout
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateLayout(const void * vertexBuffer, int size)
{
HRESULT hr = 0;
// Define the input layout
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE( layout );
// Create the input layout
hr = GetDevice()->CreateInputLayout( layout, numElements, vertexBuffer,
size, &mVertexLayout );
if( FAILED( hr ) )
return false;
// Set the input layout
GetContext()->IASetInputLayout( mVertexLayout );
return true;
}

void D3DClass::SetPrimitiveTopology()
{
// Set primitive topology
GetContext()->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
}
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By YixunLiu
      Hi,
      I have a surface mesh and I want to use a cone to cut a hole on the surface mesh.
      Anybody know a fast method to calculate the intersected boundary of these two geometries?
       
      Thanks.
       
      YL
       
    • By hiya83
      Hi, I tried searching for this but either I failed or couldn't find anything. I know there's D11/D12 interop and there are extensions for GL/D11 (though not very efficient). I was wondering if there's any Vulkan/D11 or Vulkan/D12 interop?
      Thanks!
    • By lonewolff
      Hi Guys,
      I am just wondering if it is possible to acquire the address of the backbuffer if an API (based on DX11) only exposes the 'device' and 'context' pointers?
      Any advice would be greatly appreciated
    • By MarcusAseth
      bool InitDirect3D::Init() { if (!D3DApp::Init()) { return false; } //Additional Initialization //Disable Alt+Enter Fullscreen Toggle shortkey IDXGIFactory* factory; CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory)); factory->MakeWindowAssociation(mhWindow, DXGI_MWA_NO_WINDOW_CHANGES); factory->Release(); return true; }  
      As stated on the title and displayed on the code above, regardless of it Alt+Enter still takes effect...
      I recall something from the book during the swapChain creation, where in order to create it one has to use the same factory used to create the ID3D11Device, therefore I tested and indeed using that same factory indeed it work.
      How is that one particular factory related to my window and how come the MakeWindowAssociation won't take effect with a newly created factory?
      Also what's even the point of being able to create this Factories if they won't work,?(except from that one associated with the ID3D11Device) 
    • By ProfL
      Can anyone recommend a wrapper for Direct3D 11 that is similarly simple to use as SFML? I don't need all the image formats etc. BUT I want a simple way to open a window, allocate a texture, buffer, shader.
  • Popular Now