Sign in to follow this  

DX11 DirectX 11 Pixel Shader Problem

This topic is 2050 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

Hi, I was reading the and tried to put texture on my cube.
The only problem is that the pixel shader always receive (0.0f, 0.0f) as texture coordinates. the vertex shader gets the right one.
I have no idea of what can cause that.

And another problem with my code is that the far-plane is too close, around 1.5f and I can't change it, I tried changing all the values that have something to do with the z buffer or the view matrix but still.

The partial code is here:

Obs: CStaticModel is not the problem, it was working before I start using DirectX 11

#pragma once
#include <Windows.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>
#include "StaticModel.h"
#define DIRECTX_WINDOW_CLASSNAME "Such DirectX class Name"
#define DIRECTX_WINDOW_CAPTION "Such DirectX caption"
struct VERTEX
FLOAT X, Y, Z; // position
D3DXMATRIX finalMatrix;
class CSDirectX
//WIN32 Initialization and management
HWND m_hWnd;
HINSTANCE m_hInstance;
UINT m_screenWidth;
UINT m_screenHeight;
void createWindow(const char* caption, HINSTANCE hInstance);
bool registerClass(const char* className)
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX); = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = staticProc;
wc.hInstance = m_hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = className;
return RegisterClassEx(&wc) != 0;
void showWindow(bool show)
ShowWindow(m_hWnd, SW_SHOW);
ShowWindow(m_hWnd, SW_HIDE);
static LRESULT CALLBACK staticProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
return 0;
} break;
return DefWindowProc (hWnd, message, wParam, lParam);
return 0;
//DirectX initialization and management
ID3D11Device* m_device;
IDXGISwapChain* m_swapChain;
ID3D11DeviceContext* m_deviceContext;
ID3D11RenderTargetView* m_backBuffer;
ID3D11DepthStencilView* m_zBuffer;
D3DXCOLOR m_backgroundColor;
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11Buffer* m_vertexBuffer;
ID3D11InputLayout* m_inputLayout;
ID3D11Buffer* m_constantBuffer;
ID3D11ShaderResourceView* textureTest;
CStaticModel teste;
D3DXMATRIX m_cameraPosition;
D3DXMATRIX m_projectionMatrix;
void init3D();
void clean3D();
void initPipeline();
void initGraphics();
void setCameraPosition(D3DXVECTOR3* position, D3DXVECTOR3* lookAt, D3DXVECTOR3* upDirection = &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
void init(HINSTANCE hInstance)
createWindow(DIRECTX_WINDOW_CAPTION, hInstance);
void setBackgroundColor(D3DXCOLOR color){m_backgroundColor = color;}
void setFullscreen(BOOL fullscreen=true){m_swapChain->SetFullscreenState(fullscreen, NULL);}
void renderLoop()
m_deviceContext->ClearRenderTargetView(m_backBuffer, m_backgroundColor);
m_deviceContext->ClearDepthStencilView(m_zBuffer, D3D11_CLEAR_DEPTH, 1.0f, 0);
D3DXMATRIX rotation;
D3DXMATRIX translation;
static float a = 0.0f;a += 0.0001f;
D3DXMatrixRotationY(&rotation, a);
D3DXMATRIX final = rotation*m_cameraPosition*m_projectionMatrix*translation;
UINT stride = sizeof(VERTEX);
UINT offset = 0;
m_deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
// select which primtive type we are using
// draw the vertex buffer to the back buffer
D3DXMatrixScaling(&translation, 0.5f, 0.5f, 0.5f);
final = rotation*m_cameraPosition*m_projectionMatrix*translation;
m_deviceContext->UpdateSubresource(m_constantBuffer, 0, 0, &final, 0, 0);
m_deviceContext->PSSetShaderResources(0, 1, &textureTest);
m_swapChain->Present(0, 0);
void createVertexBuffer(ID3D11Buffer** pBuffer, size_t size);
void createIndexBuffer(ID3D11Buffer** pBuffer, size_t size);
void createConstantBuffer(ID3D11Buffer** pBuffer, size_t size);
ID3D11DeviceContext* context()
return m_deviceContext;

#include "SDirectX.h"
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dx11.lib")
#pragma comment (lib, "d3dx10.lib")
m_hWnd = 0;
m_hInstance = 0;
m_screenWidth = 800;
m_screenHeight = 600;
m_swapChain = 0;
m_device = 0;
m_deviceContext = 0;
m_backBuffer = 0;
m_vertexShader = 0;
m_pixelShader = 0;
m_constantBuffer = 0;
m_zBuffer = 0;
m_backgroundColor = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f);
void CSDirectX::init3D()
// clear out the struct for use
ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));
// fill the swap chain description struct
scd.BufferCount = 1; // one back buffer
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // use 32-bit color
scd.BufferDesc.Width = m_screenWidth;
scd.BufferDesc.Height = m_screenHeight;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how swap chain is to be used
scd.OutputWindow = m_hWnd; // the window to be used
scd.SampleDesc.Count = 4; // how many multisamples
scd.Windowed = TRUE; // windowed/full-screen mode
// create a device, device context and swap chain using the information in the scd struct
ID3D11Texture2D *pBackBuffer;
m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
// use the back buffer address to create the render target
m_device->CreateRenderTargetView(pBackBuffer, NULL, &m_backBuffer);
ZeroMemory(&texd, sizeof(texd));
texd.Width = m_screenWidth;
texd.Height = m_screenHeight;
texd.ArraySize = 1;
texd.MipLevels = 1;
texd.SampleDesc.Count = 4;
texd.Format = DXGI_FORMAT_D32_FLOAT;
texd.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ID3D11Texture2D* depthBuffer;
m_device->CreateTexture2D(&texd, NULL, &depthBuffer);
ZeroMemory(&dsvd, sizeof(dsvd));
dsvd.Format = DXGI_FORMAT_D32_FLOAT;
dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
m_device->CreateDepthStencilView(depthBuffer, &dsvd, &m_zBuffer);
m_deviceContext->OMSetRenderTargets(1, &m_backBuffer, m_zBuffer);
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = (float)m_screenWidth;
viewport.Height = (float)m_screenHeight;
viewport.MinDepth = 0.0f; // the closest an object can be on the depth buffer is 0.0
viewport.MaxDepth = 1.0f; // the farthest an object can be on the depth buffer is 1.0
m_deviceContext->RSSetViewports(1, &viewport);

