• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By isu diss
      I'm following rastertek tutorial 14 (http://rastertek.com/tertut14.html). The problem is, slope based texturing doesn't work in my application. There are plenty of slopes in my terrain. None of them get slope color.
      float4 PSMAIN(DS_OUTPUT Input) : SV_Target { float4 grassColor; float4 slopeColor; float4 rockColor; float slope; float blendAmount; float4 textureColor; grassColor = txTerGrassy.Sample(SSTerrain, Input.TextureCoords); slopeColor = txTerMossRocky.Sample(SSTerrain, Input.TextureCoords); rockColor = txTerRocky.Sample(SSTerrain, Input.TextureCoords); // Calculate the slope of this point. slope = (1.0f - Input.LSNormal.y); if(slope < 0.2) { blendAmount = slope / 0.2f; textureColor = lerp(grassColor, slopeColor, blendAmount); } if((slope < 0.7) && (slope >= 0.2f)) { blendAmount = (slope - 0.2f) * (1.0f / (0.7f - 0.2f)); textureColor = lerp(slopeColor, rockColor, blendAmount); } if(slope >= 0.7) { textureColor = rockColor; } return float4(textureColor.rgb, 1); } Can anyone help me? Thanks.

    • By cozzie
      Hi all,
      As a part of the debug drawing system in my engine,  I want to add support for rendering simple text on screen  (aka HUD/ HUD style). From what I've read there are a few options, in short:
      1. Write your own font sprite renderer
      2. Using Direct2D/Directwrite, combine with DX11 rendertarget/ backbuffer
      3. Use an external library, like the directx toolkit etc.
      I want to go for number 2, but articles/ documentation confused me a bit. Some say you need to create a DX10 device, to be able to do this, because it doesn't directly work with the DX11 device.  But other articles tell that this was 'patched' later on and should work now.
      Can someone shed some light on this and ideally provide me an example or article on  how to set this up?
      All input is appreciated.
    • By stale
      I've just started learning about tessellation from Frank Luna's DX11 book. I'm getting some very weird behavior when I try to render a tessellated quad patch if I also render a mesh in the same frame. The tessellated quad patch renders just fine if it's the only thing I'm rendering. This is pictured below:
      However, when I attempt to render the same tessellated quad patch along with the other entities in the scene (which are simple triangle-lists), I get the following error:

      I have no idea why this is happening, and google searches have given me no leads at all. I use the following code to render the tessellated quad patch:
      ID3D11DeviceContext* dc = GetGFXDeviceContext(); dc->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST); dc->IASetInputLayout(ShaderManager::GetInstance()->m_JQuadTess->m_InputLayout); float blendFactors[] = { 0.0f, 0.0f, 0.0f, 0.0f }; // only used with D3D11_BLEND_BLEND_FACTOR dc->RSSetState(m_rasterizerStates[RSWIREFRAME]); dc->OMSetBlendState(m_blendStates[BSNOBLEND], blendFactors, 0xffffffff); dc->OMSetDepthStencilState(m_depthStencilStates[DSDEFAULT], 0); ID3DX11EffectTechnique* activeTech = ShaderManager::GetInstance()->m_JQuadTess->Tech; D3DX11_TECHNIQUE_DESC techDesc; activeTech->GetDesc(&techDesc); for (unsigned int p = 0; p < techDesc.Passes; p++) { TerrainVisual* terrainVisual = (TerrainVisual*)entity->m_VisualComponent; UINT stride = sizeof(TerrainVertex); UINT offset = 0; GetGFXDeviceContext()->IASetVertexBuffers(0, 1, &terrainVisual->m_VB, &stride, &offset); Vector3 eyePos = Vector3(cam->m_position); Matrix rotation = Matrix::CreateFromYawPitchRoll(entity->m_rotationEuler.x, entity->m_rotationEuler.y, entity->m_rotationEuler.z); Matrix model = rotation * Matrix::CreateTranslation(entity->m_position); Matrix view = cam->GetLookAtMatrix(); Matrix MVP = model * view * m_ProjectionMatrix; ShaderManager::GetInstance()->m_JQuadTess->SetEyePosW(eyePos); ShaderManager::GetInstance()->m_JQuadTess->SetWorld(model); ShaderManager::GetInstance()->m_JQuadTess->SetWorldViewProj(MVP); activeTech->GetPassByIndex(p)->Apply(0, GetGFXDeviceContext()); GetGFXDeviceContext()->Draw(4, 0); } dc->RSSetState(0); dc->OMSetBlendState(0, blendFactors, 0xffffffff); dc->OMSetDepthStencilState(0, 0); I draw my scene by looping through the list of entities and calling the associated draw method depending on the entity's "visual type":
      for (unsigned int i = 0; i < scene->GetEntityList()->size(); i++) { Entity* entity = scene->GetEntityList()->at(i); if (entity->m_VisualComponent->m_visualType == VisualType::MESH) DrawMeshEntity(entity, cam, sun, point); else if (entity->m_VisualComponent->m_visualType == VisualType::BILLBOARD) DrawBillboardEntity(entity, cam, sun, point); else if (entity->m_VisualComponent->m_visualType == VisualType::TERRAIN) DrawTerrainEntity(entity, cam); } HR(m_swapChain->Present(0, 0)); Any help/advice would be much appreciated!
    • By KaiserJohan
      Am trying a basebones tessellation shader and getting unexpected result when increasing the tessellation factor. Am rendering a group of quads and trying to apply tessellation to them.
      OutsideTess = (1,1,1,1), InsideTess= (1,1)

      OutsideTess = (1,1,1,1), InsideTess= (2,1)

      I expected 4 triangles in the quad, not two. Any idea of whats wrong?
      struct PatchTess { float mEdgeTess[4] : SV_TessFactor; float mInsideTess[2] : SV_InsideTessFactor; }; struct VertexOut { float4 mWorldPosition : POSITION; float mTessFactor : TESS; }; struct DomainOut { float4 mWorldPosition : SV_POSITION; }; struct HullOut { float4 mWorldPosition : POSITION; }; Hull shader:
      PatchTess PatchHS(InputPatch<VertexOut, 3> inputVertices) { PatchTess patch; patch.mEdgeTess[ 0 ] = 1; patch.mEdgeTess[ 1 ] = 1; patch.mEdgeTess[ 2 ] = 1; patch.mEdgeTess[ 3 ] = 1; patch.mInsideTess[ 0 ] = 2; patch.mInsideTess[ 1 ] = 1; return patch; } [domain("quad")] [partitioning("fractional_odd")] [outputtopology("triangle_ccw")] [outputcontrolpoints(4)] [patchconstantfunc("PatchHS")] [maxtessfactor( 64.0 )] HullOut hull_main(InputPatch<VertexOut, 3> verticeData, uint index : SV_OutputControlPointID) { HullOut ret; ret.mWorldPosition = verticeData[index].mWorldPosition; return ret; }  
      Domain shader:
      [domain("quad")] DomainOut domain_main(PatchTess patchTess, float2 uv : SV_DomainLocation, const OutputPatch<HullOut, 4> quad) { DomainOut ret; const float MipInterval = 20.0f; ret.mWorldPosition.xz = quad[ 0 ].mWorldPosition.xz * ( 1.0f - uv.x ) * ( 1.0f - uv.y ) + quad[ 1 ].mWorldPosition.xz * uv.x * ( 1.0f - uv.y ) + quad[ 2 ].mWorldPosition.xz * ( 1.0f - uv.x ) * uv.y + quad[ 3 ].mWorldPosition.xz * uv.x * uv.y ; ret.mWorldPosition.y = quad[ 0 ].mWorldPosition.y; ret.mWorldPosition.w = 1; ret.mWorldPosition = mul( gFrameViewProj, ret.mWorldPosition ); return ret; }  
      Any ideas what could be wrong with these shaders?
    • By simco50
      I've stumbled upon Urho3D engine and found that it has a really nice and easy to read code structure.
      I think the graphics abstraction looks really interesting and I like the idea of how it defers pipeline state changes until just before the draw call to resolve redundant state changes.
      This is done by saving the state changes (blendEnabled/SRV changes/RTV changes) in member variables and just before the draw, apply the actual state changes using the graphics context.
      It looks something like this (pseudo):
      void PrepareDraw() { if(renderTargetsDirty) { pD3D11DeviceContext->OMSetRenderTarget(mCurrentRenderTargets); renderTargetsDirty = false } if(texturesDirty) { pD3D11DeviceContext->PSSetShaderResourceView(..., mCurrentSRVs); texturesDirty = false } .... //Some more state changes } This all looked like a great design at first but I've found that there is one big issue with this which I don't really understand how it is solved in their case and how I would tackle it.
      I'll explain it by example, imagine I have two rendertargets: my backbuffer RT and an offscreen RT.
      Say I want to render my backbuffer to the offscreen RT and then back to the backbuffer (Just for the sake of the example).
      You would do something like this:
      //Render to the offscreen RT pGraphics->SetRenderTarget(pOffscreenRT->GetRTV()); pGraphics->SetTexture(diffuseSlot, pDefaultRT->GetSRV()) pGraphics->DrawQuad() pGraphics->SetTexture(diffuseSlot, nullptr); //Remove the default RT from input //Render to the default (screen) RT pGraphics->SetRenderTarget(nullptr); //Default RT pGraphics->SetTexture(diffuseSlot, pOffscreenRT->GetSRV()) pGraphics->DrawQuad(); The problem here is that the second time the application loop comes around, the offscreen rendertarget is still bound as input ShaderResourceView when it gets set as a RenderTargetView because in Urho3D, the state of the RenderTargetView will always be changed before the ShaderResourceViews (see top code snippet) even when I set the SRV to nullptr before using it as a RTV like above causing errors because a resource can't be bound to both input and rendertarget.
      What is usually the solution to this?
  • Advertisement
  • Advertisement
Sign in to follow this  

DX11 [DirectX] Beginning DX Learning - SwapChain::Present crashes program and driver

This topic is 2572 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I am just starting out with Direct X 11. I have been following these tutorials but I am stuck at the first lesson with actual rendering (drawing a triangle). Specifically, my program crashes when I reach the present line. Actually, it doesn't crash but my computer freezes up, then the screen goes blank, then comes back on with a message saying my display driver has crashed and my program doesn't do anything more. I have updated my drivers and my graphics card is running Direct X 11. Heres the code

#include <Windows.h>
#include <WindowsX.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>

#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dx11.lib")
#pragma comment (lib, "d3dx10.lib")

#define ScreenWidth 800
#define ScreenHeight 600

IDXGISwapChain *swapChain;
ID3D11Device *device;
ID3D11DeviceContext *devcon;
ID3D11RenderTargetView *backBuffer;

ID3D11VertexShader *mVertexShader;
ID3D11PixelShader *mPixelShader;

ID3D11Buffer *mVideoBuffer;
ID3D11InputLayout *mInputLayout;

struct Vertex
float x, y, z;

void Init3D(HWND windowHandle);
void RenderFrame();
void Clean3D();
void InitGraphics();
void InitPipeline();

LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
//MessageBox(NULL, "Hello world","My Window", MB_OK);
HWND windowHandle;
WNDCLASSEX windowClass;

ZeroMemory(&windowClass, sizeof(WNDCLASSEX));

windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WindowProc;
windowClass.hInstance = hInstance;
windowClass.hCursor = LoadCursor(NULL,IDC_ARROW);
//windowClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
windowClass.lpszClassName = "WindowClass1";


RECT desiredSize = {0,0,500,400};
AdjustWindowRect(&desiredSize,WS_OVERLAPPEDWINDOW, FALSE);

windowHandle = CreateWindowEx(NULL,"WindowClass1","TK Program", WS_OVERLAPPEDWINDOW,0,0,ScreenWidth,ScreenHeight,NULL, NULL, hInstance, NULL);

ShowWindow(windowHandle, nCmdShow);


MSG msg = {0};

if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))

