Draw 2 quads with one function DirectX11 - c++

I'm Leanrning DirectX11 and I'm trying to draw 2 Quad with a single function but when i call this function , the function override the previous QUAD.
If you want to see the problem , here is a gif :
<video alt="Video from Gyazo" width="1280" autoplay muted loop playsinline controls><source src="https://i.gyazo.com/b819ffc64975c1531434047b9b4a92f7.mp4" type="video/mp4" /></video>
Here is the code :
(here is where i call the function to draw the QUAD)
void Application::ApplicationRun()
{
//wind.SetEventCallBack(std::bind(&Application::OnEvent, Instance, std::placeholders::_1));
Vertex v[] =
{
Vertex(-0.5f, -0.5f, 0.0f, 1.0f), /// botom Left Point - [0]
Vertex(-0.5f, 0.5f, 0.0f, 0.0f), //top Left Point - [1]
Vertex{ 0.0f, -0.5f, 1.0f, 1.0f}, // -[2]
Vertex(0.0f, 0.5f, 1.0f, 0.0f), //Right Point - [3]
};
Vertex vv[] =
{
Vertex(-0.1f, -0.1f, 0.0f, 0.0f), /// botom Left Point - [0]
Vertex(-0.1f, 0.1f, 0.0f, 0.0f), //top Left Point - [1]
Vertex{ 0.05f, -0.1f, 0.0f, 0.0f}, // -[2]
Vertex(0.05f, 0.1f, 0.0f, 0.0f), //Right Point - [3]
};
DWORD indices[] =
{
0,1,2,
1,2,3,
};
while (wind.PorcessMessage())
{
//
if (Armageddon::Application::GetInstance()->GetWindow()->GetNativeKeyBoard().KeyIsPressed(AG_KEY_A))
{
Log::GetLogger()->trace("A ");
wind.GetWindowGraphics()->DrawTriangle(v, ARRAYSIZE(v));
}
if (Armageddon::Application::GetInstance()->GetWindow()->GetNativeKeyBoard().KeyIsPressed(AG_KEY_B))
{
Log::GetLogger()->trace("B");
wind.GetWindowGraphics()->DrawTriangle(vv, ARRAYSIZE(vv));
}
}
}
(Here is the DrawTriangle Function) :
void Armageddon::D3D_graphics::DrawTriangle(Vertex v[], int Vertexcount)
{
HRESULT hr = vertexBuffer.Initialize(this->device.Get(),this->device_context.Get() , v, Vertexcount);
if (FAILED(hr))
{
Armageddon::Log::GetLogger()->error("FAILED INITIALIZE VERTEX BUFFER ");
}
DWORD indices[] =
{
0,1,2,
1,2,3,
};
hr = this->indicesBuffer.Init(this->device.Get(), indices, ARRAYSIZE(indices));
hr = DirectX::CreateWICTextureFromFile(this->device.Get(), L"..\\TestApplication\\assets\\Textures\\tex.png",nullptr,textures.GetAddressOf());
if (FAILED(hr))
{
Armageddon::Log::GetLogger()->error("FAILED INITIALIZE WIC TEXTURE ");
}
}
(Here is where i initialize the Vertex and the Indice buffer) :
HRESULT Initialize(ID3D11Device* device , ID3D11DeviceContext* device_context, T* data, UINT numElements)
{
this->bufferSize = numElements;
this->stride = sizeof(T);
D3D11_BUFFER_DESC vertex_buffer_desc;
ZeroMemory(&vertex_buffer_desc, sizeof(vertex_buffer_desc));
vertex_buffer_desc.Usage = D3D11_USAGE_DEFAULT;
vertex_buffer_desc.ByteWidth = sizeof(Vertex) * numElements;
vertex_buffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertex_buffer_desc.CPUAccessFlags = 0;
vertex_buffer_desc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA VertexBufferData;
ZeroMemory(&VertexBufferData, sizeof(VertexBufferData));
VertexBufferData.pSysMem = data;
HRESULT hr = device->CreateBuffer(&vertex_buffer_desc, &VertexBufferData, buffer.GetAddressOf());
UINT offset = 0;
device_context->IASetVertexBuffers(0, 1, buffer.GetAddressOf(), &stride, &offset);
return hr;
};```
HRESULT Init(ID3D11Device* device, DWORD* data, UINT n_indices)
{
D3D11_SUBRESOURCE_DATA Indice_buffer_data;
this->buffer_size = n_indices;
D3D11_BUFFER_DESC Indice_buffer_desc;
ZeroMemory(&Indice_buffer_desc, sizeof(Indice_buffer_desc));
Indice_buffer_desc.Usage = D3D11_USAGE_DEFAULT;
Indice_buffer_desc.ByteWidth = sizeof(DWORD) * n_indices;
Indice_buffer_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
Indice_buffer_desc.CPUAccessFlags = 0;
Indice_buffer_desc.MiscFlags = 0;
ZeroMemory(&Indice_buffer_data, sizeof(Indice_buffer_data));
Indice_buffer_data.pSysMem = data;
HRESULT hr = device->CreateBuffer(&Indice_buffer_desc, &Indice_buffer_data, buffer.GetAddressOf());
return hr;
};
And here is where I draw the quads :
void Armageddon::D3D_graphics::RenderFrame()
{
float color[] = { 0.1f,0.1f,0.1f,1.0f };
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
ImGui::Checkbox("Another Window", &show_another_window);
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
// 3. Show another simple window.
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
show_another_window = false;
ImGui::End();
}
ImGui::Render();
this->device_context->OMSetRenderTargets(1, target_view.GetAddressOf(), this->depthStencilView.Get());
this->device_context->ClearRenderTargetView(this->target_view.Get(), color);
this->device_context->ClearDepthStencilView(this->depthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
//ICI QU'ON FAIT TOUT LES RENDU APRES AVOIR CLEAN LE PLAN
this->device_context->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
f += 0.1;
ConstantBuffer.data.mat = DirectX::XMMatrixRotationRollPitchYaw(0.0f,0.0f,f);
ConstantBuffer.data.mat = DirectX::XMMatrixTranspose(ConstantBuffer.data.mat);
ConstantBuffer.data.Yoffset = f;
ConstantBuffer.data.Xoffset = 0;
// Armageddon::Log::GetLogger()->trace(ConstantBuffer.data.Yoffset);
if (!ConstantBuffer.ApplyChanges())
{
Armageddon::Log::GetLogger()->error("ERRO WHEN APPLYING CHANGES");
}
this->device_context->VSSetConstantBuffers(0, 1, ConstantBuffer.GetAdressOf());
/***********SHADER*******************************/
this->device_context->VSSetShader(vertexShader.GetShader(), NULL, 0);
this->device_context->PSSetShader(pixelShader.GetShader(), NULL, 0);
this->device_context->IASetInputLayout(this->vertexShader.GetInputLayout());
/***********Texture Sampler*******************************/
this->device_context->PSSetSamplers(0, 1, this->ColorSampler.GetAddressOf());
/***********DEPHT BUFFER*******************************/
this->device_context->OMSetDepthStencilState(this->depthStencilState.Get(), 0);
/***********RASTERIZER STATE*******************************/
this->device_context->RSSetState(this->rasterizerState.Get());
/***********UPDATE LES CONSTANTS BUFFER*******************************/
UINT stride = sizeof(Vertex);
UINT offset = 0;
this->device_context->IASetIndexBuffer(indicesBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
//this->device_context->IASetVertexBuffers(0, 1, vertexBuffer.GetAddressOf(), &stride, &offset);
this->device_context->PSSetShaderResources(0, 1, this->textures.GetAddressOf());
this->device_context->DrawIndexed(indicesBuffer.GetSize(), 0,0);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
this->swapchain->Present(1,0);
}

Related

Can get the cube to pop up (DirectX 11). Cube is not showing, only screen is being cleared

I am trying to make a simple d3d11 program to rotate a cube.
But ultimately the cube doesnt seem to appear.
Only the screen is being cleared to blue but the cube doesnot show up.
I have been using this as my source: https://learn.microsoft.com/en-us/windows/win32/direct3dgetstarted/getting-started-with-a-directx-game
The structure of my project is a
MainClass.cpp, MainClass.h (Handles window initializtion)
DeviceResources.cpp, DeviceResources.h (The Device Resources include device, context, etc.)
Renderer.cpp, Renderer.h (The renderer loads geometry and shaders. Most probably this is where i am going wrong)
Here is my Renderer.h :
#pragma once
#include <memory>
#include <Windows.h>
#include <DirectXMath.h>
#include "DeviceResources.h"
class Renderer
{
public:
Renderer(std::shared_ptr<DeviceResources> deviceResources);
~Renderer();
void CreateDeviceDependentResources();
void CreateWindowSizeDependentResources();
void Update();
void Render();
private:
HRESULT CreateShaders();
HRESULT CreateCube();
void CreateViewAndPerspective();
bool m_done = false;
std::shared_ptr<DeviceResources> m_deviceResources;
typedef struct _constantBufferStruct {
DirectX::XMFLOAT4X4 world;
DirectX::XMFLOAT4X4 view;
DirectX::XMFLOAT4X4 projection;
} ConstantBufferStruct;
static_assert((sizeof(ConstantBufferStruct) % 16) == 0, "Constant Buffer size must be 16-byte aligned");
typedef struct _vertexPositionColor {
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT3 color;
} VertexPositionColor;
typedef struct _vertexPositionColorTangent {
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT3 color;
DirectX::XMFLOAT3 tangent;
} VertexPositionColorTangent;
ConstantBufferStruct m_constantBufferData;
unsigned int m_indexCount;
unsigned int m_frameCount;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_pVertexBuffer;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_pIndexBuffer;
Microsoft::WRL::ComPtr<ID3D11VertexShader> m_pVertexShader;
Microsoft::WRL::ComPtr<ID3D11PixelShader> m_pPixelShader;
Microsoft::WRL::ComPtr<ID3D11InputLayout> m_pInputLayout;
Microsoft::WRL::ComPtr<ID3D11InputLayout> m_pInputLayoutExtended;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_pConstantBuffer;
};
And here is my Renderer.cpp code :
#include "Renderer.h"
#include <fstream>
#include <ppltasks.h>
#include <stdexcept>
Renderer::Renderer(std::shared_ptr<DeviceResources> deviceResources) :
m_deviceResources(deviceResources),
m_frameCount(0)
{
m_frameCount = 0;
}
Renderer::~Renderer() {}
void Renderer::CreateDeviceDependentResources() {
auto CreateShaderTask = Concurrency::create_task([this]() {CreateShaders();
m_done = true;
});
auto CreateCubeTask = CreateShaderTask.then([this]() {CreateCube(); });
}
void Renderer::CreateWindowSizeDependentResources() {
CreateViewAndPerspective();
}
HRESULT Renderer::CreateShaders() {
HRESULT hr = S_OK;
ID3D11Device* device = m_deviceResources->GetDevice();
FILE* vShader, * pShader;
BYTE* bytes;
size_t destSize = 4096;
size_t bytesRead = 0;
bytes = new BYTE[destSize];
fopen_s(&vShader, "cubeVertexShader.cso", "rb");
bytesRead = fread_s(bytes, destSize, 1, 4096, vShader);
hr = device->CreateVertexShader(
bytes,
bytesRead,
nullptr,
&m_pVertexShader
);
D3D11_INPUT_ELEMENT_DESC iaDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,
0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT,
0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
hr = device->CreateInputLayout(iaDesc,ARRAYSIZE(iaDesc), bytes, bytesRead, &m_pInputLayout);
delete bytes;
bytes = new BYTE[destSize];
bytesRead = 0;
fopen_s(&pShader, "cubePixelShader.cso", "rb");
bytesRead = fread_s(bytes, destSize, 1, 4096, pShader);
hr = device->CreatePixelShader(bytes, bytesRead, nullptr, &m_pPixelShader);
CD3D11_BUFFER_DESC cbDesc(sizeof(ConstantBufferStruct), D3D11_BIND_CONSTANT_BUFFER );
hr = device->CreateBuffer(&cbDesc, nullptr, &m_pConstantBuffer);
if (FAILED(hr))
throw std::exception("Failed to Create Constant Buffer");
fclose(vShader);
fclose(pShader);
return hr;
}
HRESULT Renderer::CreateCube() {
HRESULT hr = S_OK;
ID3D11Device* device = m_deviceResources->GetDevice();
VertexPositionColor CubeVertices[] =
{
{DirectX::XMFLOAT3(-0.5f,-0.5f,-0.5f), DirectX::XMFLOAT3(0, 0, 0),},
{DirectX::XMFLOAT3(-0.5f,-0.5f, 0.5f), DirectX::XMFLOAT3(0, 0, 1),},
{DirectX::XMFLOAT3(-0.5f, 0.5f,-0.5f), DirectX::XMFLOAT3(0, 1, 0),},
{DirectX::XMFLOAT3(-0.5f, 0.5f, 0.5f), DirectX::XMFLOAT3(0, 1, 1),},
{DirectX::XMFLOAT3(0.5f,-0.5f,-0.5f), DirectX::XMFLOAT3(1, 0, 0),},
{DirectX::XMFLOAT3(0.5f,-0.5f, 0.5f), DirectX::XMFLOAT3(1, 0, 1),},
{DirectX::XMFLOAT3(0.5f, 0.5f,-0.5f), DirectX::XMFLOAT3(1, 1, 0),},
{DirectX::XMFLOAT3(0.5f, 0.5f, 0.5f), DirectX::XMFLOAT3(1, 1, 1),},
};
unsigned short CubeIndices[] =
{
0,2,1, // -x
1,2,3,
4,5,6, // +x
5,7,6,
0,1,5, // -y
0,5,4,
2,6,7, // +y
2,7,3,
0,4,6, // -z
0,6,2,
1,3,7, // +z
1,7,5,
};
m_indexCount = ARRAYSIZE(CubeIndices);
CD3D11_BUFFER_DESC vbDesc(sizeof(CubeVertices), D3D11_BIND_VERTEX_BUFFER);
D3D11_SUBRESOURCE_DATA vData;
ZeroMemory(&vData, sizeof(D3D11_SUBRESOURCE_DATA));
vData.pSysMem = CubeVertices;
vData.SysMemPitch = 0;
vData.SysMemSlicePitch = 0;
hr = device->CreateBuffer(&vbDesc, &vData, &m_pVertexBuffer);
CD3D11_BUFFER_DESC ibDesc(sizeof(CubeIndices), D3D11_BIND_INDEX_BUFFER);
D3D11_SUBRESOURCE_DATA iData;
ZeroMemory(&iData, sizeof(D3D11_SUBRESOURCE_DATA));
iData.pSysMem = CubeIndices;
iData.SysMemPitch = 0;
iData.SysMemSlicePitch = 0;
hr = device->CreateBuffer(&ibDesc, &iData, &m_pIndexBuffer);
return hr;
}
void Renderer::CreateViewAndPerspective() {
// Use DirectXMath to create view and perspective matrices.
DirectX::XMVECTOR eye = DirectX::XMVectorSet(0.0f, 0.7f, 1.5f, 0.f);
DirectX::XMVECTOR at = DirectX::XMVectorSet(0.0f, -0.1f, 0.0f, 0.f);
DirectX::XMVECTOR up = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.f);
DirectX::XMStoreFloat4x4(
&m_constantBufferData.view,
DirectX::XMMatrixTranspose(
DirectX::XMMatrixLookAtRH(
eye,
at,
up
)
)
);
float aspectRatio = m_deviceResources->GetAspectRatio();
DirectX::XMStoreFloat4x4(
&m_constantBufferData.projection,
DirectX::XMMatrixTranspose(
DirectX::XMMatrixPerspectiveFovRH(
DirectX::XMConvertToRadians(70),
aspectRatio,
0.01f,
100.0f
)
)
);
}
void Renderer::Update() {
DirectX::XMStoreFloat4x4(
&m_constantBufferData.world,
DirectX::XMMatrixTranspose(
DirectX::XMMatrixRotationY(
DirectX::XMConvertToRadians(
(float)m_frameCount++
)
)
)
);
if (m_frameCount == MAXUINT) m_frameCount = 0;
}
void Renderer::Render() {
while (!m_done) {
}
ID3D11DeviceContext* context = m_deviceResources->GetDeviceContext();
ID3D11RenderTargetView* renderTarget = m_deviceResources->GetRenderTarget();
ID3D11DepthStencilView* depthStencil = m_deviceResources->GetDepthStencil();
context->UpdateSubresource(m_pConstantBuffer.Get(), 0, nullptr, &m_constantBufferData, 0, 0);
const float blue[4] = { 0.2f, 0.3f, 0.8f, 1.0f};
context->ClearRenderTargetView(renderTarget, blue);
context->ClearDepthStencilView(depthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
context->OMSetRenderTargets(1, &renderTarget, depthStencil);
UINT stride = sizeof(VertexPositionColor);
UINT offset = 0;
context->IASetVertexBuffers(
0,
1,
m_pVertexBuffer.GetAddressOf(),
&stride,
&offset
);
context->IASetIndexBuffer(m_pIndexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0);
context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
context->IASetInputLayout(m_pInputLayout.Get());
context->VSSetShader(m_pVertexShader.Get(), nullptr, 0);
context->VSSetConstantBuffers(0, 1, m_pConstantBuffer.GetAddressOf());
context->PSSetShader(m_pPixelShader.Get(), nullptr, 0);
//context->DrawIndexed(m_indexCount, 0, 0);
context->Draw(3, 0);
}
For more reference here are the shaders:-
Vertex Shader
cbuffer ModelViewProjectionBuffer : register(b0)
{
matrix model;
matrix view;
matrix projection;
};
float4 main(float3 Position:POSITION, float3 Color:COLOR) : SV_POSITION// main is the default function name
{
float4 pos = float4(Position, 1.0f);
// Transform the position from object space to homogeneous projection space
pos = mul(pos, model);
pos = mul(pos, view);
pos = mul(pos, projection);
return pos;
}
Pixel Shader:
float4 main(float4 position:SV_POSITION) : SV_TARGET
{
return float4(0.9f, 0.4f, 0.2f, 1.0f);
}
Image of the output
Please help me analyze where i am going wrong.
Moreover, i am using visual studio 2019.
Edit: Some were asking a for a complete reproduction so here is the visual studio solution
https://drive.google.com/file/d/1jt6fQgbRElpc9AYpbhYOyp-HCQL3WmEF/view?usp=sharing
You're doing invalid memory accesses when reading the vertex and pixel buffers.
Also, on my computer, both shaders have a dozen of kbytes whilst the memory buffer you're reading them to has only 4096 bytes.
To fix your problem, increase the size of the memory buffer you're using to read the shader bytecode from disk and don't forget to update the elementcount in fread_s().
e.g.,
Renderer.cpp # 35
size_t destSize = 1024 * 1024; // CHANGE THE SIZE OF YOUR MEMORY BUFFER HERE
size_t bytesRead = 0;
bytes = new BYTE[destSize];
fopen_s(&vShader, "cubeVertexShader.cso", "rb");
bytesRead = fread_s(bytes, destSize * sizeof(BYTE), sizeof(BYTE), destSize, vShader);
hr = device->CreateVertexShader(
bytes,
bytesRead,
nullptr,
&m_pVertexShader
);
Do the same where you're reading the pixel shader.
PRO TIP: Pay attention to the debug output and you'll see important messages from d3d debug layer, like the one telling you that both shaders failed to be created :)

C++ Depth Buffer Oculus Rift DK2 VR HMD

This is a question for anybody experienced with the Oculus Rift C++ SDK.
SDK Version: ovr_sdk_win_1.20.0_public
IDE: VS2013
I am trying to resolve a depth buffer problem in my code for a simplified 3D engine for the Oculus Rift DK2.
The OculusRoomTiny example supplied with the SDK is very complex as it is designed with versatility in mind. So, I've taken the SuperMinimal Sample code and used that as a basis for my engine. The SuperMinimal Sample did did not support multi-colour vertexes or depth buffers. So my code includes both.
I've had no problem creating depth buffers using Microsoft DirectX-11 libraries on PC apps so think it's an Oculus specific challenge. Note: the OculusRoomTiny example depth buffer works fine but is encapsulated in classes too complex for my code.
In my code, the Cube rendered as would be expected but inclusion of the Depth buffer only renders the world background colour.
I ripped the depth buffer code from the OculusRoomTiny_Advanced demo and am sure I have integrated it religiously.
I've posted my code for comment. Please note, it is super minimal and does not clean up the COM objects.
Any advice would be welcome as I've been playing with the code now for 6 weeks!
main.cpp
#include "d3d11.h"
#include "d3dcompiler.h"
#include "OVR_CAPI_D3D.h"
#include "DirectXMath.h"
#include "models.h"
using namespace DirectX;
#pragma comment(lib, "d3dcompiler.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
void CreateSampleModel(ID3D11Device * Device, ID3D11DeviceContext *
Context);
void RenderSampleModel(XMMATRIX * viewProj, ID3D11Device * Device, ID3D11DeviceContext * Context);
ID3D11Buffer * IndexBuffer;
ID3D11RenderTargetView * eyeRenderTexRtv[2][3];
ID3D11DepthStencilView *zbuffer[2]; // containing one for each eye
ovrLayerEyeFov ld = { { ovrLayerType_EyeFov } }; //Only using one layer Update this to an array if using several
ovrSession session;
ID3D11Device * Device;
ID3D11DeviceContext * Context;
void CreateDepthBufferForBothEyes(int eye)
{
// Create the Depth Buffer Texture
D3D11_TEXTURE2D_DESC texd;
ZeroMemory(&texd, sizeof(texd));
texd.Width = ld.Viewport[eye].Size.w;
texd.Height = ld.Viewport[eye].Size.h;
texd.ArraySize = 1;
texd.MipLevels = 1;
texd.SampleDesc.Count = 1; // This matches the RTV
texd.Format = DXGI_FORMAT_D32_FLOAT;
texd.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ID3D11Texture2D *pDepthBuffer;
Device->CreateTexture2D(&texd, NULL, &pDepthBuffer);
// Describe specific properties of the Depth Stencil Buffer
D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
ZeroMemory(&dsvd, sizeof(dsvd));
dsvd.Format = DXGI_FORMAT_D32_FLOAT; // Make the same as the texture format
dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
Device->CreateDepthStencilView(pDepthBuffer, &dsvd, &zbuffer[eye]);
pDepthBuffer->Release();
}
//-------------------------------------------------------------------------------------------------
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR, int)
{
// Init Rift and device
ovr_Initialize(0);
ovrGraphicsLuid luid;
ovr_Create(&session, &luid);
IDXGIFactory * DXGIFactory; CreateDXGIFactory1(__uuidof(IDXGIFactory), (void**)(&DXGIFactory));
IDXGIAdapter * DXGIAdapter; DXGIFactory->EnumAdapters(0, &DXGIAdapter);
D3D11CreateDevice(DXGIAdapter, D3D_DRIVER_TYPE_UNKNOWN, 0, 0, 0, 0, D3D11_SDK_VERSION, &Device, 0, &Context);
// Create eye render buffers
for (int eye = 0; eye < 2; eye++)
{
ld.Fov[eye] = ovr_GetHmdDesc(session).DefaultEyeFov[eye];
ld.Viewport[eye].Size = ovr_GetFovTextureSize(session, (ovrEyeType)eye, ld.Fov[eye], 1.0f);
ovrTextureSwapChainDesc desc = {};
desc.Type = ovrTexture_2D;
desc.ArraySize = 1;
desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
desc.Width = ld.Viewport[eye].Size.w;
desc.Height = ld.Viewport[eye].Size.h;
desc.MipLevels = 1;
desc.SampleCount = 1;
desc.StaticImage = ovrFalse;
desc.MiscFlags = ovrTextureMisc_DX_Typeless;
desc.BindFlags = ovrTextureBind_DX_RenderTarget;
ovr_CreateTextureSwapChainDX(session, Device, &desc, &ld.ColorTexture[eye]);
int textureCount = 0; ovr_GetTextureSwapChainLength(session, ld.ColorTexture[eye], &textureCount);
for (int j = 0; j < textureCount; j++) // Creates 3 backbuffers for each eye
{
ID3D11Texture2D* tex; ovr_GetTextureSwapChainBufferDX(session, ld.ColorTexture[eye], j, IID_PPV_ARGS(&tex));
D3D11_RENDER_TARGET_VIEW_DESC rtvd = { DXGI_FORMAT_R8G8B8A8_UNORM, D3D11_RTV_DIMENSION_TEXTURE2D };
Device->CreateRenderTargetView(tex, &rtvd, &eyeRenderTexRtv[eye][j]);
}
CreateDepthBufferForBothEyes(eye);
}
// Create sample model to be rendered in VR
CreateSampleModel(Device,Context);
// Loop for some frames, then terminate
float camX = 0.0f;
float camY = 0.0f;
float camZ = 0.0f;
for (long long frameIndex = 0; frameIndex < 1000;)
{
if (GetKeyState(VK_LEFT) & 0x8000)
camX -= 0.001f;
if (GetKeyState(VK_RIGHT) & 0x8000)
camX += 0.001f;
if (GetKeyState(VK_UP) & 0x8000)
camY += 0.001f;
if (GetKeyState(VK_DOWN) & 0x8000)
camY -= 0.001f;
if (GetKeyState(VK_NEXT) & 0x8000)
camZ += 0.001f;
if (GetKeyState(VK_PRIOR) & 0x8000)
camZ -= 0.001f;
// Get pose using a default IPD
ovrPosef HmdToEyePose[2] = {{{0,0,0,1}, {-0.032f, 0, 0}},
{{0,0,0,1}, {+0.032f, 0, 0}}};
ovrPosef pose[2]; ovr_GetEyePoses(session, 0, ovrTrue, HmdToEyePose, pose, &ld.SensorSampleTime);
//for (int eye = 0; eye < 2; eye++)
// ld.RenderPose[eye] = pose[eye]; // Update the Layer description with the new head position for each eye
// Render to each eye
for (int eye = 0; eye < 2; eye++)
{
ld.RenderPose[eye] = pose[eye]; // Update the Layer description with the new head position for each eye
// Set and clear current render target, and set viewport
int index = 0; ovr_GetTextureSwapChainCurrentIndex(session, ld.ColorTexture[eye], &index);
Context->OMSetRenderTargets(1, &eyeRenderTexRtv[eye][index], zbuffer[eye]); // zbuffer[eye]
Context->ClearRenderTargetView(eyeRenderTexRtv[eye][index], new float[]{ 0.1f, 0.0f, 0.0f, 0.0f });
Context->ClearDepthStencilView(zbuffer[eye], D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0, 0);
D3D11_VIEWPORT D3Dvp; // = { 0, 0, (float)ld.Viewport[eye].Size.w, (float)ld.Viewport[eye].Size.h };
D3Dvp.TopLeftX = 0.0f;
D3Dvp.TopLeftY = 0.0f;
D3Dvp.Width = (float)ld.Viewport[eye].Size.w;
D3Dvp.Height = (float)ld.Viewport[eye].Size.h;
D3Dvp.MinDepth = 0;
D3Dvp.MaxDepth = 1;
Context->RSSetViewports(1, &D3Dvp);
pose[eye].Position.z = 2.0f + camZ; // Move camera 2m from cube
pose[eye].Position.x = camX;
pose[eye].Position.y = camY;
// Calculate view and projection matrices using pose and SDK
XMVECTOR rot = XMLoadFloat4((XMFLOAT4 *)&pose[eye].Orientation);
XMVECTOR pos = XMLoadFloat3((XMFLOAT3 *)&pose[eye].Position);
XMVECTOR up = XMVector3Rotate(XMVectorSet(0, 1, 0, 0), rot);
XMVECTOR forward = XMVector3Rotate(XMVectorSet(0, 0, 1, 0), rot);
XMMATRIX view = XMMatrixLookAtLH(pos, XMVectorAdd(pos, forward), up);
ovrMatrix4f p = ovrMatrix4f_Projection(ld.Fov[eye], 0, 1, ovrProjection_None);
XMMATRIX proj = XMMatrixTranspose(XMLoadFloat4x4((XMFLOAT4X4 *)&p));
// Render model and commit frame
RenderSampleModel(&XMMatrixMultiply(view, proj), Device, Context);
ovr_CommitTextureSwapChain(session, ld.ColorTexture[eye]);
}
// Send rendered eye buffers to HMD, and increment the frame if we're visible
ovrLayerHeader* layers[1] = { &ld.Header };
if (ovrSuccess == ovr_SubmitFrame(session, 0, nullptr, layers, 1))
frameIndex; // was frameIndex++; but changed to loop forever
}
ovr_Shutdown();
}
//---------------------------------------------------------------------------------------
// THIS CODE IS NOT SPECIFIC TO VR OR THE SDK, JUST USED TO DRAW SOMETHING IN VR
//---------------------------------------------------------------------------------------
void CreateSampleModel(ID3D11Device * Device, ID3D11DeviceContext * Context)
{
// Create Vertex Buffer
//#define V(n) (n&1?+1.0f:-1.0f), (n&2?-1.0f:+1.0f), (n&4?+1.0f:-1.0f)
//float vertices[] = { V(0), V(3), V(2), V(6), V(3), V(7), V(4), V(2), V(6), V(1), V(5), V(3), V(4), V(1), V(0), V(5), V(4), V(7) };
D3D11_BUFFER_DESC vbDesc = { sizeof(VERTEX) * NUM_OF_VERTICES, D3D11_USAGE_DEFAULT, D3D11_BIND_VERTEX_BUFFER };
D3D11_SUBRESOURCE_DATA initData = { tList };
ID3D11Buffer* VertexBuffer;
Device->CreateBuffer(&vbDesc, &initData, &VertexBuffer);
//create the index buffer
D3D11_BUFFER_DESC bd;
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(short) * NUM_OF_INDICES; // 3 per triangle, 12 triangles
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;
Device->CreateBuffer(&bd, NULL, &IndexBuffer);
D3D11_MAPPED_SUBRESOURCE ms;
Context->Map(IndexBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); // map the buffer
memcpy(ms.pData, indexes, NUM_OF_INDICES * sizeof(short)); // copy the data
Context->Unmap(IndexBuffer, NULL);
// Create Vertex Shader
char* vShader = "float4x4 m;"
"struct VOut { "
" float4 position : SV_POSITION;"
" float4 color : COLOR;"
"}; "
"VOut VS(float4 p1 : POSITION, float4 colour: COLOR)"
"{"
" VOut output;"
" output.position = mul(m, p1);"
" output.color = colour;"
" return output;"
"}";
ID3D10Blob * pBlob; D3DCompile(vShader, strlen(vShader), "VS", 0, 0, "VS", "vs_4_0", 0, 0, &pBlob, 0);
ID3D11VertexShader * VertexShader;
Device->CreateVertexShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), 0, &VertexShader);
// Create Input Layout
D3D11_INPUT_ELEMENT_DESC elements[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
ID3D11InputLayout * InputLayout;
Device->CreateInputLayout(elements, 2, pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &InputLayout);
// Create Pixel Shader
char* pShader = "float4 PS(float4 position : POSITION, float4 colour : COLOR) : SV_Target { return colour; }";
D3DCompile(pShader, strlen(pShader), "PS", 0, 0, "PS", "ps_4_0", 0, 0, &pBlob, 0);
ID3D11PixelShader * PixelShader;
Device->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), 0, &PixelShader);
Context->IASetInputLayout(InputLayout);
Context->IASetIndexBuffer(IndexBuffer, DXGI_FORMAT_R16_UINT, 0);
UINT stride = sizeof(float) * 4U; // 7U
UINT offset = 0;
Context->IASetVertexBuffers(0, 1, &VertexBuffer, &stride, &offset);
Context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
Context->VSSetShader(VertexShader, 0, 0);
Context->PSSetShader(PixelShader, 0, 0);
}
//------------------------------------------------------
void RenderSampleModel(XMMATRIX * viewProj, ID3D11Device * Device, ID3D11DeviceContext * Context)
{
D3D11_BUFFER_DESC desc = { sizeof(XMMATRIX), D3D11_USAGE_DYNAMIC, D3D11_BIND_CONSTANT_BUFFER, D3D11_CPU_ACCESS_WRITE };
D3D11_SUBRESOURCE_DATA initData = { viewProj };
ID3D11Buffer * ConstantBuffer; Device->CreateBuffer(&desc, &initData, &ConstantBuffer);
Context->VSSetConstantBuffers(0, 1, &ConstantBuffer);
Context->DrawIndexed(NUM_OF_INDICES, 0, 0);
}
models.h
#ifndef MODELS_H
#define MODELS_H
#include "DirectXMath.h"
using namespace DirectX;
#define NUM_OF_MODELS 1
struct VERTEX{
float x;
float y;
float z;
uint32_t C; // Colour
};
#define NUM_OF_VERTICES 24
#define NUM_OF_INDICES 36
extern VERTEX tList[];
extern short indexes[];
#endif
models.cpp
#include "models.h"
VERTEX tList[] = {
{ -0.1f, 0.1f, 0.2f, 0xFF0000FF }, // Cube Vertex Index 0
{ 0.1f, 0.1f, 0.2f, 0xFF0000FF }, // 1
{ -0.1f, -0.1f, 0.2f, 0xFF0000FF }, // 2
{ 0.1f, -0.1f, 0.2f, 0xFF0000FF }, // 3
{ -0.1f, 0.1f, -0.0f, 0x00FF00FF }, // 4
{ 0.1f, 0.1f, -0.0f, 0x00FF00FF }, // 5
{ -0.1f, -0.1f, -0.0f, 0x00FF00FF }, // 6
{ 0.1f, -0.1f, -0.0f, 0x00FF00FF }, // 7
{ 0.1f, 0.1f, 0.2f, 0x0000FFFF }, // 8
{ 0.1f, 0.1f, -0.0f, 0x0000FFFF }, // 9
{ 0.08f, -0.1f, 0.2f, 0x0000FFFF }, // 10 Distorted in prep to test Depth
{ 0.08f, -0.1f, -0.0f, 0x0000FFFF }, // 11 Distorted in prep to test Depth
{ -0.1f, 0.1f, 0.2f, 0xFF0000FF }, // 12
{ -0.1f, 0.1f, -0.0f, 0xFF0000FF }, // 13
{ -0.1f, -0.1f, 0.2f, 0xFF0000FF }, // 14
{ -0.1f, -0.1f, -0.0f, 0xFF0000FF }, // 15
{ -0.1f, 0.1f, -0.0f, 0x00FF00FF }, // 16
{ 0.1f, 0.1f, -0.0f, 0x00FF00FF }, // 17
{ -0.1f, 0.1f, 0.2f, 0x00FF00FF }, // 18
{ 0.1f, 0.1f, 0.2f, 0x00FF00FF }, // 19
{ -0.1f, -0.1f, -0.0f, 0x00FFFFFF }, // 20
{ 0.1f, -0.1f, -0.0f, 0x00FFFFFF }, // 21
{ -0.1f, -0.1f, 0.2f, 0x00FFFFFF }, // 22
{ 0.1f, -0.1f, 0.2f, 0x00FFFFFF }, // 23
};
short indexes[] = {
0, 1, 2, // FRONT QUAD
2, 1, 3,
5, 4, 6, // BACK QUAD
5, 6, 7,
8, 9, 11, // RIGHT QUAD
8, 11, 10,
13, 12,14, // LEFT QUAD
13, 14, 15,
18,16, 17, // TOP QUAD
18, 17, 19,
22, 23, 21, // BOTTOM QUAD
22, 21, 20
};
After much research I've found my own solution:
The line
ovrMatrix4f p = ovrMatrix4f_Projection(ld.Fov[eye], 0, 1, ovrProjection_None);
Creates the projection Matrix.
A was simply a case of setting the projection depth correctly
float zNear = 0.1f;
float zFar = 1000.0f;
ovrMatrix4f p = ovrMatrix4f_Projection(ld.Fov[eye], zNear, zFar, ovrProjection_None);
Amazing how, now 7 weeks of investigating, revealed the flaw as a simple ommission!

DirectX does not draw anything

Hello I recently tried to learn DirectX 11 but my program does not draw anything.
The only thing I get is the window with the background color i have chosen
I have divided my program into a library(engine) and a regular project.
The library contains a model class, shader class and a Directx init function.
the S3DData is just a struct containing all relevant classes e.g. swap chain etc.
static bool initDX(logfile* errorlog, S3DData *data){
D3D_FEATURE_LEVEL featureLevels[] = {
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0
};
UINT numFeatureLevels = 3;
D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
HRESULT result = ERROR_SUCCESS;
DXGI_MODE_DESC bufferDesc;
ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC));
//swapchain and device
bufferDesc.Height = data->WindowHeight;
bufferDesc.Width = data->WindowWidth;
bufferDesc.RefreshRate.Denominator = 1;
bufferDesc.RefreshRate.Numerator = 60;
bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
swapChainDesc.BufferDesc = bufferDesc;
swapChainDesc.OutputWindow = data->Handle;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.Windowed = data->Windowed;
swapChainDesc.BufferCount = 1;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.SampleDesc.Count = 1;
result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL,
D3D11_SDK_VERSION, &swapChainDesc, &data->SwapChain, &data->Device, NULL, &data->DeviceContext);
if(FAILED(result)){
std::string error;
errorlog->write("failed to create swapchain or device:");
if(result == E_INVALIDARG)
error = "invalid argument";
else if(result == E_OUTOFMEMORY)
error = " no memory";
else if(result == DXGI_ERROR_MORE_DATA)
error = " more data needed for buffer";
else if(result == E_NOTIMPL)
error = " not implemented";
else if(result == DXGI_ERROR_INVALID_CALL)
error = " invalid call";
else
error = std::to_string((unsigned int)result);
errorlog->write(error);
return false;
}
//back buffer and rendertargetview
ID3D11Texture2D *backbuffer;
result = data->SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backbuffer);
if(FAILED(result)){
errorlog->write("failed to get backbuffer");
return false;
}
result = data->Device->CreateRenderTargetView(backbuffer, NULL, &data->RenderTargetView);
if(FAILED(result)){
errorlog->write("failed to create render target view");
return false;
}
data->DeviceContext->OMSetRenderTargets(1, &data->RenderTargetView, nullptr);
backbuffer->Release();
ZeroMemory(&data->viewport, sizeof(D3D11_VIEWPORT));
data->viewport.Height = data->WindowHeight;
data->viewport.Width = data->WindowWidth;
data->viewport.TopLeftX = 0;
data->viewport.TopLeftY = 0;
data->DeviceContext->RSSetViewports(1, &data->viewport);
errorlog->write("directx success");
return true;
the function basically creates: the device, swapchain and devicecontext.
and sets: the render target and the viewport
the second funtion is the shader init function:
bool shader::init(std::string vsFile, std::string psFile, S3DData * data){
std::ofstream output;
output.open("shaderErrorLog.txt", std::ios::binary);
_S3DData = data;
_pixelShader = nullptr;
_vertexShader = nullptr;
_layout = nullptr;
HRESULT result;
ID3D10Blob *errorMsg, *pixelShader, *vertexShader;;
unsigned int numElements;
errorMsg = 0;
pixelShader = 0;
vertexShader = 0;
result = D3DX11CompileFromFile(vsFile.c_str(), 0, 0, "VS", "vs_5_0", 0, 0, 0, &vertexShader, &errorMsg, 0);
if(FAILED(result)){
if(errorMsg != nullptr){
char *compilerErrors = (char*)errorMsg->GetBufferPointer();
unsigned int size = errorMsg->GetBufferSize();
output.write(compilerErrors, size);
}
else
{
std::string error ="failed to find file";
output.write(error.c_str(), error.size());
}
return false;
}
result = D3DX11CompileFromFile(psFile.c_str(), 0, 0, "PS", "ps_5_0", 0, 0, 0, &pixelShader, &errorMsg, 0);
if(FAILED(result)){
if(errorMsg){
char *compilerErrors = (char*)errorMsg->GetBufferPointer();
unsigned int size = errorMsg->GetBufferSize();
output.write(compilerErrors, size);
}
else
{
std::string noFileMsg = "file " +psFile +"not found";
output.write(noFileMsg.c_str(), noFileMsg.size());
}
return false;
}
result = _S3DData->Device->CreateVertexShader(vertexShader->GetBufferPointer(), vertexShader->GetBufferSize(), nullptr, &_vertexShader);
if(FAILED(result)){
return false;
}
result = _S3DData->Device->CreatePixelShader(pixelShader->GetBufferPointer(), pixelShader->GetBufferSize(), nullptr, &_pixelShader);
if(FAILED(result)){
return false;
}
//layout of vertex
//in case of color.fx position and color
D3D11_INPUT_ELEMENT_DESC layout[] ={
{"POSITION",0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}
};
//get num of elements
numElements = 2;
result = _S3DData->Device->CreateInputLayout(layout, numElements, vertexShader->GetBufferPointer(), vertexShader->GetBufferSize(), &_layout);
if(FAILED(result))
return false;
vertexShader->Release();
vertexShader = 0;
pixelShader->Release();
pixelShader = 0;
std::string success = "shader init : success";
output.write(success.c_str() , success.size());
_S3DData->DeviceContext->IASetInputLayout(_layout);
_S3DData->DeviceContext->VSSetShader(_vertexShader, 0, 0);
_S3DData->DeviceContext->PSSetShader(_pixelShader, 0, 0);
return true;
and these are the members of the shader class:
ID3D11VertexShader *_vertexShader;
ID3D11PixelShader *_pixelShader;
ID3D11InputLayout *_layout;
S3DData *_S3DData;
this function creates the shaders and since i only have 1 shader for now,
it sets the shaders and the input layout.
the last function is the model init function:
bool model::init(S3DData *data){
_S3DData = data;
HRESULT result;
vertex *vertexBuffer;
unsigned long* indexBuffer;
D3D11_BUFFER_DESC indexDesc, vertexDesc;
D3D11_SUBRESOURCE_DATA indexData, vertexData;
//create buffers
_vertexCount = 3;
_indexCount = 3;
vertexBuffer = new vertex[_vertexCount];
if(!vertexBuffer)return false;
indexBuffer = new unsigned long[_indexCount];
if(!indexBuffer)return false;
//fill buffers
vertexBuffer[0] = vertex( 0.0f, 1.0f, 1.0f);
vertexBuffer[0] = vertex( 1.0f, -1.0f, 1.0f);
vertexBuffer[0] = vertex( -1.0f, -1.0f, 1.0f);
indexBuffer[0] = 0;
indexBuffer[1] = 1;
indexBuffer[2] = 2;
//bufferDesc
vertexDesc.Usage = D3D11_USAGE_DEFAULT;
vertexDesc.ByteWidth = sizeof(vertex) * _vertexCount;
vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexDesc.CPUAccessFlags = 0;
vertexDesc.MiscFlags = 0;
vertexDesc.StructureByteStride = 0;
//set subressource data
vertexData.pSysMem = vertexBuffer;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
result = _S3DData->Device->CreateBuffer(&vertexDesc, &vertexData, &_vertex);
if(FAILED(result))return false;
indexDesc.ByteWidth = sizeof(unsigned long) * _indexCount;
indexDesc.Usage = D3D11_USAGE_DEFAULT;
indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexDesc.MiscFlags = 0;
indexDesc.CPUAccessFlags = 0;
indexDesc.StructureByteStride = 0;
//set subressource
indexData.pSysMem = indexBuffer;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
result = _S3DData->Device->CreateBuffer(&indexDesc, &indexData, &_index);
if(FAILED(result))return false;
delete []indexBuffer;
indexBuffer = nullptr;
delete []vertexBuffer;
vertexBuffer = nullptr;
the vertex struct:
struct vertex{
XMFLOAT3 pos;
vertex(){}
vertex(float x, float y, float z):pos(x, y, z){
}
so this function only creates the buffers
in the render function the remaining variable are set:
void model::render(shader *Shader){
unsigned int stride = sizeof(vertex);
unsigned int offset = 0;
_S3DData->DeviceContext->IASetVertexBuffers(0, 1, &_vertex, &stride, &offset);
_S3DData->DeviceContext->IASetIndexBuffer(_index, DXGI_FORMAT_R32_UINT, 0);
//set form of vertex: triangles
_S3DData->DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_S3DData->DeviceContext->DrawIndexed(_indexCount, 0, 0);
}
EDIT:
these are the shader codes you requested
Vertex Shader:
struct VSout{
float4 position :SV_POSITION;
};
VSout VS(float4 position:POSITION){
VSout output;
output.position = position;
return output;
}
Pixel Shader:
float4 PS() :SV_TARGET{
float4 newColor = float4(1.0f, 1.0f, 0.0f, 1.0f);
return newColor;
}
this here is a screenshot of the debuger left you have all the draw calls etc. And in the middle you can see the vertex buffer
debuger
thanks for your help in advance.
Looking at the debugger image you posted, the 2nd and 3rd vertices are all 0. This means you didn't fill your vertex buffer properly.
Looking at your code, when you fill your vertex buffer, you're only setting it in the 0 index. So you code looks like this:
vertexBuffer[0] = vertex( 0.0f, 1.0f, 1.0f);
vertexBuffer[0] = vertex( 1.0f, -1.0f, 1.0f);
vertexBuffer[0] = vertex( -1.0f, -1.0f, 1.0f);
And it should look like this:
vertexBuffer[0] = vertex( 0.0f, 1.0f, 1.0f);
vertexBuffer[1] = vertex( 1.0f, -1.0f, 1.0f);
vertexBuffer[2] = vertex( -1.0f, -1.0f, 1.0f);

Directx 9 Basic Terrain Creation w/Vertices

I'm trying to create terrain using indexed primitives...I've written a class to handle the graphics, however, I can't get the textured terrain to appear on the screen...The following are the source and header files associated with this process...please ignore skybox functions...
graphics.h:
#pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include <d3dx9tex.h>
#include <string>
#include "Camera.h"
class CGraphics
{
public:
CGraphics(IDirect3DDevice9 *device);
~CGraphics(void);
IDirect3DDevice9 *m_d3ddev;
LPDIRECT3DVERTEXBUFFER9 m_vertexBuffer;
LPDIRECT3DVERTEXBUFFER9 m_terrainVertexBuffer;
LPDIRECT3DINDEXBUFFER9 m_terrainIndexBuffer;
LPDIRECT3DTEXTURE9 m_textures[6];
LPDIRECT3DTEXTURE9 m_terrainTexture;
int m_numVertices;
int m_numFaces;
bool SkyBox(void);
void UpdateSkyBox(void);
bool Terrain(D3DXVECTOR3 minB, D3DXVECTOR3 maxB, int numCellsW, int numCellsL);
void RenderTerrain(void);
private:
void RenderSkyBox(void);
};
graphics.cpp:
#include "Graphics.h"
#include "3D Shapes.h"
#include "assert.h"
CGraphics::CGraphics(IDirect3DDevice9 *device) : m_d3ddev(device), m_vertexBuffer(0)
{
for(unsigned int i = 0; i < sizeof(LPDIRECT3DTEXTURE9)/sizeof(m_textures); i++)
{
m_textures[i] = 0;
m_terrainVertexBuffer = NULL;
m_terrainIndexBuffer = NULL;
}
}
CGraphics::~CGraphics(void)
{
if(m_vertexBuffer)
{
delete m_vertexBuffer;
m_vertexBuffer=0;
}
if(m_d3ddev)
{
m_d3ddev->Release();
m_d3ddev=0;
}
if(m_terrainVertexBuffer){
m_terrainVertexBuffer->Release();
m_terrainVertexBuffer=0;
}
if(m_terrainIndexBuffer){
m_terrainIndexBuffer->Release();
m_terrainIndexBuffer=0;
}
}
bool CGraphics::SkyBox(void)
{
HRESULT hr;
hr = m_d3ddev->CreateVertexBuffer(sizeof(TEXTUREVERTEX) * 24, 0, CUSTOMFVF, D3DPOOL_MANAGED,
&m_vertexBuffer, NULL);
if(FAILED(hr))
{
MessageBox(NULL, L"Failed to 'Create Vertex Buffer for SkyBox'", L"ERROR", MB_OK);
return false;
}
void* pVertices = NULL;
m_vertexBuffer->Lock(0, sizeof(TEXTUREVERTEX)*24, (void**)&pVertices, 0);
memcpy(pVertices, skyBox, sizeof(TEXTUREVERTEX)*24);
m_vertexBuffer->Unlock();
hr = D3DXCreateTextureFromFileA(m_d3ddev, fileF.c_str(), &m_textures[0]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileB.c_str(), &m_textures[1]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileL.c_str(), &m_textures[2]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileR.c_str(), &m_textures[3]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileTop.c_str(), &m_textures[4]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileBottom.c_str(), &m_textures[5]);
if ( FAILED(hr) )
{
MessageBox(NULL, L"Failed to open 1 or more images files!", L"Error Opening Texture Files", MB_OK);
return false;
}
return true;
}
void CGraphics::UpdateSkyBox(void)
{
D3DXMATRIX matView, matSave, matWorld;
m_d3ddev->GetTransform(D3DTS_VIEW, &matSave);
matView = matSave;
matView._41 = 0.0f; matView._42 = -0.4f; matView._43 = 0.0f;
m_d3ddev->SetTransform(D3DTS_VIEW, &matView);
D3DXMatrixIdentity(&matWorld);
m_d3ddev->SetTransform(D3DTS_WORLD, &matWorld);
RenderSkyBox();
m_d3ddev->SetTransform(D3DTS_VIEW, &matSave);
}
void CGraphics::RenderSkyBox(void)
{
m_d3ddev->SetRenderState(D3DRS_ZENABLE, false);
m_d3ddev->SetRenderState(D3DRS_ZWRITEENABLE, false);
m_d3ddev->SetRenderState(D3DRS_LIGHTING, false);
m_d3ddev->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP );
m_d3ddev->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP );
m_d3ddev->SetFVF(CUSTOMFVF);
m_d3ddev->SetStreamSource(0, m_vertexBuffer, 0, sizeof(TEXTUREVERTEX));
for(unsigned int i = 0; i < 6; i ++)
{
m_d3ddev->SetTexture(0, m_textures[i]);
m_d3ddev->DrawPrimitive(D3DPT_TRIANGLESTRIP, i*4, 2);
}
m_d3ddev->SetRenderState(D3DRS_ZENABLE, true);
m_d3ddev->SetRenderState(D3DRS_ZWRITEENABLE, true);
m_d3ddev->SetRenderState(D3DRS_LIGHTING, true);
}
bool CGraphics::Terrain(D3DXVECTOR3 minB, D3DXVECTOR3 maxB, int numCellsW, int numCellsL)
{
HRESULT hr = D3DXCreateTextureFromFileA(m_d3ddev, (LPCSTR)texFileTerrain.c_str(), &m_terrainTexture);
if(FAILED(hr))
{
MessageBox(NULL, L"Could not 'Load Texture(Terrain)'", L"ERROR", MB_OK);
return false;
}
TERRAIN terra = {minB,maxB,numCellsW,numCellsL,numCellsW+1,numCellsL+1,(maxB.x - minB.x)/numCellsW,
(maxB.z - minB.z)/numCellsL,
terra.vertices = new VERTEXARRAY[terra.numVertsX*terra.numVertsZ],
};
m_numVertices = terra.numVertsX*terra.numVertsZ;
m_numFaces = terra.numCellsX*terra.numCellsZ*2;
DWORD *indices = new DWORD[terra.numCellsX*terra.numCellsZ*6];
for(int i = 0; i < sizeof(indices); i++)
{
indices[i] = 0;
}
D3DXVECTOR3 pos(minB.x, 0, minB.z);
int vIter = 0;
for(int z = 0; z < terra.numVertsZ; z++)
{
for(int x = 0; x < terra.numVertsX; x++)
{
terra.vertices[vIter].x = 0;
terra.vertices[vIter].y = 0;
terra.vertices[vIter].z = 0;
terra.vertices[vIter].tu = 0;
terra.vertices[vIter].tv = 0;
vIter++;
}
}
double curTexPosZ = 1.0;
vIter=0;
for(double z = 0; z < (double)terra.numVertsZ; z++)
{
pos.x = minB.x;
curTexPosZ = (double)((double)terra.numCellsZ - z) / (double)(terra.numCellsZ);
for(double x = 0; x < terra.numVertsX; x++)
{
terra.vertices[vIter].x = pos.x;
terra.vertices[vIter].y = pos.y;
terra.vertices[vIter].z = pos.z;
//terra.vertices[vIter].color = D3DCOLOR_ARGB(0,255,255,255);
terra.vertices[vIter].tu = (float)(x / (double)terra.numCellsX);
terra.vertices[vIter].tv = (float)curTexPosZ;
pos.x += terra.stepX;
vIter++;
}
pos.z += terra.stepZ;
}
assert(vIter <= terra.numVertsX*terra.numVertsZ);
vIter = 0;
int iPos =0;
for(int z =0; z< terra.numCellsZ; z++)
{
for(int x = 0; x< terra.numCellsX; x++)
{
indices[iPos] = vIter; iPos++;
indices[iPos] = vIter+terra.numVertsX; iPos++;
indices[iPos] = vIter+terra.numVertsX+1; iPos++;
indices[iPos] = vIter; iPos++;
indices[iPos] = vIter+terra.numVertsX+1; iPos++;
indices[iPos] = vIter+1; iPos++;
vIter++;
}
vIter++;
}
assert(vIter <= terra.numCellsX*terra.numCellsZ*6);
void* pVoid;
hr = m_d3ddev->CreateVertexBuffer(sizeof(VERTEXARRAY)*terra.numVertsX*terra.numVertsZ,0,
CUSTOMFVF,D3DPOOL_MANAGED,&m_terrainVertexBuffer,NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
hr = m_terrainVertexBuffer->Lock(0, 0, (void**)&pVoid, NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Lock Vertex Buffer", L"ERROR", MB_OK);
return false;
}
memcpy(pVoid, terra.vertices, sizeof(terra.vertices));
m_terrainVertexBuffer->Unlock();
hr = m_d3ddev->CreateIndexBuffer(sizeof(DWORD)*sizeof(indices),0,
D3DFMT_INDEX16, D3DPOOL_MANAGED, &m_terrainIndexBuffer, NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Index Buffer", L"ERROR", MB_OK);
return false;
}
hr = m_terrainIndexBuffer->Lock(0, 0, (void**)&pVoid, 0);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
memcpy(pVoid, indices, sizeof(indices));
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
m_terrainIndexBuffer->Unlock();
return true;
}
void CGraphics::RenderTerrain(void)
{
m_d3ddev->SetFVF(CUSTOMFVF);
m_d3ddev->SetTexture(0, m_terrainTexture);
m_d3ddev->SetStreamSource(0, m_terrainVertexBuffer, 0, sizeof(VERTEXARRAY));
m_d3ddev->SetIndices(m_terrainIndexBuffer);
m_d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP, 0, 0, m_numVertices, 0, m_numFaces);
}
3D Shapes:
#pragma once
#define CUSTOMFVF (D3DFVF_XYZ | D3DFVF_TEX1)
struct TEXTUREVERTEX {
float x, y, z, tu, tv;
};
TEXTUREVERTEX skyBox[] = {
// Front quad, NOTE: All quads face inward
{-10.0f, -10.0f, 10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, 10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, 10.0f, 1.0f, 0.0f },
// Back quad
{ 10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, {-10.0f, -10.0f, -10.0f, 1.0f, 1.0f },{-10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Left quad
{-10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, {-10.0f, -10.0f, 10.0f, 1.0f, 1.0f }, {-10.0f, 10.0f, 10.0f, 1.0f, 0.0f },
// Right quad
{ 10.0f, -10.0f, 10.0f, 0.0f, 1.0f }, { 10.0f, 10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, -10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Top quad
{-10.0f, 10.0f, 10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, { 10.0f, 10.0f, 10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Bottom quad
{-10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, {-10.0f, -10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, -10.0f, 1.0f, 1.0f },{ 10.0f, -10.0f, 10.0f, 1.0f, 0.0f }
};
std::string fileF("skybox_front.jpg");
std::string fileB("skybox_back.jpg");
std::string fileL("skybox_left.jpg");
std::string fileR("skybox_right.jpg");
std::string fileTop("skybox_top.jpg");
std::string fileBottom("skybox_bottom.jpg");
struct VERTEXARRAY {
float x, y, z, tu, tv;
};
struct TERRAIN {
D3DXVECTOR3 minBounds; // minimum bounds (x, y, z)
D3DXVECTOR3 maxBounds; // maximum bounds (x, y, z)
int numCellsX; // # of cells in the x direction
int numCellsZ; // # of cells in the z direction
int numVertsX; // # of vertices in the x direction
int numVertsZ; // # of vertices in the z direction
float stepX; // space between vertices in the x direction
float stepZ; // space between vertices in the z direction
VERTEXARRAY *vertices; // vertex array pointer (stores the position for each vertex
};
std::string texFileTerrain("sunset.jpg");
I've looked through countless tutorials and samples online and found no solution. I imagine the problem I'm having is related to the settings, I must be overlooking something...any ideas would be appreciated...thanks in advance!

DirectX9 Lighting C++ Lighting not working

This is a simple program that draws a 3d cube with a texture. The problem is I can not see the texture because the lights are not working.I have turned off the lights just to make sure the texture is there and it is.So if any one can help me figure out why the lights are not working I would greatly appreciate it.
#include "DirectXGame.h"
DirectXGame::DirectXGame(void)
{
//init to zero good pratice
m_pD3DObject=0;
m_pD3DDevice=0;
m_currTime=0;
m_prevTime=0;
ZeroMemory(&m_D3Dpp,sizeof(m_D3Dpp));
FOV=D3DXToRadian(65.0f);
aspectRatio=800/600;
nearPlane=1.0f;
farPlane=1000.0f;
}
DirectXGame::~DirectXGame(void)
{
}
//create class for input
DirectXInput DXClass;
void DirectXGame::Initialize(HWND hWnd ,HINSTANCE hInst,bool bWindowed) // create the material struct)//
{
// grab the window width and height fronm the HWND
RECT r;
GetWindowRect(hWnd, &r);
m_nWidth = r.right - r.left;
m_nHeight = r.bottom - r.top;
m_bVSync = false;
// Create the D3D Object
m_pD3DObject = Direct3DCreate9(D3D_SDK_VERSION);
// Create our presentation parameters for our D3D Device
m_D3Dpp.hDeviceWindow = hWnd; // Handle to the window
m_D3Dpp.Windowed = bWindowed; // Windowed or Full-screen?
m_D3Dpp.BackBufferCount = 1; // Number of back-buffers
m_D3Dpp.BackBufferFormat = D3DFMT_X8R8G8B8; // Back-buffer pixel format
m_D3Dpp.BackBufferWidth = m_nWidth; // Back-buffer width
m_D3Dpp.BackBufferHeight = m_nHeight; // Back-buffer height
m_D3Dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // Swap effectm_bVSync ? D3DPRESENT_INTERVAL_DEFAULT :
m_D3Dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
m_D3Dpp.FullScreen_RefreshRateInHz = bWindowed ? 0 : D3DPRESENT_RATE_DEFAULT;
m_D3Dpp.EnableAutoDepthStencil = TRUE; // Enable depth and stencil buffer
m_D3Dpp.AutoDepthStencilFormat = D3DFMT_D24S8; // Depth/Stencil buffer bit format
m_D3Dpp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; // Discard the depth/stencil buffer upon Present()
m_D3Dpp.MultiSampleQuality = 0; // MSAA quality
m_D3Dpp.MultiSampleType = D3DMULTISAMPLE_NONE; // MSAA type
// Check the device's capabilities
DWORD deviceBehaviorFlags = 0;
m_pD3DObject->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &m_D3DCaps);
// Determine vertex processing mode
if(m_D3DCaps.DevCaps & D3DCREATE_HARDWARE_VERTEXPROCESSING)
{
deviceBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
}
else
{
deviceBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
// if hardware vertex processing is on, check for pure
if(m_D3DCaps.DevCaps & D3DCREATE_PUREDEVICE && deviceBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING)
{
deviceBehaviorFlags |= D3DCREATE_PUREDEVICE;
}
// Create D3D Device
m_pD3DObject->CreateDevice(
D3DADAPTER_DEFAULT, // Default display adapter
D3DDEVTYPE_HAL, // Device type to use
hWnd, // Handle to our window
deviceBehaviorFlags, // D3DCREATE_HARDWARE_VERTEXPROCESSINGVertex Processing Behavior Flags (PUREDEVICE, HARDWARE_VERTEXPROCESSING, SOFTWARE_VERTEXPROCESSING)
&m_D3Dpp, // Presentation parameters
&m_pD3DDevice); // Return a created D3D Device
//=================================================================//
// Create/Load Sprite & Font D3D and COM objects
//Create font
D3DXCreateFont(m_pD3DDevice, 23, 0, FW_BOLD, 0, true,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, TEXT("Times New Roman"),
&m_pD3DFont);
//for font 1 "Name"
RECT rct;
rct.left=2;
rct.right=780;
rct.top=10;
rct.bottom=rct.top+20;
//MATRIX
eyePos.x = 0;
eyePos.y = 2;
eyePos.z = -10;
lookAt.x = 0;
lookAt.y = 0;
lookAt.z = 0;
upVec.x = 0;
upVec.y = 1;
upVec.z = 0;
D3DXMatrixLookAtLH( &view_Matrix, &eyePos, &lookAt, &upVec);
m_pD3DDevice->SetTransform( D3DTS_VIEW, &view_Matrix);
// projection matrix
D3DXMatrixPerspectiveFovLH( &pro_Matrix, FOV, aspectRatio, nearPlane, farPlane);
m_pD3DDevice->SetTransform( D3DTS_PROJECTION, &pro_Matrix);
// MATRIX: VertexElement Declaration
D3DVERTEXELEMENT9 declaration[] =
{
{0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},
{0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
D3DDECL_END()
};
//LPDIRECT3DVERTEXDECLARATION9 m_pVtxDeclObject;
// Create vertex declaration
m_pD3DDevice->CreateVertexDeclaration(declaration,&vertDec);
///---CUBE: Vertex and Indicies :START---///
// Load vertex info, listed per cube face quads
// Front
m_cubeVerts[0].position = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
m_cubeVerts[1].position = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
m_cubeVerts[2].position = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
m_cubeVerts[3].position = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
D3DXVec3Normalize(&m_cubeVerts[0].normal, &D3DXVECTOR3(0.0f, 0.0f, -1.0f));
D3DXVec3Normalize(&m_cubeVerts[1].normal, &D3DXVECTOR3(0.0f, 0.0f, -1.0f));
D3DXVec3Normalize(&m_cubeVerts[2].normal, &D3DXVECTOR3(0.0f, 0.0f, -1.0f));
D3DXVec3Normalize(&m_cubeVerts[3].normal, &D3DXVECTOR3(0.0f, 0.0f, -1.0f));
m_cubeVerts[0].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[1].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[2].uv = D3DXVECTOR2(1.0f, 0.0f);
m_cubeVerts[3].uv = D3DXVECTOR2(1.0f, 1.0f);
// Back
m_cubeVerts[4].position = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
m_cubeVerts[5].position = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
m_cubeVerts[6].position = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
m_cubeVerts[7].position = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
D3DXVec3Normalize(&m_cubeVerts[4].normal, &D3DXVECTOR3(0.0f, 0.0f, 1.0f));
D3DXVec3Normalize(&m_cubeVerts[5].normal, &D3DXVECTOR3(0.0f, 0.0f, 1.0f));
D3DXVec3Normalize(&m_cubeVerts[6].normal, &D3DXVECTOR3(0.0f, 0.0f, 1.0f));
D3DXVec3Normalize(&m_cubeVerts[7].normal, &D3DXVECTOR3(0.0f, 0.0f, 1.0f));
m_cubeVerts[4].uv = D3DXVECTOR2(1.0f, 1.0f);
m_cubeVerts[5].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[6].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[7].uv = D3DXVECTOR2(1.0f, 0.0f);
// Top
m_cubeVerts[8].position = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
m_cubeVerts[9].position = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
m_cubeVerts[10].position = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
m_cubeVerts[11].position = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
D3DXVec3Normalize(&m_cubeVerts[8].normal, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[9].normal, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[10].normal, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[11].normal, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
m_cubeVerts[8].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[9].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[10].uv = D3DXVECTOR2(1.0f, 0.0f);
m_cubeVerts[11].uv = D3DXVECTOR2(1.0f, 1.0f);
// Bottom
m_cubeVerts[12].position = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
m_cubeVerts[13].position = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
m_cubeVerts[14].position = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
m_cubeVerts[15].position = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
D3DXVec3Normalize(&m_cubeVerts[12].normal, &D3DXVECTOR3(0.0f, -1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[13].normal, &D3DXVECTOR3(0.0f, -1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[14].normal, &D3DXVECTOR3(0.0f, -1.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[15].normal, &D3DXVECTOR3(0.0f, -1.0f, 0.0f));
m_cubeVerts[12].uv = D3DXVECTOR2(1.0f, 1.0f);
m_cubeVerts[13].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[14].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[15].uv = D3DXVECTOR2(1.0f, 0.0f);
// Left
m_cubeVerts[16].position = D3DXVECTOR3(-1.0f, -1.0f, 1.0f);
m_cubeVerts[17].position = D3DXVECTOR3(-1.0f, 1.0f, 1.0f);
m_cubeVerts[18].position = D3DXVECTOR3(-1.0f, 1.0f, -1.0f);
m_cubeVerts[19].position = D3DXVECTOR3(-1.0f, -1.0f, -1.0f);
D3DXVec3Normalize(&m_cubeVerts[16].normal, &D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[17].normal, &D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[18].normal, &D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[19].normal, &D3DXVECTOR3(-1.0f, 0.0f, 0.0f));
m_cubeVerts[16].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[17].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[18].uv = D3DXVECTOR2(1.0f, 0.0f);
m_cubeVerts[19].uv = D3DXVECTOR2(1.0f, 1.0f);
// Right
m_cubeVerts[20].position = D3DXVECTOR3(1.0f, -1.0f, -1.0f);
m_cubeVerts[21].position = D3DXVECTOR3(1.0f, 1.0f, -1.0f);
m_cubeVerts[22].position = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
m_cubeVerts[23].position = D3DXVECTOR3(1.0f, -1.0f, 1.0f);
D3DXVec3Normalize(&m_cubeVerts[20].normal, &D3DXVECTOR3(1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[21].normal, &D3DXVECTOR3(1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[22].normal, &D3DXVECTOR3(1.0f, 0.0f, 0.0f));
D3DXVec3Normalize(&m_cubeVerts[23].normal, &D3DXVECTOR3(1.0f, 0.0f, 0.0f));
m_cubeVerts[20].uv = D3DXVECTOR2(0.0f, 1.0f);
m_cubeVerts[21].uv = D3DXVECTOR2(0.0f, 0.0f);
m_cubeVerts[22].uv = D3DXVECTOR2(1.0f, 0.0f);
m_cubeVerts[23].uv = D3DXVECTOR2(1.0f, 1.0f);
// Load index info, refers into index into verts array to compose triangles
// Note: A clockwise winding order of verts will show the front face.
// Front
m_cubeIndices[0] = 0; m_cubeIndices[1] = 1; m_cubeIndices[2] = 2; // Triangle 0
m_cubeIndices[3] = 0; m_cubeIndices[4] = 2; m_cubeIndices[5] = 3; // Triangle 1
// Back
m_cubeIndices[6] = 4; m_cubeIndices[7] = 5; m_cubeIndices[8] = 6; // Triangle 2
m_cubeIndices[9] = 4; m_cubeIndices[10] = 6; m_cubeIndices[11] = 7; // Triangle 3
// Top
m_cubeIndices[12] = 8; m_cubeIndices[13] = 9; m_cubeIndices[14] = 10; // Triangle 4
m_cubeIndices[15] = 8; m_cubeIndices[16] = 10; m_cubeIndices[17] = 11; // Triangle 5
// Bottom
m_cubeIndices[18] = 12; m_cubeIndices[19] = 13; m_cubeIndices[20] = 14; // Triangle 6
m_cubeIndices[21] = 12; m_cubeIndices[22] = 14; m_cubeIndices[23] = 15; // Triangle 7
// Left
m_cubeIndices[24] = 16; m_cubeIndices[25] = 17; m_cubeIndices[26] = 18; // Triangle 8
m_cubeIndices[27] = 16; m_cubeIndices[28] = 18; m_cubeIndices[29] = 19; // Triangle 9
// Right
m_cubeIndices[30] = 20; m_cubeIndices[31] = 21; m_cubeIndices[32] = 22; // Triangle 10
m_cubeIndices[33] = 20; m_cubeIndices[34] = 22; m_cubeIndices[35] = 23; // Triangle 11
///---CUBE: Vertex and Indicies :END---///
//create buffers
// create a vertex buffer interface called i_buffer
m_pD3DDevice->CreateVertexBuffer(4*6*sizeof(Vertex),
D3DUSAGE_WRITEONLY,
0,
D3DPOOL_MANAGED,
&VB,
NULL);
void* pVertices;
// lock VB and load the vertices into it
VB->Lock(0, 0,&pVertices, 0);
// send array
memcpy(pVertices, m_cubeVerts, 4*6*sizeof(Vertex));
//unlock
VB->Unlock();
///////////////////////////////////////////////////
m_pD3DDevice->CreateIndexBuffer(3*12*sizeof(WORD), // 3 and 12
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&IB,
NULL);
void* pIndices;
// lock index
IB->Lock(0,0,&pIndices,0);
//send array of indices to vram
memcpy(pIndices, m_cubeIndices, 3*12*sizeof(WORD));
//unlock index
IB->Unlock();
D3DLIGHT9 light;
D3DMATERIAL9 m_Mat;
ZeroMemory(&light, sizeof(light));
// clear out the light struct for use
light.Type = D3DLIGHT_POINT;
// make the light type 'directional light'
light.Diffuse.r = 0.5f;
light.Diffuse.g = 0.5f;
light.Diffuse.b = 0.5f;
light.Diffuse.a = 1.0f;
light.Ambient.r = 0.2f;
light.Ambient.g = 0.2f;
light.Ambient.b = 1.0f;
light.Specular.r = 1.0f;
light.Specular.g = 1.0f;
light.Specular.b = 1.0f;
// set the lighting position
light.Position.x = 30;
light.Position.y = 10;
light.Position.z = -10;
light.Range = 900.0f;
light.Attenuation0 = 0.0f;
light.Attenuation1 = 0.125f;
light.Attenuation2 = 0.0f;
m_pD3DDevice->SetLight(0, &light);
// send the light struct properties to light #0
m_pD3DDevice->LightEnable(0, TRUE);
// turn on light #0
ZeroMemory(&m_Mat, sizeof(m_Mat));
// clear out the struct for use
m_Mat.Diffuse.r = 1.0f;
m_Mat.Diffuse.g = 0.0f;
m_Mat.Diffuse.b = 0.0f;
m_Mat.Diffuse.a = 0.0f;
// set diffuse color to white
m_Mat.Ambient.r = 0.2f;
m_Mat.Ambient.g = 0.2f;
m_Mat.Ambient.b = 0.2f;
m_Mat.Ambient.a = 1.0f;
// set ambient color to white
m_Mat.Specular.r = 1.0f;
m_Mat.Specular.g =1.0f;
m_Mat.Specular.b =1.0f;
m_Mat.Specular.a =1.0f;
m_Mat.Power = 100.0f;
m_pD3DDevice->SetMaterial(&m_Mat);
// Create a texture using the with "test.tga" from the sprite labs.
//Apply tri-linear filtering to the texture, by modifying the sampler states by calling the device's SetSamplerState().
D3DXCreateTextureFromFile(m_pD3DDevice, L"test.png",&m_Texture);
//Apply tri-linear filtering to the texture, by modifying the sampler states by calling the device's SetSamplerState().
m_pD3DDevice->SetSamplerState( 0,D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState( 0,D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState( 0,D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
}
void DirectXGame::Update(HWND hWnd, bool& bWindowed, double dt)
{
}
void DirectXGame::Render()
{
// if our d3d device was not craeted return
if(!m_pD3DDevice)
return;
m_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(100,149,237), 1, 0); // 100,149,237 00255
// Begin the scene
if( SUCCEEDED( m_pD3DDevice->BeginScene() ) )
{
m_pD3DDevice->SetVertexDeclaration( vertDec);
//set cube postion
D3DXMATRIX translation, rotation, scale, world, position;
float index = 0.0f; index+=0.05f;
D3DXMatrixTranslation(&translation,0,0,0);
D3DXMatrixRotationY(&rotation, timeGetTime()/1000);
D3DXMatrixScaling(&scale,1,1, 1.0f);
world = scale*rotation*translation;
m_pD3DDevice->SetTransform(D3DTS_WORLD, &world);
// select the vertex and index buffers to use
m_pD3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
m_pD3DDevice->SetRenderState( D3DRS_SPECULARENABLE, TRUE );
m_pD3DDevice->SetRenderState( D3DRS_AMBIENT, D3DCOLOR_XRGB(60,60,60));
m_pD3DDevice->SetStreamSource(0, VB, 0, sizeof(Vertex));
m_pD3DDevice->SetIndices(IB);
m_pD3DDevice->SetMaterial(&m_Mat);
m_pD3DDevice->SetTexture( 0,m_Texture);
m_pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,//D3DPRIMITIVETYPE Type
0,/*BaseVertexIndex*/
0, //* MinIndex*/
24, /*NumVertices*/
0, /*StartIndex*/
12);//PrimitiveCount
///////////////////////////////////////////////////////////////////////////
//Font 1 "Name"
RECT rct;
rct.bottom = m_nHeight;
rct.top=2;
rct.left=658;
rct.right=m_nWidth;
//for the font2 FPS
RECT rect;
rect.bottom = m_nHeight;
rect.top =2;
rect.left = 10;
rect.right = m_nWidth;
wchar_t buffer[64];
swprintf_s(buffer, 64,L"Frames Per Second: %d", m_FPS);
m_pD3DFont->DrawText(0, buffer, -1, &rect, DT_TOP | DT_NOCLIP, D3DCOLOR_ARGB(255,255,255,255));
// Create a colour for the text ( blue)
D3DCOLOR fontColor = D3DCOLOR_ARGB(255,0,0,255);
//draw the text
m_pD3DFont->DrawText(NULL, L"Mariana Serrato", -1, &rct, 0, fontColor ); // move test to far right
// End the scene
m_pD3DDevice->EndScene();
// present the back buffer to the screen
m_pD3DDevice->Present(NULL, NULL, NULL, NULL);
//calculate Frames Per Second
m_currTime = timeGetTime();
static int fspCounter = 0;
if(m_currTime - m_prevTime >= 1000.0f)
{
m_prevTime = m_currTime;
m_FPS = fspCounter;
fspCounter =0;
} else {
++fspCounter;
}
}
}
void DirectXGame::Shutdown()
{
SAFE_RELEASE(VB);
SAFE_RELEASE(IB);
SAFE_RELEASE(vertDec);
SAFE_RELEASE(m_pD3DFont);
SAFE_RELEASE(m_Texture);
SAFE_RELEASE(m_Sprite);
SAFE_RELEASE(m_pD3DDevice);
SAFE_RELEASE(m_pD3DObject);
}
//////////////////////////////////////////////////////////////////////////////////////////
.h header file
pragma once
include // for random nums
include
include
include
include
include
include "DirectXInput.h"
include
include
pragma comment (lib, "d3d9.lib")
pragma comment (lib, "d3dx9.lib")
pragma comment(lib, "winmm.lib")//for timeGetTime()
pragma comment(lib, "dinput8.lib")
pragma comment(lib, "dxguid.lib")
// Macro to Safely release com obejcts
define SAFE_RELEASE(x) if(x) {x->Release(); x = 0;}
// Direct Input version
define DIRECTINPUT_VERSION 0x0800
// Define window size
define SCREEN_WIDTH 800
define SCREEN_HEIGHT 600
//#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)
class DirectXGame
{
struct Vertex
{
D3DXVECTOR3 position;
D3DXVECTOR3 normal;
D3DXVECTOR2 uv;
};
IDirect3D9* m_pD3DObject;
IDirect3DDevice9* m_pD3DDevice;
D3DPRESENT_PARAMETERS m_D3Dpp;
ID3DXFont* m_pD3DFont; //Font
LPDIRECT3DTEXTURE9 m_Texture;
ID3DXSprite* m_Sprite;//Sprite
D3DXVECTOR3 texCenter,eyePos,lookAt,upVec;
D3DCAPS9 m_D3DCaps; //D3D Device Caps
D3DLIGHT9 m_Light;
D3DMATERIAL9 m_Mat;
D3DVERTEXELEMENT9 m_Element;
D3DXMATRIX view_Matrix, pro_Matrix;
// cube
Vertex m_cubeVerts[24];
WORD m_cubeIndices[36];
IDirect3DVertexBuffer9* VB;
IDirect3DIndexBuffer9* IB;
IDirect3DVertexDeclaration9* vertDec;
bool m_bVSync;
char buffer [256];
int m_nWidth, m_nHeight;
int m_FPS,alfa[5],mFPS,mMilliSecPerFrame;
float m_currTime,m_prevTime,FOV, aspectRatio, nearPlane, farPlane;
DWORD D3DUSASE_DYNAMIC,D3DUSASE_WRITEONLY;
public:
DirectXGame(void);
~DirectXGame(void);
void Initialize(HWND hWnd,HINSTANCE hInst, bool bWindowed);
bool isDeviceLost();
void Update(HWND hWnd, bool& bWindowed, double dt);
void Render();
void CheckPosition();
void Shutdown();
};
You haven't enabled D3DRS_LIGHTING.
m_pD3DDevice->setRenderState(D3DRS_LIGHTING, TRUE);