teste.generateCube(0.5f, 0);
void CSDirectX::clean3D()
m_swapChain->SetFullscreenState(FALSE, NULL);
m_swapChain = 0;
m_device = 0;
m_deviceContext = 0;
m_backBuffer = 0;
m_zBuffer = 0;
m_vertexShader = 0;
m_pixelShader = 0;
m_constantBuffer = 0;
void CSDirectX::initPipeline()
ID3D10Blob *VS, *PS;
D3DX11CompileFromFile("shaders.hlsl", 0, 0, "VShader", "vs_5_0", 0, 0, 0, &VS, 0, 0);
D3DX11CompileFromFile("shaders.hlsl", 0, 0, "PShader", "ps_5_0", 0, 0, 0, &PS, 0, 0);
m_device->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &m_vertexShader);
m_device->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &m_pixelShader);
m_deviceContext->VSSetShader(m_vertexShader, 0, 0);
m_deviceContext->PSSetShader(m_pixelShader, 0, 0);
createConstantBuffer(&m_constantBuffer, 64);//Multiple of 16
m_deviceContext->VSSetConstantBuffers(0, 1, &m_constantBuffer);
// create the input layout object
m_device->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &m_inputLayout);
void CSDirectX::initGraphics()
createVertexBuffer(&m_vertexBuffer, sizeof(VERTEX)*3);
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)}
m_deviceContext->Map(m_vertexBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); // map the buffer
memcpy(ms.pData, OurVertices, sizeof(OurVertices)); // copy the data
m_deviceContext->Unmap(m_vertexBuffer, NULL);
D3DXToRadian(45), // the horizontal field of view
(FLOAT)m_screenWidth / (FLOAT)m_screenHeight, // aspect ratio
0.1f, // the near view-plane
100.0f); // the far view-plane
setCameraPosition(&D3DXVECTOR3(0.0f, 1.0f, 1.5f), &D3DXVECTOR3(0.0f, 0.0f, 0.0f));
D3DX11CreateShaderResourceViewFromFile(m_device, // the Direct3D device
"Wood1.png", // load Wood.png in the local folder
NULL, // no additional information
NULL, // no multithreading
&textureTest, // address of the shader-resource-view
NULL); // no multithreading
void CSDirectX::createVertexBuffer(ID3D11Buffer** pBuffer, size_t size)
ZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DYNAMIC; // write access access by CPU and GPU
bd.ByteWidth = size; // size is the VERTEX struct * 3
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // use as a vertex buffer
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // allow CPU to write in buffer
m_device->CreateBuffer(&bd, NULL, pBuffer); // create the buffer
void CSDirectX::createIndexBuffer(ID3D11Buffer** pBuffer, size_t size)
ZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = size;
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
m_device->CreateBuffer(&bd, NULL, pBuffer);
void CSDirectX::createConstantBuffer(ID3D11Buffer** pBuffer, size_t size)
ZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = size;
m_device->CreateBuffer(&bd, NULL, pBuffer);
void CSDirectX::setCameraPosition(D3DXVECTOR3* position, D3DXVECTOR3* lookAt, D3DXVECTOR3* upDirection)
void CSDirectX::createWindow(const char* caption, HINSTANCE hInstance)
m_hInstance = hInstance;
m_hWnd = CreateWindow(DIRECTX_WINDOW_CLASSNAME, caption, WS_OVERLAPPEDWINDOW|WS_VISIBLE, 300, 300, m_screenWidth, m_screenHeight, NULL, NULL, hInstance, NULL);