if(msg.message == WM_QUIT)

//do some game related stuff
return msg.wParam;

LRESULT CALLBACK WindowProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
return 0;


return DefWindowProc (hWnd, message,wParam,lParam);

void Init3D(HWND windowHandle)
DXGI_SWAP_CHAIN_DESC swapChainDescription;
ZeroMemory(&swapChainDescription, sizeof(DXGI_SWAP_CHAIN_DESC));

swapChainDescription.BufferCount = 1;
swapChainDescription.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDescription.BufferDesc.Width = ScreenWidth;
swapChainDescription.BufferDesc.Height = ScreenHeight;
swapChainDescription.OutputWindow = windowHandle;
swapChainDescription.SampleDesc.Count = 4;
swapChainDescription.Windowed = true;

D3D11CreateDeviceAndSwapChain(NULL,D3D_DRIVER_TYPE_HARDWARE,NULL,NULL,NULL,NULL, D3D11_SDK_VERSION,&swapChainDescription, &swapChain,&device,NULL,&devcon);

ID3D11Texture2D *pBackBuffer = NULL;
device->CreateRenderTargetView(pBackBuffer, NULL, &backBuffer);

devcon->OMSetRenderTargets(1, &backBuffer,NULL);

D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = ScreenWidth;
viewport.Height = ScreenHeight;



