C++, DirecX 9: Render Self-made Vertex Struct - c++

I'm new on StackOverflow and this is my first question.
I'm very new to C++ and DirectX9 so their may be a lot of Issues in my Code!
My Question:
I would like to Render an Structure of "D3DXVECTOR3"s for making a Heightmap from a .raw.
I have a working FP Camera System and want to implement a Heightmap. I followed the Tutorial "Terrain in DirectX9 and C++" (https://www.tutorials.de/threads/tutorial-terrain-in-directx-9-und-c-teil-1.343473/), but the Code don't work properly (The Tutorial is in "Bad" German, I used It because I didn't found any Tutorial for a Heightmap in DirectX9. ...And I'm german).
All it output is This (Ignore the Cylinder, it's only a test):
renderissue
Here are some relevant Parts of the Code:
Heightmap.cpp
BOOL LoadMapFromRAW(char* pcHMAP, UINT sizePerSide, BYTE **ppData)
{
BYTE *pData = NULL;
FILE *pFile = NULL;
// Open as Binary
pFile = fopen(pcHMAP, "rb");
if (!pFile)
return false;
// Memory
pData = new BYTE[sizePerSide*sizePerSide];
// Read
fread(&pData, 1, sizePerSide*sizePerSide, pFile);
*ppData = pData;
return true;
}
BOOL CreateVertices(UINT sizePerSide, BYTE *pVertexData, STerrainVector **ppVertices, UINT *uiTriangleCount)
{
UINT uiSizePerSide = sizePerSide - 1;
*uiTriangleCount = uiSizePerSide*uiSizePerSide*2;
// Memory for Vertices
STerrainVector *pVertices = new STerrainVector[(*uiTriangleCount) * 3];
// Buffer
int index = 0;
for (int x = 0; x < uiSizePerSide; x++)
for (int z = 0; z < uiSizePerSide; z++)
{
index += 6;
pVertices[index + 0].vPos = D3DXVECTOR3(x, pVertexData[z * sizePerSide + x], z);
pVertices[index + 1].vPos = D3DXVECTOR3(x, pVertexData[(z + 1) * sizePerSide + x], z + 1);
pVertices[index + 2].vPos = D3DXVECTOR3(x + 1, pVertexData[z * sizePerSide + x + 1], z);
pVertices[index + 3].vPos = D3DXVECTOR3(x + 1, pVertexData[(z) * sizePerSide + x + 1], z);
pVertices[index + 4].vPos = D3DXVECTOR3(x, pVertexData[(z + 1) * sizePerSide + x], z + 1);
pVertices[index + 5].vPos = D3DXVECTOR3(x + 1, pVertexData[(z + 1) * sizePerSide + x + 1], z + 1);
}
// Done
*ppVertices = pVertices;
return true;
}
main.cpp
//////////////UPDATE///////////////////
{
gDXdevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(160, 200, 255), 1.0f, 0);
gDXdevice->BeginScene();
// Get and set the view matrix
D3DXMATRIX viewMatrix;
gCamera->CalculateViewMatrix(&viewMatrix);
gDXdevice->SetTransform(D3DTS_VIEW, &viewMatrix)
// Draw Heightmap
gDXdevice->SetFVF(D3DFVF_XYZ);
gDXdevice->DrawPrimitiveUP(D3DPT_TRIANGLELIST, uiTriangleCount, (void*)&pVertices, sizeof(STerrainVector));
gDXdevice->EndScene();
gDXdevice->Present(0, 0, 0, 0);}
<pre> <code>
////////////////////////Part in Setup////////////////////////
bool SetupDirect3D(HWND hWnd)
{
// Standart Directx Init
gDX3dObject = Direct3DCreate9(D3D_SDK_VERSION);
if (!gDX3dObject)
return 0;
D3DPRESENT_PARAMETERS presParams;
ZeroMemory(&presParams, sizeof(presParams));
presParams.Windowed = TRUE;
presParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
presParams.BackBufferFormat = D3DFMT_UNKNOWN;
presParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
presParams.EnableAutoDepthStencil = TRUE;
presParams.AutoDepthStencilFormat = D3DFMT_D16;
HRESULT hr = gDX3dObject->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING, &presParams, &gDXdevice);
if (FAILED(hr))
return false;
// Z-Buffer
gDXdevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
// Create a Model to View
hr = D3DXCreateCylinder(gDXdevice, 0.1f, 0.1f, 1.0f, 10, 10, &gCylinderMesh, 0);
if (FAILED(hr))
return false;
hr = D3DXCreatePolygon(gDXdevice, 10.0f, 4, &gPlateMesh, 0);
if (FAILED(hr))
return false;
// Light for Model
gDXdevice->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(20, 20, 20));
gDXdevice->SetRenderState(D3DRS_LIGHTING, TRUE);
// A light-structure
D3DLIGHT9 light;
ZeroMemory(&light, sizeof(D3DLIGHT9));
light.Type = D3DLIGHT_DIRECTIONAL;
light.Diffuse.a = 1.0f;
light.Diffuse.b = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffuse.r = 1.0f;
light.Range = 1000.0f;
// Direction for Light
D3DXVECTOR3 vecDir;
vecDir = D3DXVECTOR3(0.0f, -0.3f, 0.7f);
D3DXVec3Normalize((D3DXVECTOR3*)&light.Direction, &vecDir);
// Turn it on!
gDXdevice->SetLight(0, &light);
gDXdevice->LightEnable(0, TRUE);
// Create World
hr = LoadMapFromRAW("heightMap.raw", 1024, &pHeightData);
if (!hr)
return false;
hr = CreateVertices(1024, pHeightData, &pVertices, &uiTriangleCount);
if (!hr)
return false;
// Set up a Matrix
RECT rect;
GetClientRect(hWnd, &rect);
D3DXMATRIX matProj;
float aspect = (rect.right - rect.left) / (float)(rect.bottom - rect.top);
D3DXMatrixPerspectiveFovLH(&matProj, D3DX_PI / 4, aspect, 1.0f, 100.0f);
gDXdevice->SetTransform(D3DTS_PROJECTION, &matProj);
return true;
}
....Had a Hard time with the Code.....
The "*pHeightData; *pVertices; uiTriangleCount" are defined at the start of the Code.
I Hope you can help me!
I apologize for the the bad english: I'm German and still in School! :-)
Thanks in Advance!