Share this post

Link to post
Share on other sites
If the vertex shader gets the right texture coordinates the problem is either in the vertex or the pixel shader... post them so we can help.

Regarding the far clip plane distance, it should be at 100.0f, are you sure its at 1.5f?

Share this post

Link to post
Share on other sites
About the distance I am not sure, but I created a rotating cube and the most distant vertex was not visible.

here is the shader:
cbuffer ConstantBuffer
float4x4 finalMatrix;
Texture2D Texture;
SamplerState ss;
struct VOut
float4 color : COLOR;
float4 position : SV_POSITION;
float2 texcoord : TEXCOORD;
VOut VShader(float4 position : POSITION, float2 texcoord : TEXCOORD)
VOut output;
output.position = mul(finalMatrix, position);
output.texcoord = texcoord;
output.color = (1.0f, 1.0f, 1.0f, 1.0f);
output.color.xy = texcoord;
return output;

float4 PShader(float4 color : COLOR, float2 texcoord : TEXCOORD) : SV_TARGET
return Texture.Sample(ss, texcoord);

I am not able to test the code right now because I changed my computer with my brother, and in this computer the driver crashes when I compile...great
The driver crashes when the code gets to swapChain->Present()...anyone knows what is going on?

Ok, the program doesn't crash anymore, but I still can't render the texture Edited by Such1

Share this post

Link to post
Share on other sites
Ok, it is drawing the texture now, but the texture quality is really bad, blurred on the sides and other problems, how do I fix that?? Edited by Such1

Share this post

Link to post
Share on other sites
Blurry at boundaries sounds like trilinear filtering when looking from low angles.
Maybe the filter isn’t ideal. What about anisotropic filtering?