void InitPipeline()
ID3D10Blob *vertexShader, *pixelShader;



D3D11_INPUT_ELEMENT_DESC inputElementDesc[] =


void InitGraphics()
Vertex OurVertices[] = {{0.0f, 0.5f, 0.0f, D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
{0.45f, -0.5, 0.0f, D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f)},
{-0.45f, -0.5f, 0.0f, D3DXCOLOR(0.0f, 0.0f, 1.0f, 1.0f)},
{0.7f,0.6f,0.3f,D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)}
D3D11_BUFFER_DESC bufferDescription;

bufferDescription.Usage = D3D11_USAGE_DYNAMIC;
bufferDescription.ByteWidth = 3 * sizeof(Vertex);
bufferDescription.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;


D3D11_MAPPED_SUBRESOURCE mappedSubResource;
devcon->Map(mVideoBuffer,NULL,D3D11_MAP_WRITE_DISCARD,NULL, &mappedSubResource);

void RenderFrame()
devcon->ClearRenderTargetView(backBuffer, D3DXCOLOR(0.0f,0.2f,0.4f,1.0f));

UINT stride = sizeof(Vertex);
UINT offset = 0;


void Clean3D()


Share this post

Link to post
Share on other sites
Use the flag D3D11_CREATE_DEVICE_DEBUG for the flags in D3D11CreateDeviceAndSwapChain, and then run with the debugger. You should get debug output if anything is wrong. Overall your code is unsafe as you don't seem to be checking any return values at all. D3D11 functions usually return a HRESULT value which will tell you if they failed.