So... I solved by myself. The solution was: Complete rewrite! For anyone with the same/similar problem: http://www.riemers.net/eng/Tutorials/DirectX/C++/Series1/tut13.php That is a very good Tutorial I've found! Try It!

Related

Alternative way to SwapChain->Present to draw a frame on DX11

I need to hook DX11 on a game to draw some rectangle.
To do it I have tried some source code but actually the only one that work in my case is ImGui:
https://github.com/ocornut/imgui
theoretically I can use it, but because in my case I need to draw only some line I like to consider other altarnative.
For this reason I have tried this example:
http://www.directxtutorial.com/Lesson.aspx?lessonid=11-4-5
that work on a test desktop project but not in my dll that hook the game.
My dll crash in this line:
pChain->Present(0, 0);
becouse I have already hook with detour this method:
HRESULT __stdcall IDXGISwapChain_Present(IDXGISwapChain* pChain, UINT SyncInterval, UINT Flags)
{
// Get device and swapchain
if (!bGraphicsInitialised)
{
// Init Direct X
if (!InitDirectXAndInput(pChain)) return fnIDXGISwapChainPresent(pChain, SyncInterval, Flags);
// Init ImGui
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
// Setup rendering and IO
ImGui_ImplWin32_Init(hWindow);
ImGui_ImplDX11_Init(pDevice, pContext);
ImGui::GetIO().ImeWindowHandle = hWindow;
// Create render target view for rendering
ID3D11Texture2D* pBackBuffer;
pChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
HRESULT hr = pDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRenderTargetView);
if (FAILED(hr))
{
std::cerr << "Failed to create render target view" << std::endl;
return fnIDXGISwapChainPresent(pChain, SyncInterval, Flags);
}
pBackBuffer->Release();
bGraphicsInitialised = true;
}
LF::Log_Update("IDXGISwapChain_Present");
// Render ImGui
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
ImGui::ShowDemoWindowCustom(test);
ImGui::EndFrame();
ImGui::Render();
pContext->OMSetRenderTargets(1, &pRenderTargetView, NULL);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
return fnIDXGISwapChainPresent(pChain, SyncInterval, Flags);
}
with this code my dll (that use ImuGui) work perfectly and not need "swapChain->Present".
Here my dll without ImuGui:
HRESULT __stdcall IDXGISwapChain_Present(IDXGISwapChain* pChain, UINT SyncInterval, UINT Flags)
{
// Get device and swapchain
if (!bGraphicsInitialised)
{
// Init Direct X
if (!InitDirectXAndInput(pChain)) return fnIDXGISwapChainPresent(pChain, SyncInterval, Flags);
// Init ImGui
////ImGui::CreateContext();
////ImGuiIO& io = ImGui::GetIO(); (void)io;
////io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
////// Setup rendering and IO
////ImGui_ImplWin32_Init(hWindow);
////ImGui_ImplDX11_Init(pDevice, pContext);
////ImGui::GetIO().ImeWindowHandle = hWindow;
// set up and initialize Direct3D
InitD3D(hWindow, pDevice, pContext);
// Create render target view for rendering
ID3D11Texture2D* pBackBuffer;
pChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
HRESULT hr = pDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRenderTargetView);
if (FAILED(hr))
{
std::cerr << "Failed to create render target view" << std::endl;
return fnIDXGISwapChainPresent(pChain, SyncInterval, Flags);
}
pBackBuffer->Release();
bGraphicsInitialised = true;
}
RenderFrame();
pChain->Present(0, 0);
LF::Log_Update("pChain->Present(1, 0)");
return fnIDXGISwapChainPresent(pChain, SyncInterval, Flags);
}
and here my renderframe:
// this is the function used to render a single frame
void RenderFrame(void)
{
if (VectVertices.size() < 1)
return;
// Set transparent color
float color[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
// clear the back buffer
devcon->ClearRenderTargetView(backbuffer, color);
// select which vertex buffer to display
UINT stride = sizeof(VERTEX);
UINT offset = 0;
devcon->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);
// select which primtive type we are using
// draw the vertex buffer to the back buffer
devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
devcon->Draw(VectVertices.size(), 0);
// swapchain->Present(0, 0);
}
in short my code not work becouse shouldn't use swapchain->Present that is hooked.
The here the working rendering method of imuGUI:
// Render function
void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
return;
ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
// Create and grow vertex/index buffers if needed
if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
{
if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
D3D11_BUFFER_DESC desc;
memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
return;
}
if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
{
if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
D3D11_BUFFER_DESC desc;
memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
return;
}
// Upload vertex/index data into a single contiguous GPU buffer
D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
return;
if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
return;
ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
vtx_dst += cmd_list->VtxBuffer.Size;
idx_dst += cmd_list->IdxBuffer.Size;
}
ctx->Unmap(g_pVB, 0);
ctx->Unmap(g_pIB, 0);
// Setup orthographic projection matrix into our constant buffer
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
{
D3D11_MAPPED_SUBRESOURCE mapped_resource;
if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
return;
VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
float mvp[4][4] =
{
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
{ 0.0f, 0.0f, 0.5f, 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
};
memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
ctx->Unmap(g_pVertexConstantBuffer, 0);
}
// Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
struct BACKUP_DX11_STATE
{
UINT ScissorRectsCount, ViewportsCount;
D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
ID3D11RasterizerState* RS;
ID3D11BlendState* BlendState;
FLOAT BlendFactor[4];
UINT SampleMask;
UINT StencilRef;
ID3D11DepthStencilState* DepthStencilState;
ID3D11ShaderResourceView* PSShaderResource;
ID3D11SamplerState* PSSampler;
ID3D11PixelShader* PS;
ID3D11VertexShader* VS;
ID3D11GeometryShader* GS;
UINT PSInstancesCount, VSInstancesCount, GSInstancesCount;
ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation
D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
DXGI_FORMAT IndexBufferFormat;
ID3D11InputLayout* InputLayout;
};
BACKUP_DX11_STATE old;
old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
ctx->RSGetState(&old.RS);
ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
ctx->PSGetSamplers(0, 1, &old.PSSampler);
old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256;
ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
ctx->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount);
ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
ctx->IAGetInputLayout(&old.InputLayout);
// Setup desired DX state
ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
// Render command lists
// (Because we merged all buffers into a single one, we maintain our own offset into them)
int global_idx_offset = 0;
int global_vtx_offset = 0;
ImVec2 clip_off = draw_data->DisplayPos;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != NULL)
{
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Apply scissor/clipping rectangle
const D3D11_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) };
ctx->RSSetScissorRects(1, &r);
// Bind texture, Draw
ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->TextureId;
ctx->PSSetShaderResources(0, 1, &texture_srv);
ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
}
}
global_idx_offset += cmd_list->IdxBuffer.Size;
global_vtx_offset += cmd_list->VtxBuffer.Size;
}
// Restore modified DX state
ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
ctx->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release();
for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
}
Can you please suggest me a way to avoid to use pChain->Present(0, 0) ?
Thank you !

DirectX cuts Vertex and only draws last call

This is what happens in DirectX:
What it should do is display 5 of those birds. It only does one (the last one) and also not correctly.
And this is how it really should look like (same buffers etc., but done in openGL):
So any idea what could cause the problem?
My calls are:
Initialize:
this->device->QueryInterface(__uuidof(IDXGIDevice), (LPVOID*)&dxgiDevice);
dxgiDevice->GetAdapter(&adapter);
adapter->GetParent(IID_PPV_ARGS(&factory));
ZeroMemory(&swapChainDescription, sizeof(swapChainDescription));
swapChainDescription.BufferDesc.Width = this->description.ResolutionWidth;
swapChainDescription.BufferDesc.Height = this->description.ResolutionHeight;
swapChainDescription.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDescription.BufferDesc.RefreshRate.Numerator = 60;
swapChainDescription.BufferDesc.RefreshRate.Denominator = 1;
swapChainDescription.BufferDesc.Scaling = DXGI_MODE_SCALING_STRETCHED;
swapChainDescription.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
swapChainDescription.SampleDesc.Count = 1;
swapChainDescription.SampleDesc.Quality = 0;
swapChainDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDescription.BufferCount = 1;
swapChainDescription.OutputWindow = this->hwnd;
swapChainDescription.Windowed = !this->window->GetDescription().Fullscreen;
swapChainDescription.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDescription.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
factory->CreateSwapChain(this->device, &swapChainDescription, &this->swapChain);
this->swapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&backBuffer);
this->device->CreateRenderTargetView(backBuffer, NULL, &this->backBufferView);
backBuffer->Release();
ZeroMemory(&depthStencilDescription, sizeof(depthStencilDescription));
depthStencilDescription.Width = this->description.ResolutionWidth;
depthStencilDescription.Height = this->description.ResolutionHeight;
depthStencilDescription.MipLevels = 1;
depthStencilDescription.ArraySize = 1;
depthStencilDescription.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilDescription.SampleDesc.Count = 1;
depthStencilDescription.SampleDesc.Quality = 0;
depthStencilDescription.Usage = D3D10_USAGE_DEFAULT;
depthStencilDescription.BindFlags = D3D10_BIND_DEPTH_STENCIL;
depthStencilDescription.CPUAccessFlags = 0;
depthStencilDescription.MiscFlags = 0;
this->device->CreateTexture2D(&depthStencilDescription, 0, &depthStencilBuffer);
this->device->CreateDepthStencilView(depthStencilBuffer, 0, &this->depthStencilBufferView);
depthStencilBuffer->Release();
viewPort.Width = this->description.ResolutionWidth;
viewPort.Height = this->description.ResolutionHeight;
viewPort.MinDepth = 0.0f;
viewPort.MaxDepth = 1.0f;
viewPort.TopLeftX = 0;
viewPort.TopLeftY = 0;
this->device->RSSetViewports(1, &viewPort);
D3D10_BLEND_DESC BlendState;
ZeroMemory(&BlendState, sizeof(D3D10_BLEND_DESC));
BlendState.AlphaToCoverageEnable = FALSE;
BlendState.BlendEnable[0] = TRUE;
BlendState.SrcBlend = D3D10_BLEND_SRC_ALPHA;
BlendState.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
BlendState.BlendOp = D3D10_BLEND_OP_ADD;
BlendState.SrcBlendAlpha = D3D10_BLEND_ZERO;
BlendState.DestBlendAlpha = D3D10_BLEND_ZERO;
BlendState.BlendOpAlpha = D3D10_BLEND_OP_ADD;
BlendState.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
this->device->CreateBlendState(&BlendState, &this->blendState);
Each Frame (broken down to):
this->device->OMSetBlendState(this->blendState, 0, 0xffffffff);
this->device->OMSetRenderTargets(1, &this->backBufferView, this->depthStencilBufferView);
this->device->ClearRenderTargetView(this->backBufferView, &Color.colors[0]);
this->device->ClearDepthStencilView(this->depthStencilBufferView, D3D10_CLEAR_DEPTH |
D3D10_CLEAR_STENCIL, 1.0f, 0);
in for loop (5 times):
ID3D10Buffer* buff = (ID3D10Buffer*)buffer->GetData();
UINT stride = buffer->GetStride();
UINT offset = 0;
this->device->IASetVertexBuffers(0, 1, &buff, &stride, &offset);
ID3D10Buffer* buff = (ID3D10Buffer*)buffer->GetData();
this->device->IASetIndexBuffer(buff, DXGI_FORMAT_R32_UINT, 0);
this->device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
this->device->DrawIndexed(Indexes, 0, 0);
At the End
this->swapChain->Present(0, 0);
I got it fixed, here for others:
Vertices getting cut:
my near/far plane were to near to eachother. (they were 0.1f and 100.0f) Changed both values and now they work.
DirectX only drawing last call:
Had to apply material again for each model.
So doing
// Set coresponding input layout
this->device->IASetInputLayout(this->inputLayout);
// Apply specified pass of current technique
this->technique->GetPassByIndex(0)->Apply(0);

Directx exception

I have a project that I started a while ago on my other laptop, which was running windows vista. I got a new laptop running windows 8, and wanted to run the project on it, but it gives me an unhandled exception. I have directx included in the program. It says Unhandled exception at 0x0f91a253. violation reading location 0xae8b587c. Here is some of my code
#pragma region Effects
// Load our effect file
D3DXCreateEffectFromFile(m_pD3DDevice, L"Effect.fx", 0, 0, 0, 0, &m_pEffect, &m_pEffectError);
m_hTech = m_pEffect->GetTechniqueByName("Effect");
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//Sun.jpg", &m_pTexture[0]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//earth.jpg", &m_pTexture[1]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//mercury.jpg", &m_pTexture[2]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//venus.jpg", &m_pTexture[3]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//mars.jpg", &m_pTexture[4]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//jupiter.jpg", &m_pTexture[5]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//saturn.jpg", &m_pTexture[6]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//uranus.jpg", &m_pTexture[7]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//neptune.jpg", &m_pTexture[8]);
D3DXCreateTextureFromFile(m_pD3DDevice, L"1.bmp", &mTex0);
D3DXCreateTextureFromFile(m_pD3DDevice, L"Textures//moon.jpg", &m_pTexture[9]);
m_pEffect->SetTexture("Texture", mTex0);
m_pEffect->SetFloat("DiffuseIntensity", 1.5f );
m_pEffect->SetFloat("LineThickness", 0.15f );
#pragma endregion Effects
#pragma region Object Positions
//positions
DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&input, NULL);
// Initialize Keyboard
input->CreateDevice(GUID_SysKeyboard, &m_pDIKeyboard, NULL);
// Initialize Mouse
input->CreateDevice(GUID_SysMouse, &m_pDIMouse, NULL);
// Set up Keyboard
m_pDIKeyboard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
m_pDIKeyboard->SetDataFormat(&c_dfDIKeyboard);
// Set up Mouse (c_dfDIMouse2 = 8 button mouse)
m_pDIMouse->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
m_pDIMouse->SetDataFormat(&c_dfDIMouse2);
D3DXVECTOR3 pos[12];
planetscaling[0] = 95.0f;
planetscaling[1] = 900.0f;
planetscaling[2] = 900.0f;
planetscaling[3] = 900.0f;
planetscaling[4] = 1000.0f;
planetscaling[5] = 600.0f;
planetscaling[6] = 650.0f;
planetscaling[7] = 665.0f;
planetscaling[8] = 660.0f;
planetscaling[9] = 1350.0f;
pos[0] = D3DXVECTOR3(0.0f, 0.0f, planetscaling[0]); // Sun
pos[1] = D3DXVECTOR3(150.0f, 20.0f, planetscaling[1]); // Earth
pos[2] = D3DXVECTOR3(50.0f, 50.0f, planetscaling[2]); // Mercury
pos[3] = D3DXVECTOR3(100.0f, 0.0f, planetscaling[3]); // Venus
pos[4] = D3DXVECTOR3(0.0f, -200.0f, planetscaling[4]); // Mars
pos[5] = D3DXVECTOR3(-40.0f, 0.0f, planetscaling[5]); // Jupiter
pos[6] = D3DXVECTOR3(-50.0f, -100.0f, planetscaling[6]); // Saturn
pos[7] = D3DXVECTOR3(20.0f, -100.0f, planetscaling[7]); // Uranus
pos[8] = D3DXVECTOR3(0.0f, -70.0f, planetscaling[8]); // Neptune
pos[9] = D3DXVECTOR3(300.0f, 320.0f, planetscaling[9]);
Object[0].set(Sun, pos[0], 4.8f, -1, mTex0); // Sun
Object[1].set(PLANET, pos[1], 4.8f, -1, mTex0); // Earth
Object[2].set(PLANET, pos[2], 4.8f, -1, mTex0); // Mercury
Object[3].set(PLANET, pos[3], 4.8f, -1, mTex0); // Venus
Object[4].set(PLANET, pos[4], 4.8f, -1, mTex0); // Mars
Object[5].set(PLANET, pos[5], 4.8f, -1, mTex0); // Jupiter
Object[6].set(PLANET, pos[6], 4.8f, -1, mTex0); // Saturn
Object[7].set(PLANET, pos[7], 4.8f, -1, mTex0); // Uranus
Object[8].set(PLANET, pos[8], 4.8f, -1, mTex0); // Neptune
Object[9].set(MOON, pos[9], 4.8f, -1, mTex0); // moon
#pragma endregion Object Positions
}
void PlanetClass::Update(double dt, IDirect3DDevice9* m_pD3DDevice)
{
for(int i = 0; i < 12; i++)
{
if(i == 0)
continue;
D3DXMatrixRotationY(&rotMat, (float)timeGetTime() * 0.009f);
D3DXMatrixTranslation(&TransMat, Object[i].position.x, Object[i].position.y, Object[i].position.z);
D3DXMatrixScaling(&ScaleMat, planetscaling[i], planetscaling[i], planetscaling[i]);
Object[i].toParentXForm = rotMat * TransMat;
}
D3DXMatrixRotationY(&rotMat, 5.0f);
D3DXMatrixTranslation(&TransMat, Object[0].position.x, Object[0].position.y, Object[0].position.z);
D3DXMatrixScaling(&ScaleMat, planetscaling[0], planetscaling[0], planetscaling[0]);
Object[0].toParentXForm = rotMat * TransMat;
Object[0].ScaleXForm = ScaleMat * TransMat;
DIMOUSESTATE2 mouseState;
ZeroMemory(&mouseState, sizeof(mouseState));
// Get the input device state
hr = m_pDIMouse->GetDeviceState( sizeof(DIMOUSESTATE2), &mouseState );
if(FAILED(hr))
{
hr = m_pDIMouse->Acquire();
// Device has probably been lost if failed, if so keep trying to get it until it’s found.
while( hr == DIERR_INPUTLOST)
{
hr = m_pDIMouse->Acquire();
}
// If we failed for some other reason
for(int i = 0; i < 12; i++)
{
if(FAILED(hr))
return;
// Read the device state again
m_pDIMouse->GetDeviceState(sizeof(DIMOUSESTATE2), &mouseState);
}
}
for(int i = 0; i < 12; i++)
{
if(mouseState.rgbButtons[1] & 0x80)
{
planetscaling[i] += mouseState.lX * 0.01f; // X Axis
planetscaling[i] += mouseState.lY * 0.01f; // Y Axis
m_pD3DDevice->SetRenderState(D3DRS_NORMALIZENORMALS, true);
}
}
rad = 270.0f;
radM = 150.0f;
radV = 215.0f;
radMA = 360.0f;
radJ = 260.0f;
radS = 330.0f;
radU = 390.0f;
radN = 450.0f;
radMO = 370.0f;
radMOON = 300.0f;
double time = timeGetTime() * 0.00009;
double timeM = timeGetTime() * 0.0002;
double timeV = timeGetTime() * 0.0001;
double timeMA = timeGetTime() * 0.00008;
double timeJ = timeGetTime() * 0.000009;
double timeS = timeGetTime() * 0.000008;
double timeU = timeGetTime() * 0.000007;
double timeN = timeGetTime() * 0.000006;
double timeMO = timeGetTime() * 0.00009;
double timeMOON = timeGetTime() * 0.00009;
Object[2].position.x = sin(timeM)*radM;
Object[2].position.y = cos(timeM)*radM;
Object[3].position.x = sin(timeV)*radV;
Object[3].position.y = cos(timeV)*radV;
Object[1].position.x = sin(time)*rad;
Object[1].position.y = cos(time)*rad;
Object[4].position.x = sin(timeMA)*radMA;
Object[4].position.y = cos(timeMA)*radMA;
Object[5].position.x = sin(timeJ)*radJ;
Object[5].position.y = cos(timeJ)*radJ;
Object[6].position.x = sin(timeS)*radS;
Object[6].position.y = cos(timeS)*radS;
Object[7].position.x = sin(timeU)*radU;
Object[7].position.y = cos(timeU)*radU;
Object[8].position.x = sin(timeN)*radN;
Object[8].position.y = cos(timeN)*radN;
Object[9].position.x = sin(timeMO)*radMO;
Object[9].position.y = cos(timeMO)*radMO;
Object[9].position.x = sin(timeMOON)*radMOON;
Object[9].position.y = cos(timeMOON)*radMOON;
// For each object...
for(int i = 0; i < 12; ++i)
{
// Initialize to identity matrix.
D3DXMatrixIdentity(&Object[i].toWorldXForm);
D3DXMatrixIdentity(&Object[0].ScaleForm);
// The ith object's world transform is given by its
// to-parent transform, followed by its parent's
// to-parent transform, followed by its grandparent's
// to-parent transform, and so on, up to the root's
// to-parent transform.
int k = i;
while( k != -1 ) // While there exists an ancestor.
{
Object[i].toWorldXForm *= Object[k].toParentXForm;
Object[i].ScaleForm *= Object[k].ScaleXForm;
k = Object[k].parent; // Move up the ancestry chain.
k = Object[k].parent2;
}
}
}
It actually crashes right at the end of the while loop, and when it does it opens up a new file called d3dx9math.inl, which I don't even understand, because thats not my file, but its a file associated with directx. Here is the code that it shows me when it does crash
D3DXMATRIX::operator FLOAT* ()
{
return (FLOAT *) &_11;
}
D3DXINLINE
D3DXMATRIX::operator CONST FLOAT* () const
{
return (CONST FLOAT *) &_11;
}
// assignment operators
D3DXINLINE D3DXMATRIX&
D3DXMATRIX::operator *= ( CONST D3DXMATRIX& mat )
{
D3DXMatrixMultiply(this, this, &mat);
return *this;
}
D3DXINLINE D3DXMATRIX&
D3DXMATRIX::operator += ( CONST D3DXMATRIX& mat )
{
_11 += mat._11; _12 += mat._12; _13 += mat._13; _14 += mat._14;
_21 += mat._21; _22 += mat._22; _23 += mat._23; _24 += mat._24;
_31 += mat._31; _32 += mat._32; _33 += mat._33; _34 += mat._34;
_41 += mat._41; _42 += mat._42; _43 += mat._43; _44 += mat._44;
return *this;
}
D3DXINLINE D3DXMATRIX&
D3DXMATRIX::operator -= ( CONST D3DXMATRIX& mat )
{
_11 -= mat._11; _12 -= mat._12; _13 -= mat._13; _14 -= mat._14;
_21 -= mat._21; _22 -= mat._22; _23 -= mat._23; _24 -= mat._24;
_31 -= mat._31; _32 -= mat._32; _33 -= mat._33; _34 -= mat._34;
_41 -= mat._41; _42 -= mat._42; _43 -= mat._43; _44 -= mat._44;
return *this;
}
it shows the arrow pointing inside this function D3DXMATRIX::operator *= ( CONST D3DXMATRIX& mat ), at the return *this line. I don't know if this exception has to do with trying to run it on a new operating system, or maybe something isn't installed on the computer, but was installed on the previous one. and this is a 3d project as well, but I also noticed that when I go inside the project folder and trying to open up one of the 3d objects, it says an error occurred tying to open that type of file, which is a .x file. Its weird to because I have directx installed on the computer. Microsoft directx sdk (June 2010) version. I don't know if its the version of directx or that I cant open up the .x file from the project folder which could be causing the project to crash like it is. So this is my issue, and any help would be greatly appreciated
Thanks a lot

Using Direct 3D's index buffer

I am writing a program that generates a sphere and renders it using a Direct 3D device. I am using an Index buffer and I am having trouble figuring out why my triangles are so messed up. I tested the positions of the vertices sent to the vertex buffer, and they all look like they are in perfekt position.
The primitive type used is D3DPT_TRIANGLESTRIP.
I'd be really happy if someone could point out where in my understanding of index buffers I fail horribly, and maybe tell me how shizzle works.
This is my Code:
bool CGameApp::CreateSphere( ULONG nColor, LPDIRECT3DVERTEXBUFFER9 * ppVertexBuffer, LPDIRECT3DINDEXBUFFER9 * ppIndexBuffer, ULONG & nNumVertices, ULONG & nNumFaces )
{
float x, y = 0.0f, z = 0.0f;
float r = 0.0f; // the radius calculated for each circle
ULONG nUsage= D3DUSAGE_WRITEONLY;
LPDIRECT3DVERTEXBUFFER9 pVertexBuffer = NULL;
LPDIRECT3DINDEXBUFFER9 pIndexBuffer = NULL;
HRESULT hRet;
CVertex * pVertex = NULL;
ULONG * pIndex = NULL;
ULONG nSlices, nStacks, jump= 10;
ULONG nStack, nSlice;
if (ppVertexBuffer != NULL) *ppVertexBuffer = NULL;
if (ppIndexBuffer != NULL) *ppIndexBuffer = NULL;
// Validate parameters
if (ppVertexBuffer == NULL | ppIndexBuffer == NULL )
return false;
// The Poles are hardcoded, the rest generated using trigonometry
x = -1.0f;
m_aSphere.push_back(CVertex(x, y, z, 0xFF0000FF));
for (int degreesX = 180; degreesX >= 0; degreesX -= 10) //stack ( 18 stacks )
{
x = (float)cos(D3DXToRadian(degreesX));
for (int degreesY = 0; degreesY < 360; degreesY+= 10) // slices ( 36 slices )
{
r = (float)sin(D3DXToRadian(degreesX));
y = (float)sin(D3DXToRadian(degreesY)) * r; // regulate each unit circle
z = (float)cos(D3DXToRadian(degreesY)) * r; // by multiplying with radius
m_aSphere.push_back(CVertex(x, y, z, nColor));
}
}
nStacks = 180 / jump;
nSlices = 360 / jump;
x = 1.0f; y = 0.0f; z = 0.0f;
m_aSphere.push_back(CVertex(x, y, z, 0xFF0000FF));
//m_aSphere.push_back(CVertex(0, 0, 0, 0xFF0000FF));
/////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////
nNumFaces= nStacks * nSlices * 2;
nNumVertices = m_aSphere.size();
VERTEXPROCESSING_TYPE vp = m_D3DSettings.GetSettings()->VertexProcessingType;
if (vp != HARDWARE_VP && vp != PURE_HARDWARE_VP) nUsage |= D3DUSAGE_SOFTWAREPROCESSING;
hRet = m_pD3DDevice->CreateVertexBuffer(sizeof(CVertex)* m_aSphere.size(), D3DUSAGE_WRITEONLY,
D3DFVF_XYZ | D3DFVF_DIFFUSE, D3DPOOL_MANAGED, &pVertexBuffer, NULL);
if (FAILED(hRet)) return false;
// Lock the vertex buffer ant run in the array generated.
hRet = pVertexBuffer->Lock(0, sizeof(CVertex)* m_aSphere.size(), (void**)&pVertex, 0);
if (FAILED(hRet))
{
pVertexBuffer->Release();
return false;
}
// Load the Vertices into the vertex buffer
for (int i = 0; i <= m_aSphere.size() - 1; i++)
{
*pVertex++ = m_aSphere[i];
}
pVertexBuffer->Unlock(); // Unlock the Vertex Buffer yet again.
// Initialize the Index Buffer
hRet = m_pD3DDevice->CreateIndexBuffer( nNumFaces * 3 * sizeof(ULONG) , nUsage, D3DFMT_INDEX16,
D3DPOOL_MANAGED, &pIndexBuffer, NULL );
if (FAILED(hRet))
{
pIndexBuffer->Release();
pVertexBuffer->Release();
return false;
}
//Try to Lock the index buffer to apply the index stream
hRet = pIndexBuffer->Lock(0, 0, (void**)&pIndex, 0);
if (FAILED(hRet))
{
pIndexBuffer->Release();
pIndex= NULL;
return false;
} // Lock was Successful!
// Here the vertices will be awesomely interpreted by the Index Buffer!!!!!!
// This is where things go wrong apparently
for (nStack = 10; nStack < nStacks; nStack++)
{
for (nSlice = 10; nSlice < nSlices; nSlice++)
{
*pIndex++ = nStack * nSlice;
*pIndex++ = (nStack + 1) * nSlice;
}
*pIndex++ = (nStack + 1) * nSlice; // Make degenerate triangle, then start new stack!
}
pIndexBuffer->Unlock(); // unlock the index buffer;
//return pointers
*ppVertexBuffer = pVertexBuffer;
*ppIndexBuffer = pIndexBuffer;
// Success!
return true;
}
This is the outcome showed in fillmode Wireframe.:
http://imgur.com/2D4NN5e
Thank you in advance :)

c++ DirectX function Present() not working

I'm working on simple graphic library in DirectX. I use Dx 9 because I'm pretty new in it and I have found a good programming book written for 9th version. Anyway, I can't get anything on the screen because Device's function Present() returns E_FAIL code 0x80004005 (which what I've read mean 'Unspecified failure').
I've also checked all Dx functions used in program and none of them returns fail (except Present() obviously).
The program works fine if I comment line kAnimation.Render() from main.cpp
Here's the causing problems part of code:
main.cpp:
//...
if(FAILED(g_pkD3DDevice->BeginScene())) return ErrorBeginScene;
kAnimation.Render();
if(FAILED(g_pkD3DDevice->EndScene())) return ErrorEndScene;
HRESULT hr;
hr = g_pkD3DDevice->Present(NULL, NULL, NULL, NULL); //Returns E_FAIL
if(FAILED(hr)) return ErrorPresent;
Animation.cpp:
#define D3DFVF_MYVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1)
Error Animation::Render()
{
//...
//This is what contain fX[4] and fY[4] and other variables while debugging
//float fX[4]
//float fY[4]
//fX[0] = -16; fX[1] = 16; fX[2] = -16; fX[3] = 16;
//fY[0] = 16; fY[1] = 16; fY[2] = -16; fY[3] = -16;
//m_iCellHeight = 32
//m_iCellWidth = 32
//m_iTextureWidth = 128
//m_iTextureHeight = 128
//kTextCoord.Left = 1/128; .Right = 33/128; .Top = 1/128; .Bottom = 33/128;
Rect kTextCoord = GetUV(CellID(0,0));
Vertex kVertices[] =
{ //x, y, z, w, color, texture coord (u, v)
{ fX[2], fY[2], 0, 1.0f, iColor, kTextCoord.Left, kTextCoord.Top},
{ fX[3], fY[3], 0, 1.0f, iColor, kTextCoord.Right, kTextCoord.Top},
{ fX[1], fY[1], 0, 1.0f, iColor, kTextCoord.Right, kTextCoord.Bottom},
{ fX[0], fY[0], 0, 1.0f, iColor, kTextCoord.Left, kTextCoord.Boottom},
};
g_D3DDevice->SetTexture(0, m_pkD3DTexture);
g_D3DDevice->SetFVF(D3DFVF_MYVERTEX);
if(FAILED(g_D3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, kVertices, sizeof(Vertex)))
return ErrorDrawPrimitive;
return NoError;
}
Rect Animation::GetUV(CellID kPosition)
{
Rect kUVRect;
kUVRect.Left = (1 + ((1 + m_iCellWidth) * kPosition.x)) / m_iTextureWidth;
kUVRect.Right = (1 + ((1 + m_iCellWidth) * kPosition.x) + m_iCellWidth) / m_iTextureWidth;
kUVRect.Top = (1 + ((1 + m_iCellHeight) * kPosition.y)) / m_iTextureHeight;
kUVRect.Bottom =(1 + ((1 + m_iCellHeight) * kPosition.y) + m_iCellHeight) / m_iTextureHeight;
return kUVRect;
}
Rest you need:
class Rect
{
public:
float Left;
float Right;
float Top;
float Bottom;
};
//Position of single cell in animation texture
class CellID
{
public:
unsigned long x;
unsigned long y;
};
My operating system is Windows 7 Ultimate. I'm using VS c++ 2010
If you would like to see entire solution there's link: http://speedy.sh/CmBRb/ConWinLib.rar
(It's a bit different than that because I wanted to make code as short as I could)
Thank you for any help!
EDIT
Answering to your questions:
#tbridge The Device should be good because I created few small programs before and they were working prefectly. But anyway there's the code:
//...
g_pkD3D = Direct3DCreate9(D3D_SDK_VERSION);
D3DPRESENT_PARAMETERS kPresentParams;
unsigned long iDeviceType = D3DDEVTYPE_REF; //I have already checked D3DDEVTYPE_HAL and it doesn't work either
ZeroMemory(&kPresentParams, sizeof(D3DPRESENT_PARAMETERS));
kPresentParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
D3DDISPLAYMODE kCurrentMode;
if(FAILED(g_pkD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &kCurrentMode)))
return ErrorGetAdapterDisplayMode;
kPresentParams.Windowed = true;
kPresentParams.BackBufferCount = 1;
kPresentParams.BackBufferFormat = kCurrentMode.Format;
if(FAILED(g_pkD3D->CreateDevice(D3DADAPTER_DEFAULT, (D3DDEVTYPE)iDeviceType, hWindow,
D3DCREATE_SOFTWARE_VERTEXPROCESSING, &kPresentParams, &g_pkD3DDevice)))
return ErrorCreateDevice;
g_pkD3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
g_pkD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
g_pkD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
g_pkD3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
g_pkD3DDevice->SetRenderState(D3DRSDESTBLEND, D3DBLEND_INVSRCALPHA);
g_pkD3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
g_pkD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
c