[CODE]D3D11_SAMPLER_DESC SamplerStateTexture = {
LodBias, MaxAnisotropy,
0, 0, 0, 0, 0,
pD3D11Device->CreateSamplerState(&SamplerStateTexture, &mSamplerTexture);[/CODE]

You can play with the LodBias and with MaxAnisotropy.
The LodBias moves your sample to more detailed mipmap levels at the risk of aliasing and more texture cache misses.
MaxAnisotropy increases the quality as well. The maximum value is hardware dependent, but probably somewhere between 1 and 16.

Could you show us a picture, such that we can get a better idea of what's wrong with your textures? Thanks!

Best regards

Share this post

Link to post
Share on other sites

This topic is 2050 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.

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  

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By GreenGodDiary
      Having some issues with a geometry shader in a very basic DX app.
      We have an assignment where we are supposed to render a rotating textured quad, and in the geometry shader duplicate this quad and offset it by its normal. Very basic stuff essentially.
      My issue is that the duplicated quad, when rendered in front of the original quad, seems to fail the Z test and thus the original quad is rendered on top of it.
      Whats even weirder is that this only happens for one of the triangles in the duplicated quad, against one of the original quads triangles.

      Here's a video to show you what happens: Video (ignore the stretched textures)

      Here's my GS: (VS is simple passthrough shader and PS is just as basic)
      struct VS_OUT { float4 Pos : SV_POSITION; float2 UV : TEXCOORD; }; struct VS_IN { float4 Pos : POSITION; float2 UV : TEXCOORD; }; cbuffer cbPerObject : register(b0) { float4x4 WVP; }; [maxvertexcount(6)] void main( triangle VS_IN input[3], inout TriangleStream< VS_OUT > output ) { //Calculate normal float4 faceEdgeA = input[1].Pos - input[0].Pos; float4 faceEdgeB = input[2].Pos - input[0].Pos; float3 faceNormal = normalize(cross(,; //Input triangle, transformed for (uint i = 0; i < 3; i++) { VS_OUT element; VS_IN vert = input[i]; element.Pos = mul(vert.Pos, WVP); element.UV = vert.UV; output.Append(element); } output.RestartStrip(); for (uint j = 0; j < 3; j++) { VS_OUT element; VS_IN vert = input[j]; element.Pos = mul(vert.Pos + float4(faceNormal, 0.0f), WVP);; element.UV = vert.UV; output.Append(element); } }  
      I havent used geometry shaders much so im not 100% on what happens behind the scenes.
      Any tips appreciated! 
    • By mister345
      Hi, I'm building a game engine using DirectX11 in c++.
      I need a basic physics engine to handle collisions and motion, and no time to write my own.
      What is the easiest solution for this? Bullet and PhysX both seem too complicated and would still require writing my own wrapper classes, it seems. 
      I found this thing called PAL - physics abstraction layer that can support bullet, physx, etc, but it's so old and no info on how to download or install it.
      The simpler the better. Please let me know, thanks!
    • By Hexaa
      I try to draw lines with different thicknesses using the geometry shader approach from here:
      It seems to work great on my development machine (some Intel HD). However, if I try it on my target (Nvidia NVS 300, yes it's old) I get different results. See the attached images. There
      seem to be gaps in my sine signal that the NVS 300 device creates, the intel does what I want and expect in the other picture.
      It's a shame, because I just can't figure out why. I expect it to be the same. I get no Error in the debug output, with enabled native debugging. I disabled culling with CullMode.None. Could it be some z-fighting? I have little clue about it but I tested to play around with the RasterizerStateDescription and DepthBias properties with no success, no change at all. Maybe I miss something there?
      I develop the application with SharpDX btw.
      Any clues or help is very welcome

    • By Beny Benz
      I'm currently trying to write a shader which shoud compute a fast fourier transform of some data, manipulating the transformed data, do an inverse FFT an then displaying the result as vertex offset and color. I use Unity3d and HLSL as shader language. One of the main problems is that the data should not be passed from CPU to GPU for every frame if possible. My original plan was to use a vertex shader and do the fft there, but I fail to find out how to store changing data betwen shader calls/passes. I found a technique called ping-ponging which seems to be based on writing and exchangeing render targets, but I couldn't find an example for HLSL as a vertex shader yet.
      I found
      which seem to use COLOR0 and COLOR1 as such render targets.
      Is it even possible to do such calculations on the gpu only? (/in this shader stage?, because I need the result of the calculation to modify the vertex offsets there)
      I also saw the use of compute shaders in simmilar projects (ocean wave simulation), do they realy copy data between CPU / GPU for every frame?
      How does this ping-ponging / rendertarget switching technique work in HLSL?
      Have you seen an example of usage?
      Any answer would be helpfull.
      Thank you
    • By ADDMX
      Just a simple question about compute shaders (CS5, DX11).
      Do the atomic operations (InterlockedAdd in my case) should work without any issues on RWByteAddressBuffer and be globaly coherent ?
      I'v come back from CUDA world and commited fairly simple kernel that does some job, the pseudo-code is as follows:
      (both kernels use that same RWByteAddressBuffer)
      first kernel does some job and sets Result[0] = 0;
      (using Result.Store(0, 0))
      I'v checked with debugger, and indeed the value stored at dword 0 is 0
      now my second kernel
      RWByteAddressBuffer Result;  [numthreads(8, 8, 8)] void main() {     for (int i = 0; i < 5; i++)     {         uint4 v0 = DoSomeCalculations1();         uint4 v1 = DoSomeCalculations2();         uint4 v2 = DoSomeCalculations3();                  if (v0.w == 0 && v1.w == 0 && v2.w)             continue;         //    increment counter by 3, and get it previous value         // this should basically allocate space for 3 uint4 values in buffer         uint prev;         Result.InterlockedAdd(0, 3, prev);                  // this fills the buffer with 3 uint4 values (+1 is here as the first 16 bytes is occupied by DrawInstancedIndirect data)         Result.Store4((prev+0+1)*16, v0);         Result.Store4((prev+1+1)*16, v1);         Result.Store4((prev+2+1)*16, v2);     } } Now I invoke it with Dispatch(4,4,4)
      Now I use DrawInstancedIndirect to draw the buffer, but ocassionaly there is missed triangle here and there for a frame, as if the atomic counter does not work as expected
      do I need any additional synchronization there ?
      I'v tried 'AllMemoryBarrierWithGroupSync' at the end of kernel, but without effect.
      If I do not use atomic counter, and istead just output empty vertices (that will transform into degenerated triangles) the all is OK - as if I'm missing some form of synchronization, but I do not see such a thing in DX11.
      I'v tested on both old and new nvidia hardware (680M and 1080, the behaviour is that same).
  • Popular Now