Share this post

Link to post
Share on other sites

Use the flag D3D11_CREATE_DEVICE_DEBUG for the flags in D3D11CreateDeviceAndSwapChain, and then run with the debugger. You should get debug output if anything is wrong. Overall your code is unsafe as you don't seem to be checking any return values at all. D3D11 functions usually return a HRESULT value which will tell you if they failed.

Ok so I put in HRESULT results in front of all the methods that return HRESULT and the problem appear to be with the shader creation which returns "E_INVALIDARG". If I'm honest, the shader part was something the tutorial glossed over. What I did to incorporate the shader was add a file called "Shaders.hlsl" in to the source folder of the solution containing:

struct VOut
float4 position : SV_POSITION;
float4 color : COLOR;

VOut VShader(float4 position : POSITION, float4 color : COLOR)
VOut output;

output.position = position;
output.color = color;

return output;

float4 PShader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
return color;

The shader loading code is:

ID3D10Blob *vertexShader, *pixelShader;
LPVOID vertexBufferPointer = vertexShader->GetBufferPointer();
SIZE_T vertexBufferSize = vertexShader->GetBufferSize();
//HRESULT result = device->CreateVertexShader(vertexShader->GetBufferPointer(),vertexShader->GetBufferSize(),NULL,&mVertexShader);
HRESULT result = device->CreateVertexShader(vertexBufferPointer, vertexBufferSize,NULL,&mVertexShader);
result = device->CreatePixelShader(pixelShader->GetBufferPointer(),pixelShader->GetBufferSize(),NULL,&mPixelShader);

