Jump to content

  • Log In with Google      Sign In   
  • Create Account

Sluggish D3D on Init and Live Devices


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
No replies to this topic

#1 KingofNoobs   Members   -  Reputation: 301

Like
0Likes
Like

Posted 25 October 2012 - 02:25 PM

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
// © 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 );
}

Attached Files


I wonder as I wander...

http://www.davesgameoflife.com


Sponsor:



Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS