I'm trying to render a square with a texture. Does anyone know why this texture appears to be shifted or misaligned?
Here is how it's supposed to look: http://imgur.com/siCQXXT
Here is how the issue looks: http://imgur.com/rj6tHcX
auto createVSTask = loadVSTask.then([this](const std::vector<byte>& fileData) {
DX::ThrowIfFailed(
m_deviceResources->GetD3DDevice()->CreateVertexShader(
&fileData[0],
fileData.size(),
nullptr,
&m_vertexShader
)
);
static const D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
DX::ThrowIfFailed(
m_deviceResources->GetD3DDevice()->CreateInputLayout(
vertexDesc,
ARRAYSIZE(vertexDesc),
&fileData[0],
fileData.size(),
&m_inputLayout
)
);
});
auto createPSTask = loadPSTask.then([this](const std::vector<byte>& fileData) {
DX::ThrowIfFailed(
m_deviceResources->GetD3DDevice()->CreatePixelShader(
&fileData[0],
fileData.size(),
nullptr,
&m_pixelShader
)
);
CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
DX::ThrowIfFailed(
m_deviceResources->GetD3DDevice()->CreateBuffer(
&constantBufferDesc,
nullptr,
&m_constantBuffer
)
);
});
auto createPrimitiveTask = (createPSTask && createVSTask).then([this]() {
const VertexPositionColor cubeVertices[] =
{
{ DirectX::XMFLOAT3(-1.0f, -1.0f, 0.0f), DirectX::XMFLOAT3(0.0f, 1.0f, 0.0f), DirectX::XMFLOAT2(0.0f, 0.0f) },
{ DirectX::XMFLOAT3(1.0f, -1.0f, 0.0f), DirectX::XMFLOAT3(0.0f, 1.0f, 0.0f), DirectX::XMFLOAT2(1.0f, 0.0f) },
{ DirectX::XMFLOAT3(1.0f, 1.0f, 0.0f), DirectX::XMFLOAT3(0.0f, 1.0f, 0.0f), DirectX::XMFLOAT2(1.0f, 1.0f) },
{ DirectX::XMFLOAT3(-1.0f, 1.0f, 0.0f), DirectX::XMFLOAT3(0.0f, 1.0f, 0.0f), DirectX::XMFLOAT2(0.0f, 1.0f) },
};
static const unsigned short cubeIndices[] =
{
0, 1, 2,
0, 2, 3
};
m_indexCount = ARRAYSIZE(cubeIndices);
D3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };
vertexBufferData.pSysMem = cubeVertices;
vertexBufferData.SysMemPitch = 0;
vertexBufferData.SysMemSlicePitch = 0;
CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(cubeVertices), D3D11_BIND_VERTEX_BUFFER);
DX::ThrowIfFailed(
m_deviceResources->GetD3DDevice()->CreateBuffer(
&vertexBufferDesc,
&vertexBufferData,
&m_vertexBuffer
)
);
D3D11_SUBRESOURCE_DATA indexBufferData = { 0 };
indexBufferData.pSysMem = cubeIndices;
indexBufferData.SysMemPitch = 0;
indexBufferData.SysMemSlicePitch = 0;
CD3D11_BUFFER_DESC indexBufferDesc(sizeof(cubeIndices), D3D11_BIND_INDEX_BUFFER);
DX::ThrowIfFailed(
m_deviceResources->GetD3DDevice()->CreateBuffer(
&indexBufferDesc,
&indexBufferData,
&m_indexBuffer
)
);
});
auto loadTDTask = DX::ReadDataAsync(m_textureFile);
auto createSubresourceTask = loadTDTask.then([=](std::vector<byte>& textureData) {
D3D11_SUBRESOURCE_DATA textureSubresourceData = { 0 };
textureSubresourceData.pSysMem = &textureData[0];
textureSubresourceData.SysMemPitch = 1024;
textureSubresourceData.SysMemSlicePitch = 0;
D3D11_TEXTURE2D_DESC textureDesc = { 0 };
textureDesc.Width = 256;
textureDesc.Height = 256;
textureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.CPUAccessFlags = 0;
textureDesc.ArraySize = 1;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
textureDesc.MipLevels = 0;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
DX::ThrowIfFailed(m_d3dDevice->CreateTexture2D(
&textureDesc,
nullptr,
&m_texture
);
if (m_texture != NULL)
{
D3D11_SHADER_RESOURCE_VIEW_DESC textureViewDesc;
ZeroMemory(&textureViewDesc, sizeof(textureViewDesc));
textureViewDesc.Format = textureDesc.Format;
textureViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
textureViewDesc.Texture2D.MipLevels = -1;
textureViewDesc.Texture2D.MostDetailedMip = 0;
DX::ThrowIfFailed(
m_d3dDevice->CreateShaderResourceView(
m_texture.Get(),
&textureViewDesc,
&m_textureView
)
);
context->UpdateSubresource(m_texture.Get(), 0, nullptr, &textureData[0], textureSubresourceData.SysMemPitch, textureDesc.Width);
context->GenerateMips(m_textureView.Get());
}
}
D3D11_SAMPLER_DESC samplerDesc;
ZeroMemory(&samplerDesc, sizeof(samplerDesc));
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.MaxAnisotropy = 0;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.BorderColor[0] = 0.0f;
samplerDesc.BorderColor[1] = 0.0f;
samplerDesc.BorderColor[2] = 0.0f;
samplerDesc.BorderColor[3] = 0.0f;
DX::ThrowIfFailed(
m_d3dDevice->CreateSamplerState(
&samplerDesc,
&m_sampler
)
);
First, you confirmed that it was no state or geometry problem with the clamp experiment, second, you said you are using a DDS image, and this is the key.
According to your code, the image is 256 width RGBA8, as the stone are 1/8 of that, it means they cover 32*4 = 128 bytes. Close enough, the DDS header is 124 bytes when you do not have the dx10 chunk in it and it explains why the image is offset-ed like that.
All you have to do is skip the header and pass only the image data to UpdateSubResource. I invit you to look at the DDS reference to learn how the file is layout so you can read the sizes, format, properly skip to the beginning of the data, and also take advantage of the DDS to store compressed format, and include the mip maps upfront to not use GenerateMips that is bad practice.
Related
I'm taking my first steps in programming with Direct3D. I have a very basic pipeline setup, and all I want to get from it is an antialiased smooth image. But I get this:
First, I can't get rid of stair effect though I have 4x MSAA enabled already in my pipeline (DXGI_SAMPLE_DESC::Count is 4 and Quality is 0):
And second, I get this noisy texturing though I have mipmaps generated and LINEAR filtering set in the sampler state.
Am I missing something or doing wrong?
Here is my code:
1) Renderer class:
#include "Scene.h" // Custom class that contains vertex and index buffer contents for every rendered mesh.
#include "Camera.h" // Custom class that contains camera position and fov.
#include <wrl/client.h>
using Microsoft::WRL::ComPtr;
#include <DirectXMath.h>
using namespace DirectX;
#include <map>
#include "generated\VertexShader.h"
#include "generated\PixelShader.h"
class Renderer
{
public:
Renderer(HWND hWnd, int wndWidth, int wndHeight, const Scene& scene, const Camera& camera);
void Render();
void SwitchToWireframe();
void SwitchToSolid();
protected:
void CreateDeviceAndSwapChain();
void CreateDepthStencil();
void CreateInputLayout();
void CreateVertexShader();
void CreatePixelShader();
void CreateRasterizerStates();
void CreateBlendState();
void CreateSamplerState();
void CreateBuffer(ID3D11Buffer** buffer,
D3D11_USAGE usage, D3D11_BIND_FLAG bindFlags,
UINT cpuAccessFlags, UINT miscFlags,
UINT sizeOfBuffer, UINT sizeOfBufferElement, const void* initialData);
void CreateTexture2DAndSRV(const Scene::Texture& texture, ID3D11ShaderResourceView** view);
void CreateTexturesAndViews();
void GenerateMips();
protected:
const Scene& m_scene;
const Camera& m_camera;
DWORD m_cameraLastUpdateTickCount;
HWND m_windowHandle;
int m_windowWidth;
int m_windowHeight;
DXGI_SAMPLE_DESC m_sampleDesc;
ComPtr<IDXGISwapChain> m_swapChain;
ComPtr<ID3D11Texture2D> m_swapChainBuffer;
ComPtr<ID3D11RenderTargetView> m_swapChainBufferRTV;
ComPtr<ID3D11Device> m_device;
ComPtr<ID3D11DeviceContext> m_deviceContext;
ComPtr<ID3D11Debug> m_debugger;
ComPtr<ID3D11Texture2D> m_depthStencilTexture;
ComPtr<ID3D11DepthStencilState> m_depthStencilState;
ComPtr<ID3D11DepthStencilView> m_depthStencilView;
ComPtr<ID3D11InputLayout> m_inputLayout;
ComPtr<ID3D11VertexShader> m_vertexShader;
ComPtr<ID3D11PixelShader> m_pixelShader;
ComPtr<ID3D11RasterizerState> m_solidRasterizerState;
ComPtr<ID3D11RasterizerState> m_wireframeRasterizerState;
ComPtr<ID3D11BlendState> m_blendState;
ComPtr<ID3D11SamplerState> m_linearSamplerState;
std::map<std::string, ComPtr<ID3D11ShaderResourceView>> m_diffuseMapViews;
std::map<std::string, ComPtr<ID3D11ShaderResourceView>> m_normalMapViews;
XMMATRIX m_worldViewMatrix;
ID3D11RasterizerState* m_currentRasterizerState;
};
void Renderer::CreateDeviceAndSwapChain()
{
HRESULT hr;
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.BufferDesc.Width = m_windowWidth;
swapChainDesc.BufferDesc.Height = m_windowHeight;
swapChainDesc.BufferDesc.RefreshRate.Numerator = 1;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 60;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED;
swapChainDesc.SampleDesc = m_sampleDesc;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 1;
swapChainDesc.OutputWindow = m_windowHandle;
swapChainDesc.Windowed = TRUE;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
D3D_FEATURE_LEVEL desiredFeatureLevels[] = { D3D_FEATURE_LEVEL_10_1 };
D3D_FEATURE_LEVEL featureLevel;
hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL,
D3D11_CREATE_DEVICE_DEBUG | D3D11_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS,
desiredFeatureLevels, 1, D3D11_SDK_VERSION, &swapChainDesc,
m_swapChain.GetAddressOf(), m_device.GetAddressOf(), &featureLevel,
m_deviceContext.GetAddressOf());
if (FAILED(hr))
{
hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_WARP, NULL,
D3D11_CREATE_DEVICE_DEBUG | D3D11_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS,
desiredFeatureLevels, 1, D3D11_SDK_VERSION, &swapChainDesc,
m_swapChain.GetAddressOf(), m_device.GetAddressOf(), &featureLevel,
m_deviceContext.GetAddressOf());
}
if (FAILED(hr))
throw std::exception("Failed to create device or swap chain");
hr = m_device->QueryInterface(m_debugger.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to get debugger interface");
hr = m_swapChain->GetBuffer(0, __uuidof(m_swapChainBuffer),
(void**)m_swapChainBuffer.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to get swap chain buffer");
hr = m_device->CreateRenderTargetView(m_swapChainBuffer.Get(), NULL,
m_swapChainBufferRTV.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create RTV for swap chain buffer");
}
void Renderer::CreateDepthStencil()
{
HRESULT hr;
D3D11_TEXTURE2D_DESC tdesc;
tdesc.Width = m_windowWidth;
tdesc.Height = m_windowHeight;
tdesc.MipLevels = 1;
tdesc.ArraySize = 1;
tdesc.Format = DXGI_FORMAT_D16_UNORM;
tdesc.SampleDesc = m_sampleDesc;
tdesc.Usage = D3D11_USAGE_DEFAULT;
tdesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
tdesc.CPUAccessFlags = 0;
tdesc.MiscFlags = 0;
hr = m_device->CreateTexture2D(&tdesc, NULL, m_depthStencilTexture.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create depth stencil texture");
D3D11_DEPTH_STENCIL_VIEW_DESC dsvdesc;
dsvdesc.Format = DXGI_FORMAT_D16_UNORM;
dsvdesc.ViewDimension = m_sampleDesc.Count > 1
? D3D11_DSV_DIMENSION_TEXTURE2DMS
: D3D11_DSV_DIMENSION_TEXTURE2D;
dsvdesc.Flags = 0;
dsvdesc.Texture2D.MipSlice = 0;
hr = m_device->CreateDepthStencilView(m_depthStencilTexture.Get(), &dsvdesc,
m_depthStencilView.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create depth stencil view");
D3D11_DEPTH_STENCIL_DESC dsdesc;
dsdesc.DepthEnable = TRUE;
dsdesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsdesc.DepthFunc = D3D11_COMPARISON_LESS;
dsdesc.StencilEnable = FALSE;
dsdesc.StencilReadMask = 0;
dsdesc.StencilWriteMask = 0;
dsdesc.FrontFace = {};
dsdesc.BackFace = {};
hr = m_device->CreateDepthStencilState(&dsdesc, m_depthStencilState.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create depth stencil state");
}
void Renderer::CreateInputLayout()
{
HRESULT hr;
D3D11_INPUT_ELEMENT_DESC iedescs[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
hr = m_device->CreateInputLayout(iedescs, 3,
g_vertexShader, sizeof(g_vertexShader),
m_inputLayout.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create input layout");
}
void Renderer::CreateVertexShader()
{
HRESULT hr;
hr = m_device->CreateVertexShader(g_vertexShader, sizeof(g_vertexShader),
NULL, m_vertexShader.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create vertex shader");
}
void Renderer::CreatePixelShader()
{
HRESULT hr;
hr = m_device->CreatePixelShader(g_pixelShader, sizeof(g_pixelShader),
NULL, m_pixelShader.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create pixel shader");
}
void Renderer::CreateRasterizerStates()
{
HRESULT hr;
D3D11_RASTERIZER_DESC rdesc;
rdesc.FillMode = D3D11_FILL_SOLID;
rdesc.CullMode = D3D11_CULL_FRONT;
rdesc.FrontCounterClockwise = FALSE;
rdesc.DepthBias = 0;
rdesc.DepthBiasClamp = 0.0f;
rdesc.SlopeScaledDepthBias = 0.0f;
rdesc.DepthClipEnable = TRUE;
rdesc.ScissorEnable = FALSE;
rdesc.MultisampleEnable = m_sampleDesc.Count > 1 ? TRUE : FALSE;
rdesc.AntialiasedLineEnable = m_sampleDesc.Count > 1 ? TRUE : FALSE;
hr = m_device->CreateRasterizerState(&rdesc, m_solidRasterizerState.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create rasterizer state");
rdesc.FillMode = D3D11_FILL_WIREFRAME;
hr = m_device->CreateRasterizerState(&rdesc, m_wireframeRasterizerState.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create rasterizer state");
m_currentRasterizerState = m_solidRasterizerState.Get();
}
void Renderer::CreateSamplerState()
{
HRESULT hr;
D3D11_SAMPLER_DESC smdesc;
smdesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
smdesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
smdesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
smdesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
smdesc.MipLODBias = 0.0f;
smdesc.MaxAnisotropy = 0;
smdesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
smdesc.BorderColor[4] = {};
FLOAT MinLOD = 0.0;
FLOAT MaxLOD = 0.0;
hr = m_device->CreateSamplerState(&smdesc, m_linearSamplerState.GetAddressOf());
if (FAILED(hr))
throw new std::exception("Failed to create sampler state");
}
void Renderer::CreateBlendState()
{
HRESULT hr;
D3D11_BLEND_DESC bdesc;
bdesc.AlphaToCoverageEnable = FALSE;
bdesc.IndependentBlendEnable = FALSE;
bdesc.RenderTarget[0].BlendEnable = FALSE;
bdesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
bdesc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO;
bdesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
bdesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
bdesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
bdesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
bdesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
hr = m_device->CreateBlendState(&bdesc, m_blendState.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create blend state");
}
void Renderer::CreateBuffer(ID3D11Buffer** buffer,
D3D11_USAGE usage, D3D11_BIND_FLAG bindFlags,
UINT cpuAccessFlags, UINT miscFlags,
UINT sizeOfBuffer, UINT sizeOfBufferElement, const void* initialData)
{
HRESULT hr;
D3D11_BUFFER_DESC bdesc;
bdesc.ByteWidth = sizeOfBuffer;
bdesc.Usage = usage;
bdesc.BindFlags = bindFlags;
bdesc.CPUAccessFlags = cpuAccessFlags;
bdesc.MiscFlags = miscFlags;
bdesc.StructureByteStride = sizeOfBufferElement;
D3D11_SUBRESOURCE_DATA bdata;
bdata.pSysMem = initialData;
bdata.SysMemPitch = 0;
bdata.SysMemSlicePitch = 0;
hr = m_device->CreateBuffer(&bdesc, &bdata, buffer);
if (FAILED(hr))
throw std::exception("Failed to create buffer");
}
void Renderer::CreateTexture2DAndSRV(const Scene::Texture& sceneTexture, ID3D11ShaderResourceView** view)
{
HRESULT hr;
constexpr DXGI_FORMAT texformat = DXGI_FORMAT_R32G32B32A32_FLOAT;
D3D11_TEXTURE2D_DESC tdesc;
tdesc.Width = sceneTexture.width;
tdesc.Height = sceneTexture.height;
tdesc.MipLevels = 0;
tdesc.ArraySize = 1;
tdesc.Format = texformat;
tdesc.SampleDesc.Count = 1;
tdesc.SampleDesc.Quality = 0;
tdesc.Usage = D3D11_USAGE_DEFAULT;
tdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
tdesc.CPUAccessFlags = 0;
tdesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
ComPtr<ID3D11Texture2D> texture2d;
hr = m_device->CreateTexture2D(&tdesc, NULL, texture2d.GetAddressOf());
if (FAILED(hr))
throw std::exception("Failed to create texture");
D3D11_SUBRESOURCE_DATA srdata;
srdata.pSysMem = sceneTexture.data;
srdata.SysMemPitch = sceneTexture.width * sizeof(float) * 4;
srdata.SysMemSlicePitch = 0;
m_deviceContext->UpdateSubresource(texture2d.Get(), 0, NULL,
srdata.pSysMem, srdata.SysMemPitch, srdata.SysMemSlicePitch);
D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc;
srvdesc.Format = texformat;
srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvdesc.Texture2D.MostDetailedMip = 0;
srvdesc.Texture2D.MipLevels = -1;
ComPtr<ID3D11ShaderResourceView> shaderResourceView;
hr = m_device->CreateShaderResourceView(texture2d.Get(), &srvdesc, view);
if (FAILED(hr))
throw std::exception("Failed to create shader resource view");
}
void Renderer::CreateTexturesAndViews()
{
for (auto it = m_scene.materials.cbegin(); it != m_scene.materials.cend(); it++)
{
//don't know what's the problem but if I don't place initialized ComPtr<...> instance into a map
//then further .GetAddessOf() fails.
m_diffuseMapViews.emplace(it->first, ComPtr<ID3D11ShaderResourceView>());
m_normalMapViews.emplace(it->first, ComPtr<ID3D11ShaderResourceView>());
CreateTexture2DAndSRV(it->second.diffuseMap, m_diffuseMapViews[it->first].GetAddressOf());
CreateTexture2DAndSRV(it->second.normalMap, m_normalMapViews[it->first].GetAddressOf());
}
}
void Renderer::GenerateMips()
{
for (auto it = m_diffuseMapViews.begin(); it != m_diffuseMapViews.end(); it++)
m_deviceContext->GenerateMips(it->second.Get());
for (auto it = m_normalMapViews.begin(); it != m_normalMapViews.end(); it++)
m_deviceContext->GenerateMips(it->second.Get());
}
Renderer::Renderer(HWND hWnd, int windowWidth, int windowHeight,
const Scene& scene, const Camera& camera)
: m_scene(scene)
, m_camera(camera)
, m_cameraLastUpdateTickCount(0)
, m_windowHandle(hWnd)
, m_windowWidth(windowWidth)
, m_windowHeight(windowHeight)
{
m_sampleDesc.Count = 4;
m_sampleDesc.Quality = 0;
CreateDeviceAndSwapChain();
CreateDepthStencil();
CreateInputLayout();
CreateVertexShader();
CreatePixelShader();
CreateRasterizerStates();
CreateBlendState();
CreateSamplerState();
CreateTexturesAndViews();
GenerateMips();
// Setting up IA stage
m_deviceContext->IASetPrimitiveTopology(
D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_deviceContext->IASetInputLayout(m_inputLayout.Get());
// Setting up VS stage
m_deviceContext->VSSetShader(m_vertexShader.Get(), 0, 0);
// Setting up RS stage
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
viewport.Width = static_cast<FLOAT>(m_windowWidth);
viewport.Height = static_cast<FLOAT>(m_windowHeight);
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
m_deviceContext->RSSetViewports(1, &viewport);
// Setting up PS stage
m_deviceContext->PSSetSamplers(0, 1, m_linearSamplerState.GetAddressOf());
m_deviceContext->PSSetShader(m_pixelShader.Get(), 0, 0);
// Setting up OM stage
m_deviceContext->OMSetBlendState(m_blendState.Get(), NULL, 0xffffffff);
m_deviceContext->OMSetDepthStencilState(m_depthStencilState.Get(), 0);
m_deviceContext->OMSetRenderTargets(1, m_swapChainBufferRTV.GetAddressOf(), m_depthStencilView.Get());
}
void Renderer::Render()
{
constexpr float background[4] = { 0.047f, 0.0487f, 0.066f, 1.0f };
// Setting up view matix
if (m_cameraLastUpdateTickCount
!= m_camera.GetLastUpdateTickCount())
{
const Float3& camFrom = m_camera.GetFrom();
const Float3& camAt = m_camera.GetAt();
const Float3& camUp = m_camera.GetUp();
m_cameraLastUpdateTickCount = m_camera.GetLastUpdateTickCount();
FXMVECTOR from = XMVectorSet(camFrom.x, camFrom.y, camFrom.z, 1.0f);
FXMVECTOR at = XMVectorSet(camAt.x, camAt.y, camAt.z, 1.0f);
FXMVECTOR up = XMVectorSet(camUp.x, camUp.y, camUp.z, 0.0f);
FXMVECTOR dir = XMVectorSubtract(at, from);
FXMVECTOR x = XMVector3Cross(dir, up);
FXMVECTOR up2 = XMVector3Cross(x, dir);
XMMATRIX lookTo = XMMatrixLookToRH(from, dir, up2);
float scalef = 1.0f / XMVectorGetByIndex(XMVector3Length(dir), 0);
XMMATRIX scale = XMMatrixScaling(scalef, scalef, scalef);
float aspect = float(m_windowWidth) / m_windowHeight;
float fov = m_camera.GetFov() / 180.0f * 3.14f;
XMMATRIX persp = XMMatrixPerspectiveFovRH(fov, aspect, 0.1f, 1000.0f);
m_worldViewMatrix = XMMatrixMultiply(XMMatrixMultiply(lookTo, scale), persp);
}
else
{
return;
}
m_deviceContext->ClearDepthStencilView(m_depthStencilView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
m_deviceContext->ClearRenderTargetView(m_swapChainBufferRTV.Get(), background);
for (auto imesh = m_scene.meshes.cbegin(); imesh != m_scene.meshes.cend(); imesh++)
{
// Creating vertex buffer
ComPtr<ID3D11Buffer> vertexBuffer;
CreateBuffer(vertexBuffer.GetAddressOf(),
D3D11_USAGE_DEFAULT, D3D11_BIND_VERTEX_BUFFER, 0, 0,
sizeof(Scene::Vertex) * imesh->vertices.size(), sizeof(Scene::Vertex),
imesh->vertices.data());
// Creating index buffer
ComPtr<ID3D11Buffer> indexBuffer;
CreateBuffer(indexBuffer.GetAddressOf(),
D3D11_USAGE_DEFAULT, D3D11_BIND_INDEX_BUFFER, 0, 0,
sizeof(unsigned int) * imesh->indices.size(), sizeof(unsigned int),
imesh->indices.data());
// Creating constant buffer
ComPtr<ID3D11Buffer> constantBuffer;
CreateBuffer(constantBuffer.GetAddressOf(),
D3D11_USAGE_IMMUTABLE, D3D11_BIND_CONSTANT_BUFFER, 0, 0,
sizeof(XMMATRIX), sizeof(XMMATRIX),
&m_worldViewMatrix);
// Setting up IA stage
ID3D11Buffer* vertexBuffers[8] = { vertexBuffer.Get() };
unsigned int vertexBufferStrides[8] = { sizeof(Scene::Vertex) };
unsigned int vertexBufferOffsets[8] = { 0 };
m_deviceContext->IASetVertexBuffers(0, 8,
vertexBuffers, vertexBufferStrides, vertexBufferOffsets);
m_deviceContext->IASetIndexBuffer(indexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
// Setting up VS stage
m_deviceContext->VSSetConstantBuffers(0, 1, constantBuffer.GetAddressOf());
// Setting up RS stage
m_deviceContext->RSSetState(m_currentRasterizerState);
// Setting up PS stage
ID3D11ShaderResourceView* srvs[2] = { };
srvs[0] = m_diffuseMapViews.at(imesh->material).Get();
srvs[1] = m_normalMapViews.at(imesh->material).Get();
m_deviceContext->PSSetShaderResources(0, 2, srvs);
// Drawing
m_deviceContext->DrawIndexed(imesh->indices.size(), 0, 0);
}
m_swapChain->Present(0, 0);
}
void Renderer::SwitchToWireframe()
{
m_currentRasterizerState = m_wireframeRasterizerState.Get();
m_camera.UpdateLastUpdateTickCount();
}
void Renderer::SwitchToSolid()
{
m_currentRasterizerState = m_solidRasterizerState.Get();
m_camera.UpdateLastUpdateTickCount();
}
2) Vertex shader
struct VS_INPUT
{
float3 position : POSITION;
float3 normal : NORMAL;
float2 texcoord : TEXCOORD;
};
struct VS_OUTPUT
{
float4 position : SV_POSITION;
float3 normal : NORMAL;
float2 texcoord : TEXCOORD;
};
cbuffer Matrices
{
matrix worldViewMatrix;
}
VS_OUTPUT main(VS_INPUT input)
{
VS_OUTPUT output;
output.position = mul(worldViewMatrix, float4(input.position.xyz, 1.0));
output.normal = input.normal;
output.texcoord = input.texcoord;
return output;
}
3) Pixel shader
Texture2D DiffuseMap : register(t0);
Texture2D NormalMap: register(t1);
SamplerState LinearSampler : register(s0);
float4 main(VS_OUTPUT input) : SV_TARGET
{
float3 light = normalize(float3(2.87, -0.36, 1.68));
float3 diffuseColor = DiffuseMap.Sample(LinearSampler, input.texcoord);
float3 normalDisplace = float3(0.0, 0.0, 1.0) - NormalMap.Sample(LinearSampler, input.texcoord);
float illumination = clamp(dot(light, input.normal + normalDisplace), 0.2, 1.0);
return float4(mul(diffuseColor, illumination), 1.0);
}
Okay, I've just figured out the reason of this stairs effect:
The reason is that I passed the same width and height values for CreateWindow WinApi function, and for DXGI_SWAP_CHAIN_DESC::BufferDesc. Meanwhile, these should be different because CreateWindow takes outer width and height of a window to create (window rectangle), while BufferDesc should receive inner values (window client area rectangle). Because of that actual area on screen was smaller than swap chain buffer and the result of rendering was presumably resampled to fit the rectangle, which was introducing the aliasing after MSAA was already applied.
Fixing the issue gave a much cleaner result (4x MSAA is applied here):
But the question with texture aliasing is still open:
I'm trying to create a texture manually from my own data and display it. As I could seize in different DirectX docs the main part of code would be written in this manner
// Global variables
HWND g_hWnd = NULL;
D3D10_DRIVER_TYPE g_driverType = D3D10_DRIVER_TYPE_NULL;
ID3D10Device *g_pd3dDevice = NULL;
IDXGISwapChain *g_pSwapChain = NULL;
ID3D10RenderTargetView *g_pRenderTargetView = NULL;
ID3D10ShaderResourceView *g_pShaderResource = NULL;
ID3DX10Sprite *g_pSprite = NULL;
ID3D10Texture2D *g_pTexture = NULL;
// Any additional code for creation the window object
// ............
// Initialize DirectX
HRESULT InitDirectX()
{
HRESULT hr = S_OK;
RECT rc;
GetClientRect(g_hWnd, &rc);
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
D3D10_DRIVER_TYPE driverTypes[] =
{
D3D10_DRIVER_TYPE_HARDWARE,
D3D10_DRIVER_TYPE_REFERENCE
};
UINT numDriverTypes = sizeof(driverTypes)/sizeof(driverTypes[0]);
// Initialization of the Swap Chain and the Device
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = 64;
sd.BufferDesc.Height = 64;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = g_hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
{
g_driverType = driverTypes[driverTypeIndex];
hr = D3D10CreateDeviceAndSwapChain(NULL, g_driverType, NULL, D3D10_CREATE_DEVICE_DEBUG, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice);
if (SUCCEEDED(hr))
break;
}
if (FAILED(hr))
return hr;
ID3D10Texture2D *pBackBuffer;
hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer);
if (FAILED(hr))
return hr;
hr = g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_pRenderTargetView);
pBackBuffer->Release();
if (FAILED(hr))
return hr;
g_pd3dDevice->OMSetRenderTargets(1, &g_pRenderTargetView, NULL);
// Create the Viewport
D3D10_VIEWPORT vp;
vp.Width = 64;
vp.Height = 64;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0.0f;
vp.TopLeftY = 0.0f;
g_pd3dDevice->RSSetViewports(1, &vp);
// Fill the structure of future texture
D3D10_TEXTURE2D_DESC desc;
desc.Width = 64;
desc.Height = 64;
desc.MipLevels = desc.ArraySize = 1;
desc.MiscFlags = 0;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D10_USAGE_DYNAMIC;
desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
hr = g_pd3dDevice->CreateTexture2D( &desc, NULL, &g_pTexture );
// Get the access to the texture data
D3D10_MAPPED_TEXTURE2D mappedTex;
g_pTexture->Map( D3D10CalcSubresource(0, 0, 1), D3D10_MAP_WRITE_DISCARD, 0, &mappedTex );
int cnt = 0;
UCHAR* pTexels = (UCHAR*)mappedTex.pData;
ZeroMemory(pTexels, sizeof(pTexels));
for( UINT row = 0; row < desc.Height; row++ )
{
UINT rowStart = row * mappedTex.RowPitch;
for( UINT col = 0; col < desc.Width; col++ )
{
UINT colStart = col * 4;
if (cnt == 0)
{
pTexels[rowStart + colStart + 0] = 255; // Red
pTexels[rowStart + colStart + 1] = 128; // Green
pTexels[rowStart + colStart + 2] = 64; // Blue
pTexels[rowStart + colStart + 3] = 255; // Alpha
}
else
{
pTexels[rowStart + colStart + 0] = 64;// Red
pTexels[rowStart + colStart + 1] = 128;// Green
pTexels[rowStart + colStart + 2] = 255;// Blue
pTexels[rowStart + colStart + 3] = 255;// Alpha
}
cnt++;
cnt %= 2;
}
}
g_pTexture->Unmap( D3D10CalcSubresource(0, 0, 1));
// Bind shader and texture
D3D10_SHADER_RESOURCE_VIEW_DESC srvDesc;
// Fill the shader attributes
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = desc.MipLevels - 1;
hr = g_pd3dDevice->CreateShaderResourceView(g_pTexture, &srvDesc, &g_pShaderResource);
// Create sprite object
hr = D3DX10CreateSprite(g_pd3dDevice, 1, &g_pSprite);
if (FAILED(hr))
return hr;
return S_OK;
}
// Now render the texture
void RenderScene()
{
float ClearColor[4] = {1.0f, 1.0f, 1.0f, 1.0f};
g_pd3dDevice->ClearRenderTargetView(g_pRenderTargetView, ClearColor);
D3DXMATRIX mWorld;
D3DXMATRIX mView;
D3DXMATRIX mProjection;
// Now render the generated texture thus it will be entirelly displayed in window
D3DXMatrixTranslation(&mWorld, 0.0f, 0.0f, 0.0f);
D3DXMatrixPerspectiveFovLH(&mProjection, 0.3258f, 1.0f, 0.0f, 0.01f);
g_pSprite->SetProjectionTransform(&mProjection);
D3DXVECTOR3 vEyePt(0.0f, 0.0f, -3.0f);
D3DXVECTOR3 vLookAtPt(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 vUpVec(0.0f, 1.0f, 0.0f);
D3DXMatrixLookAtLH(&mView, &vEyePt, &vLookAtPt, &vUpVec);
g_pSprite->SetViewTransform(&mView);
HRESULT hr;
g_pSprite->Begin(D3DX10_SPRITE_SORT_TEXTURE);
// Render sprite based on shader created on the basis of generated texture
D3DX10_SPRITE SpriteToDraw; // Sprite array
SpriteToDraw.matWorld = mWorld;
SpriteToDraw.TexCoord.x = 0.0f;
SpriteToDraw.TexCoord.y = 0.0f;
SpriteToDraw.TexSize.x = 1.0f;
SpriteToDraw.TexSize.y = 1.0f;
SpriteToDraw.ColorModulate = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
SpriteToDraw.pTexture = g_pShaderResource;
SpriteToDraw.TextureIndex = 0;
hr = g_pSprite->DrawSpritesBuffered(&SpriteToDraw, 1);
if (FAILED(hr))
{
MessageBox(NULL, L"Sprite display error", L"Error", 0);
}
g_pSprite->Flush();
g_pSprite->End();
g_pSwapChain->Present(0, 0);
}
Suddenly, the final result represents the image with nonuniform "lightened" stripes.
link to image http://savepic.org/7623429.jpg:
I've tried to change viewpoint parameters, that led to change the number of visible stripes and their shade, but I can't understand the cause of appearance of different blue/orange shades (in code their colors are uniform). Also, if I generate texture that is evenly filled with one color, i.e:
for( UINT row = 0; row < desc.Height; row++ )
{
UINT rowStart = row * mappedTex.RowPitch;
for( UINT col = 0; col < desc.Width; col++ )
{
UINT colStart = col * 4;
pTexels[rowStart + colStart + 0] = xxx; // Exact color has no reason
pTexels[rowStart + colStart + 1] = yyy;
pTexels[rowStart + colStart + 2] = zzz;
pTexels[rowStart + colStart + 3] = ttt;
}
}
there is no effect of nonuniform shade of the final displayed texture.
Using DirectX SDK which was included to Windows8 SDK.
Compile is success, but program stops in one place. Debugging showed error in this function:
//ID3D11DeviceContext* deviceContext
//IDXGISwapChain* swapChain
//const float BackGround[4] = {0.0f, 0.0f, 0.0f, 0.0f};
void DrawScene(){
deviceContext->ClearRenderTargetView(renderTargetView, BackGroung);
deviceContext->Draw(3, 0); //<-this
swapChain->Present(0, 0);
}
While commenting this function everything goes OK. I think that I have some problems in this functions:
bool InitScene(){
hr = D3DCompileFromFile(L"Effects.fx", 0, 0, "VS", "vs_4_0", NULL, NULL, &vsBuffer, NULL);
hr = D3DCompileFromFile(L"Effects.fx", 0, 0, "PS", "ps_4_0", NULL, NULL, &psBuffer, NULL);
hr = device->CreateVertexShader(vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), NULL, &VS);
hr = device->CreatePixelShader(psBuffer->GetBufferPointer(), psBuffer->GetBufferSize(), NULL, &PS);
Vertex v[] = {
Vertex(0.0f, 0.5f, 0.5f),
Vertex(0.5f, -0.5f, 0.5f),
Vertex(-0.5f, -0.5f, 0.5f),
};
D3D11_BUFFER_DESC vertexBufferDesc;
ZeroMemory(&vertexBufferDesc, sizeof(&vertexBufferDesc));
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Vertex) * 3;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA vertexBufferData;
ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
vertexBufferData.pSysMem = v;
hr = device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &triangleVertexBuffer);
UINT stride = sizeof(Vertex);
UINT offset = 0;
deviceContext->IASetVertexBuffers(0, 0, &triangleVertexBuffer, &stride, &offset);
hr = device->CreateInputLayout(layout, numElements, vsBuffer->GetBufferPointer(), vsBuffer->GetBufferSize(), &vertLayout);
deviceContext->IASetInputLayout(vertLayout);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Height = Height;
viewport.Width = Width;
deviceContext->RSSetViewports(1, &viewport);
return true;
}
Or here:
bool Init3D(){
DXGI_MODE_DESC bufferDesc;
ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC));
bufferDesc.Width = Width;
bufferDesc.Height = Height;
bufferDesc.RefreshRate.Numerator = 60;
bufferDesc.RefreshRate.Denominator = 1;
bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
swapChainDesc.BufferDesc = bufferDesc;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 1;
swapChainDesc.OutputWindow = hWnd;
swapChainDesc.Windowed = TRUE;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
hr = D3D11CreateDeviceAndSwapChain(
NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
NULL,
NULL,
NULL,
D3D11_SDK_VERSION,
&swapChainDesc,
&swapChain,
&device,
NULL,
&deviceContext);
ID3D11Texture2D *backBuffer;
hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBuffer);
hr = device->CreateRenderTargetView(backBuffer, NULL, &renderTargetView);
backBuffer->Release();
deviceContext->OMSetRenderTargets(1, &renderTargetView, NULL);
return true;
}
I'm perfect lamer and can't understand what's going wrong. Help me please.
I'm learning DirectX 11 and I'm trying to render a simple cube, unfortunately my code doesn't work, it simply doesn't render nothing... no errors, no warnings... The only thing displayed is the window with the specified clear color. I'm also very sure that the code is executed entirely.
This is the header of my specialized class:
#pragma once
#include "DirectxApp.h"
#include <DirectXMath.h>
#include "DirectxUtils.h"
struct Vertex
{
DirectX::XMFLOAT3 Position;
DirectX::XMFLOAT4 Color;
};
struct TransformationMatrix
{
DirectX::XMMATRIX worldViewProjMatrix;
};
class MyDirectxApp : public DirectxApp
{
private:
ID3D11Buffer* m_vertexBuffer;
ID3D11Buffer* m_indexBuffer;
ID3D11Buffer* m_worldViewProjBuffer;
ID3D11RasterizerState* m_rasterizerState;
ID3D11InputLayout* m_inputLayout;
ID3D11VertexShader* m_vertexShader;
ID3D11PixelShader* m_pixelShader;
DirectX::XMMATRIX m_worldMatrix;
DirectX::XMMATRIX m_viewMatrix;
DirectX::XMMATRIX m_projMatrix;
TransformationMatrix m_transformationMatrix;
float m_theta;
float m_phi;
float m_radius;
public:
MyDirectxApp(HINSTANCE hInstance,
int width,
int height,
LPWSTR windowName = L"",
bool enable4xMsaa = true,
int xCoord = CW_USEDEFAULT,
int yCoord = CW_USEDEFAULT
);
virtual bool Init();
virtual void OnFrame();
virtual ~MyDirectxApp(void);
};
And this is the cpp (the init method of the super class initializes the window and the basic components of DirectX, see later):
#include "MyDirectxApp.h"
using namespace DirectX;
MyDirectxApp::MyDirectxApp(HINSTANCE hInstance,
int width,
int height,
LPWSTR windowName,
bool enable4xMsaa,
int xCoord,
int yCoord
) : DirectxApp(hInstance, width, height, windowName, enable4xMsaa, xCoord, yCoord)
{
m_vertexBuffer = 0;
m_indexBuffer = 0;
m_inputLayout = 0;
m_rasterizerState = 0;
m_vertexShader = 0;
m_pixelShader = 0;
m_worldViewProjBuffer = 0;
XMMATRIX matrixIdentity = XMMatrixIdentity();
m_worldMatrix = matrixIdentity;
m_viewMatrix = matrixIdentity;
m_projMatrix = matrixIdentity;
m_transformationMatrix.worldViewProjMatrix = matrixIdentity;
m_theta = 1.5f * DirectX::XM_PI;
m_phi = 0.25f* DirectX::XM_PI;
m_radius = 5.0f;
}
bool MyDirectxApp::Init()
{
if(!DirectxApp::Init())
{
return false;
}
HRESULT hResult;
//////////////////////////////////////
// CreateVertexBuffer
//////////////////////////////////////
Vertex cubeVertexArray[] = {
// Position Color
{XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)}, //white
{XMFLOAT3(-1.0f, +1.0f, -1.0f), XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f)}, //black
{XMFLOAT3(+1.0f, +1.0f, -1.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)}, //red
{XMFLOAT3(+1.0f, -1.0f, -1.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)}, //green
{XMFLOAT3(-1.0f, -1.0f, +1.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f)}, //blue
{XMFLOAT3(-1.0f, +1.0f, +1.0f), XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f)}, //yellow
{XMFLOAT3(+1.0f, +1.0f, +1.0f), XMFLOAT4(0.0f, 1.0f, 1.0f, 1.0f)}, //cyan
{XMFLOAT3(+1.0f, -1.0f, +1.0f), XMFLOAT4(1.0f, 0.0f, 1.0f, 1.0f)} //magenta
};
hResult = DirectxUtils::CreateVertexBuffer(m_d3dDevice, &cubeVertexArray, sizeof(cubeVertexArray), &m_vertexBuffer);
if (FAILED(hResult))
{
MessageBox(0, L"CreateVertexBuffer FAILED", 0, 0);
return false;
}
//////////////////////////////////////
// CreateIndexBuffer
//////////////////////////////////////
UINT indices[] = {
0, 1, 2, // front face
0, 2, 3,
4, 6, 5, // back face
4, 7, 6,
4, 5, 1, // left face
4, 1, 0,
3, 2, 6, // right face
3, 6, 7,
1, 5, 6, // top face
1, 6, 2,
4, 0, 3, // bottom face
4, 3, 7
};
hResult = DirectxUtils::CreateIndexBuffer(m_d3dDevice, &indices, sizeof(indices), &m_indexBuffer);
if (FAILED(hResult))
{
MessageBox(0, L"CreateIndexBuffer FAILED", 0, 0);
return false;
}
//////////////////////////////////////
// CreateVertexShader
//////////////////////////////////////
D3D11_INPUT_ELEMENT_DESC inputLayoutDesc[] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"COLOR" , 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
};
hResult = DirectxUtils::CreateVertexShader(m_d3dDevice, L"VertexShader.hlsl", "main", inputLayoutDesc, 2, &m_vertexShader, &m_inputLayout);
if (FAILED(hResult))
{
MessageBox(0, L"CreateVertexShader FAILED", 0, 0);
return false;
}
//////////////////////////////////////
// CreatePixelShader
//////////////////////////////////////
hResult = DirectxUtils::CreatePixelShader(m_d3dDevice, L"PixelShader.hlsl", "main", &m_pixelShader);
if (FAILED(hResult))
{
MessageBox(0, L"CreatePixelShader FAILED", 0, 0);
return false;
}
//////////////////////////////////////
// create world\view\proj matrix
//////////////////////////////////////
XMVECTOR cameraPos = XMVectorSet(0.0f, 3.0f, -5.0f, 1.0f);
XMVECTOR cameraTarget = XMVectorZero();
XMVECTOR cameraUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
m_worldMatrix = XMMatrixIdentity();
m_projMatrix = XMMatrixPerspectiveFovLH(XMConvertToRadians(45.0f), AspectRatio(), 0.1f, 100.0f);
m_viewMatrix = XMMatrixLookAtLH(cameraPos, cameraTarget, cameraUp);
hResult = DirectxUtils::CreateConstantBuffer(m_d3dDevice, sizeof(TransformationMatrix), &m_worldViewProjBuffer);
if (FAILED(hResult))
{
MessageBox(0, L"CreateConstantBuffer FAILED", 0, 0);
return false;
}
//////////////////////////////////////
// CreateRasterizerState
//////////////////////////////////////
D3D11_RASTERIZER_DESC rasterizerDesc;
rasterizerDesc.FillMode = D3D11_FILL_SOLID;
rasterizerDesc.CullMode = D3D11_CULL_BACK;
rasterizerDesc.FrontCounterClockwise = false;
rasterizerDesc.DepthClipEnable = true;
hResult = m_d3dDevice->CreateRasterizerState(&rasterizerDesc, &m_rasterizerState);
if (FAILED(hResult))
{
MessageBox(0, L"CreateRasterizerState FAILED", 0, 0);
return false;
}
return true;
}
void MyDirectxApp::OnFrame()
{
///////////////////////////////////
// update worldViewProj matrix
///////////////////////////////////
XMVECTOR cameraPos = XMVectorSet(0.0f, 3.0f, -5.0f, 1.0f);
XMVECTOR cameraTarget = XMVectorZero();
XMVECTOR cameraUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
m_viewMatrix = XMMatrixLookAtLH(cameraPos, cameraTarget, cameraUp);
m_transformationMatrix.worldViewProjMatrix = m_worldMatrix * m_viewMatrix * m_projMatrix;
///////////////////////////////////
// drawing
///////////////////////////////////
static const FLOAT clearColor[4] = {0.0f, 0.0f, 0.0f, 0.0f};
m_d3dDeviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilBufferView);
m_d3dDeviceContext->ClearRenderTargetView(m_renderTargetView, clearColor);
m_d3dDeviceContext->ClearDepthStencilView(m_depthStencilBufferView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
m_d3dDeviceContext->IASetInputLayout(m_inputLayout);
m_d3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
UINT stride = sizeof(Vertex);
UINT offset = 0;
m_d3dDeviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
m_d3dDeviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
m_d3dDeviceContext->VSSetShader(m_vertexShader, nullptr, 0);
m_d3dDeviceContext->PSSetShader(m_pixelShader, nullptr, 0);
m_d3dDeviceContext->RSSetState(m_rasterizerState);
m_d3dDeviceContext->UpdateSubresource(m_worldViewProjBuffer, 0, nullptr, &m_transformationMatrix, 0, 0);
m_d3dDeviceContext->VSSetConstantBuffers(0, 1, &m_worldViewProjBuffer);
m_d3dDeviceContext->DrawIndexed(36, 0, 0);
m_swapChain->Present(0, 0);
}
MyDirectxApp::~MyDirectxApp(void)
{
m_vertexBuffer->Release();
m_indexBuffer->Release();
m_inputLayout->Release();
m_rasterizerState->Release();
m_vertexShader->Release();
m_pixelShader->Release();
m_worldViewProjBuffer->Release();
}
The VertexShader is really simple, it only does the world-view-projection transformation:
cbuffer cbPerObject
{
float4x4 worldViewProjection;
};
//input data structure
struct VertexInput
{
float3 iPosition : POSITION;
float4 iColor : COLOR;
};
//output data
struct VertexOutput
{
float4 oPosition : SV_POSITION; //system-value-position is a special semantic name
float4 oColor : COLOR;
};
VertexOutput main(VertexInput vertexInput)
{
VertexOutput vertexOutput;
//transform world-view-projection
vertexOutput.oPosition = mul(float4(vertexInput.iPosition, 1.0f), worldViewProjection);
vertexOutput.oColor = vertexInput.iColor;
return vertexOutput;
}
The PixelShader is even simpler:
//input data structure
//must match the vertexShader output
struct PixelShaderInput
{
float4 iPosition : SV_POSITION;
float4 iColor : COLOR;
};
float4 main(PixelShaderInput pixelShaderInput) : SV_TARGET //system-value-target means the output must match the renderTarget format
{
return pixelShaderInput.iColor;
}
As mentioned above the basic components of Directx are created by the super class (DirectxApp), here's the code:
bool DirectxApp::InitDirectx()
{
//////////////////////////////////////
// device creation
//////////////////////////////////////
UINT creationDeviceFlags = 0;
#if defined(DEBUG)
creationDeviceFlags = D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL featureLevel;
HRESULT hResult = D3D11CreateDevice(0, //display adapter
D3D_DRIVER_TYPE_HARDWARE, //drier type
0, //software driver
creationDeviceFlags, //device flag
0, //array of feature levels (NULL means choose the greatest)
0, //number of feature levels
D3D11_SDK_VERSION, //sdk version
&m_d3dDevice,
&featureLevel,
&m_d3dDeviceContext);
if (FAILED(hResult))
{
MessageBox(0, L"D3D11CreateDevice FAILED", 0, 0);
return false;
}
if (featureLevel != D3D_FEATURE_LEVEL_11_0)
{
MessageBox(0, L"D3D_FEATURE_LEVEL_11_0 not supported", 0, 0);
return false;
}
//////////////////////////////////////
// check 4xMSAA
//////////////////////////////////////
UINT m4xMsaaQuality;
m_d3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality);
assert(m4xMsaaQuality > 0); //m4xMsaaQuality is always > 0
//////////////////////////////////////
// swap chain creation
//////////////////////////////////////
DXGI_SWAP_CHAIN_DESC swapChainDesc;
swapChainDesc.BufferDesc.Width = m_windowWidth;
swapChainDesc.BufferDesc.Height = m_windowHeight;
swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
if (m_enable4xMsaa)
{
swapChainDesc.SampleDesc.Count = 4;
swapChainDesc.SampleDesc.Quality = m4xMsaaQuality -1;
}
else
{
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
}
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 1; //means double buffering
swapChainDesc.OutputWindow = m_mainWindow;
swapChainDesc.Windowed = true;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = 0;
IDXGIDevice* dxgiDevice = 0;
m_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice));
IDXGIAdapter* dxgiAdapter = 0;
dxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&dxgiAdapter));
IDXGIFactory* dxgiFactory = 0;
dxgiAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory));
HRESULT hResultSwapChain = dxgiFactory->CreateSwapChain(m_d3dDevice, &swapChainDesc, &m_swapChain);
dxgiDevice->Release();
dxgiAdapter->Release();
dxgiFactory->Release();
if (FAILED(hResultSwapChain))
{
MessageBox(0, L"CreateSwapChain FAILED", 0, 0);
return false;
}
//////////////////////////////////////
// render target creation
//////////////////////////////////////
ID3D11Texture2D* backBufferTexture2D = 0;
m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBufferTexture2D));
HRESULT hResultRenderTarget = m_d3dDevice->CreateRenderTargetView(backBufferTexture2D, 0, &m_renderTargetView);
backBufferTexture2D->Release();
if (FAILED(hResultRenderTarget))
{
MessageBox(0, L"CreateRenderTargetView FAILED", 0, 0);
return false;
}
//////////////////////////////////////
// depth-stencil buffer creation
//////////////////////////////////////
D3D11_TEXTURE2D_DESC depthStencilBufferTexture2D;
depthStencilBufferTexture2D.Width = m_windowWidth;
depthStencilBufferTexture2D.Height = m_windowHeight;
depthStencilBufferTexture2D.MipLevels = 1;
depthStencilBufferTexture2D.ArraySize = 1;
depthStencilBufferTexture2D.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
if (m_enable4xMsaa)
{
depthStencilBufferTexture2D.SampleDesc.Count = 4;
depthStencilBufferTexture2D.SampleDesc.Quality = m4xMsaaQuality -1;
}
else
{
depthStencilBufferTexture2D.SampleDesc.Count = 1;
depthStencilBufferTexture2D.SampleDesc.Quality = 0;
}
depthStencilBufferTexture2D.Usage = D3D11_USAGE_DEFAULT;
depthStencilBufferTexture2D.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilBufferTexture2D.CPUAccessFlags = 0;
depthStencilBufferTexture2D.MiscFlags = 0;
HRESULT hResultDepthStencil = m_d3dDevice->CreateTexture2D(&depthStencilBufferTexture2D, 0, &m_depthStencilBufferTexture2D);
if (FAILED(hResultDepthStencil))
{
MessageBox(0, L"CreateTexture2D depthStencil FAILED", 0, 0);
return false;
}
HRESULT hResultDepthStencilView = m_d3dDevice->CreateDepthStencilView(m_depthStencilBufferTexture2D, 0, &m_depthStencilBufferView);
if (FAILED(hResultDepthStencilView))
{
MessageBox(0, L"CreateDepthStencilView FAILED", 0, 0);
return false;
}
//////////////////////////////////////
// viewport creation
//////////////////////////////////////
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = float(m_windowWidth);
viewport.Height = float(m_windowHeight);
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
m_d3dDeviceContext->RSSetViewports(1, &viewport);
return true;
}
I appreciate any hint to solve this problem!
Thanks in advance
EDIT
To the rendering pipeline arrives only one triangle, the VertexShader is executed but not the PixelShader, and then dies...
It may not be the only problem, but you should transpose the matrices before sending them to the shader. You can do that by calling XMMatrixTranspose( matrix ).
(I see now that someone already mentioned it)
I've been playing around with making games for a little while now, using SDL at first and then SFML. It's been nice to have the basics done for me, but now I'd like to take another step and learn how to do the graphics from the ground up. So I'm trying to learn the ropes of Direct3D, and have been reading a couple of tutorials on D3D 11 to get started. I'm just trying to get the absolute basics going by drawing a white triangle on a dark background... but I can't get it to work.
I'm using the Visual Studio 2012 RC and the Windows 8 SDK, so there's some C++11 syntax in here, plus there's no D3DX. I've managed to set up the window and the initialization of Direct3D seems to go just fine. It runs the rendering part of the main loop, as it clears the screen in the color I specify. However, my fancy white triangle just won't show up. I've gone through my code several times, and with my lack of experience I can't tell what is wrong with it. I've cut out the window initialization/d3d shutdown and other irrelevant parts, but I'm afraid to cut off too much in case some of it is relevant to my problem, so... big-wall-of-code-warning.
I think I have all the required steps in place; I create the device, device context, swap chain and render target. Then I create a vertex shader+input layout and a pixel shader. After that I create a vertex buffer, add the vertices for my triangle and set the primitive topology to TRIANGLELIST, and that's it for the initialization. In my main loop, I point D3D to my vertex/pixel shaders, and tell it to draw the 3 vertices i inserted into the buffer. But only the dark blue background from the call to ClearRenderTargetView shows up; no triangle. Have I missed any steps, or done anything wrong on the way?
Here is the code I have (I'll shamefully admit to have slacked a bit with the code conventions on this one, so no p before pointer variables etc.):
Main loop:
while ( msg.message != WM_QUIT )
{
if ( PeekMessage( &msg, 0, 0, 0, PM_REMOVE ))
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
g_d3dContext->ClearRenderTargetView( g_renderTarget, clearColor );
g_d3dContext->VSSetShader( g_vertexShader, nullptr, 0 );
g_d3dContext->PSSetShader( g_pixelShader, nullptr, 0 );
g_d3dContext->Draw( 3, 0 );
g_swapChain->Present( 0, 0 );
}
}
Direct3D init:
HRESULT hr = S_OK;
RECT rc;
GetClientRect( g_hWnd, &rc );
float width = static_cast<float>( rc.right - rc.left );
float height = static_cast<float>( rc.bottom - rc.top );
uint createDeviceFlags = 0;
const uint numDriverTypes = 3;
D3D_DRIVER_TYPE driverTypes[ numDriverTypes ] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE
};
const uint numFeatureLevels = 3;
D3D_FEATURE_LEVEL featureLevels[ numFeatureLevels ] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0
};
DXGI_SWAP_CHAIN_DESC sd = { 0 };
sd.BufferCount = 1;
sd.BufferDesc.Width = static_cast<uint>( width );
sd.BufferDesc.Height = static_cast<uint>( height );
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = g_hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = true;
for( uint driverTypeIndex : driverTypes )
{
g_driverType = driverTypes[ driverTypeIndex ];
hr = D3D11CreateDeviceAndSwapChain( nullptr, g_driverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels,
D3D11_SDK_VERSION, &sd, &g_swapChain, &g_d3d, &g_featureLevel, &g_d3dContext );
if( SUCCEEDED( hr ))
break;
}
if( FAILED( hr ))
return hr;
// Create a render target view
ID3D11Texture2D* backBuffer = nullptr;
hr = g_swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), reinterpret_cast<void**>( &backBuffer ));
if( FAILED( hr ))
return hr;
hr = g_d3d->CreateRenderTargetView( backBuffer, nullptr, &g_renderTarget );
backBuffer->Release();
if( FAILED( hr ))
return hr;
g_d3dContext->OMSetRenderTargets( 1, &g_renderTarget, nullptr );
// Setup the viewport
D3D11_VIEWPORT vp = { 0 };
vp.Width = width;
vp.Height = height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
g_d3dContext->RSSetViewports( 1, &vp );
// Create vertex shader and input layout
ID3DBlob* vsBlob = nullptr;
ID3DBlob* errorBlob = nullptr;
hr = D3DCompileFromFile( L"VertexShader.hlsl", nullptr, nullptr, "main", "vs_4_0", 0, 0, &vsBlob, &errorBlob );
if ( FAILED( hr ))
return hr;
hr = g_d3d->CreateVertexShader( vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), nullptr, &g_vertexShader );
if ( FAILED( hr ))
{
vsBlob->Release();
return hr;
}
D3D11_INPUT_ELEMENT_DESC ied = { 0 };
ied.AlignedByteOffset = 0;
ied.Format = DXGI_FORMAT_R32G32B32_FLOAT;
ied.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
ied.InputSlot = 0;
ied.InstanceDataStepRate = 0;
ied.SemanticIndex = 0;
ied.SemanticName = "POSITION";
hr = g_d3d->CreateInputLayout( &ied, 1, vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), &g_inputLayout );
vsBlob->Release();
if ( FAILED ( hr ))
return hr;
g_d3dContext->IASetInputLayout( g_inputLayout );
// Create pixel shader
ID3DBlob* psBlob = nullptr;
errorBlob = nullptr;
hr = D3DCompileFromFile( L"PixelShader.hlsl", nullptr, nullptr, "main", "ps_4_0", 0, 0, &psBlob, &errorBlob );
if ( FAILED( hr ))
return hr;
hr = g_d3d->CreatePixelShader( psBlob->GetBufferPointer(), psBlob->GetBufferSize(), nullptr, &g_pixelShader );
psBlob->Release();
if ( FAILED( hr ))
return hr;
// Put some vertices up in this bitch
Vector3f vertices[] =
{
Vector3f( 0.5f, -0.5f, 0.5f ),
Vector3f( 0.5f, -0.5f, 0.5f ),
Vector3f( -0.5f, -0.5f, 0.5f )
};
D3D11_BUFFER_DESC bd = { 0 };
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.ByteWidth = sizeof( Vector3f ) * 3;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
bd.StructureByteStride = 0;
bd.Usage = D3D11_USAGE_DEFAULT;
D3D11_SUBRESOURCE_DATA initData = { 0 };
initData.pSysMem = vertices;
initData.SysMemPitch = 0;
initData.SysMemSlicePitch = 0;
hr = g_d3d->CreateBuffer( &bd, &initData, &g_vertexBuffer );
if ( FAILED( hr ))
return hr;
uint stride = sizeof( Vector3f );
uint offset = 0;
g_d3dContext->IASetVertexBuffers( 0, 1, &g_vertexBuffer, &stride, &offset );
g_d3dContext->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
return S_OK;
My vertex type:
struct Vector3f
{
Vector3f( float ix, float iy, float iz )
: x( ix ), y( iy ), z( iz ) {}
float x;
float y;
float z;
};
My vertex shader:
float4 main( float4 pos : POSITION ) : SV_POSITION
{
return pos;
}
My pixel shader:
float4 main() : SV_TARGET
{
return float4( 1.0f, 1.0f, 1.0f, 1.0f );
}
Of course it was an incredibly stupid oversight. I simply entered bad vertex data - all the vertices were in the same Y dimension; the two first were even identical.
Changed to this:
Vector3f( -0.5f, 0.5f, 0.5f ),
Vector3f( 0.5f, 0.5f, 0.5f ),
Vector3f( -0.5f, -0.5f, 0.5f )
And there was much song and dance and happiness.