Is this where I am going wrong? Also, on a more general note, At each of the HRESULT points, should I be checking that they're ok before continuing? Would hate to be picking up bad practices when I have hardly begun!

Share this post

Link to post
Share on other sites
Yes, generally you want to check as much as possible, or at least methods that are somewhat likely to fail. Compiling shaders is one of those. Does it fail at CreateVertexShader or CreatePixelShader?
If you have a DX11 capable card that is somewhat strange, if D3DX11CompileFromFile succeeds. D3DX11CompileFromFile also returns a HRESULT, and the last parameter can give you compile errors for the shader.

Did you use the debug flag when creating your device?
If you try to call a D3D11 method and have some invalid parameters you will get debug output in the 'Output' window when running with the debugger, which will tell you what's wrong. In VC++, just press F5 to run with the debugger, and make sure to select Debug in the target menu, which should be the default if you didn't change it to Release.

Anyway, to correctly check for errors when compiling the shader, do something like this:

HRESULT hResult;

ID3DBlob *pCompiledCode = NULL;
ID3DBlob *pErrorMsgs = NULL;
hResult = D3DX11CompileFromFile(TEXT("Shaders.hlsl"), NULL, NULL, "VShader", "vs_5_0", 0, 0, NULL, &pCompiledCode, &pErrorMsgs, NULL);
if(FAILED(hResult)) {
MessageBoxA(NULL, (char*)pErrorMsgs->GetBufferPointer(), "D3DX11CompileFromFile failed", MB_OK);

ID3D11VertexShader *pVertexShader;
hResult = pDevice->CreateVertexShader(pCompiledCode->GetBufferPointer(), pCompiledCode->GetBufferSize(), NULL, &pVertexShader);
if(FAILED(hResult)) {
asdf; // Add breakpoint here

if(pErrorMsgs != NULL)


Couple that with D3D11_CREATE_DEVICE_DEBUG and you will be able to identify most errors easily.

From what I've heard directxtutorial.com has never been very good at any of this, and skips many things that are important to write safe and stable code. Then again there's not that many D3D11 tutorials I know about.. but you should definitely keep in mind that many functions can fail, and will fail, especially during development when you're changing things around. It's very easy to get a mistake into a shader, and without proper debug output you have no way of knowing which call failed.

Share this post

Link to post
Share on other sites

From what I've heard directxtutorial.com has never been very good at any of this, and skips many things that are important to write safe and stable code. Then again there's not that many D3D11 tutorials I know about.. but you should definitely keep in mind that many functions can fail, and will fail, especially during development when you're changing things around. It's very easy to get a mistake into a shader, and without proper debug output you have no way of knowing which call failed.

Thank you so much for you help. The problem was the version number, apparently has to be 4 not 5? Thanks for the heads up about safety, will now make sure pointers point to null and I am actually handling error messages :P


Share this post

Link to post
Share on other sites
If it has to be 4, then that probably means you're running at feature level 10.0. What graphics card do you have?

You can check your feature level with pDevice->GetFeatureLevel(). The following values are valid, and depend on your graphics card:

D3D_FEATURE_LEVEL featureLevel = pDevice->GetFeatureLevel();


Shader version 5.0 only works with feature level 11.0.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement