Sign in to follow this  

DX11 Questions about good coding practices for DirectX (C++)

Recommended Posts

Hyunkel    401
I've been using SlimDX (DX11) for quite some time now and I am fluent in C# and feel quite comfortable coding for DX11.
However, I figured that my lack of C++ skills is unacceptable, so I set out to learn C++.

So far, everything seems quite straightforward and obvious, though I obviously had some difficulties in the beginning.
To test and further develop my C++ skills, I decided to port my current engine, which I've written in C#/SlimDX to C++.
I'm not really experiencing any trouble with porting and solving problems...

... however I'm quite at a loss as to how to produce "good / clean code".

Online reading materials do a great job at explaining programming logic and how to solve problems, but they seem to give no indication on what would be a good or clean way to do so.
Due to this, I feel rather insecure about my current way of coding C++.

Here's a random class as an example on how I'm currently approaching things:

[source]#pragma once
#include "stdafx.h"

// Forward Declarations
class CDeferredRenderer;

class CGBuffer

ID3D11Texture2D *GDiffuse;
ID3D11Texture2D *GNormal;
ID3D11Texture2D *GDepth;
ID3D11Texture2D *GLight;
ID3D11RenderTargetView *RTDiffuse;
ID3D11RenderTargetView *RTNormal;
ID3D11RenderTargetView *RTDepth;
ID3D11RenderTargetView *RTLight;
ID3D11ShaderResourceView *GDiffuseView;
ID3D11ShaderResourceView *GNormalView;
ID3D11ShaderResourceView *GDepthView;
ID3D11ShaderResourceView *GLightView;

void Init(CDeferredRenderer * Renderer);
void Clear();
void BeginGeometryStage(ID3D11DepthStencilView *DepthBufferView);
void Release();

CDeferredRenderer *Renderer;
ID3D11Device *Device;
ID3D11DeviceContext *Context;

void CreateGBufferTextures();
void CreateGTexture( DXGI_FORMAT Format, ID3D11Texture2D* & Texture, ID3D11RenderTargetView* & RTView, ID3D11ShaderResourceView* & ResView );

[source]#include "StdAfx.h"
#include "GBuffer.h"
#include "DeferredRenderer.h"
#include "Engine.h"
#include "Log.h"
#include "StringParser.h"



void CGBuffer::Init( CDeferredRenderer * Renderer )
this->Renderer = Renderer;
this->Device = Renderer->Device;
this->Context = Renderer->Context;


void CGBuffer::CreateGBufferTextures()
CreateGTexture(DXGI_FORMAT_R8G8B8A8_UNORM, GDiffuse, RTDiffuse, GDiffuseView);
CreateGTexture(DXGI_FORMAT_R16G16_UNORM, GNormal, RTNormal, GNormalView);
CreateGTexture(DXGI_FORMAT_R32_FLOAT, GDepth, RTDepth, GDepthView);
CreateGTexture(DXGI_FORMAT_R16G16B16A16_FLOAT, GLight, RTLight, GLightView);

void CGBuffer::CreateGTexture( DXGI_FORMAT Format, ID3D11Texture2D* & Texture, ID3D11RenderTargetView* & RTView, ID3D11ShaderResourceView* & ResView )
// Create Texture
D3D11_TEXTURE2D_DESC TextureDesc;
ZeroMemory(&TextureDesc, sizeof(D3D11_TEXTURE2D_DESC));

TextureDesc.Width = SCREEN_WIDTH;
TextureDesc.Height = SCREEN_HEIGHT;
TextureDesc.MipLevels = 1;
TextureDesc.ArraySize = 1;
TextureDesc.Format = Format;
TextureDesc.SampleDesc.Count = 1;
TextureDesc.SampleDesc.Quality = 0;
TextureDesc.Usage = D3D11_USAGE_DEFAULT;
TextureDesc.CPUAccessFlags = 0;
TextureDesc.MiscFlags = 0;

HRESULT hr = Device->CreateTexture2D(&TextureDesc, NULL, &Texture);

// Create RenderView
ZeroMemory(&Desc, sizeof(D3D11_RENDER_TARGET_VIEW_DESC));

Desc.Format = Format;
Desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;

hr = Device->CreateRenderTargetView(Texture, &Desc, &RTView);

// Create Shader Resource View
hr = Device->CreateShaderResourceView(Texture, NULL, &ResView);

void CGBuffer::Release()



GDiffuse = NULL;
GNormal = NULL;
GDepth = NULL;
GLight = NULL;

RTDiffuse = NULL;
RTNormal = NULL;
RTDepth = NULL;
RTLight = NULL;

GDiffuseView = NULL;
GNormalView = NULL;
GDepthView = NULL;
GLightView = NULL;

void CGBuffer::Clear()
Context->ClearRenderTargetView(RTDiffuse, D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f));
Context->ClearRenderTargetView(RTNormal, D3DXCOLOR(0.5f, 0.5f, 0.0f, 0.0f));
Context->ClearRenderTargetView(RTDepth, D3DXCOLOR(1.0f, 0.0f, 0.0f, 0.0f));
Context->ClearRenderTargetView(RTLight, D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f));

void CGBuffer::BeginGeometryStage(ID3D11DepthStencilView *DepthBufferView)
ID3D11RenderTargetView* RenderTargetViews[3] =
Context->OMSetRenderTargets(3, RenderTargetViews, DepthBufferView);

This works fine, but there's a lot of questions popping up in my head:
[list][*]I only include stdafx.h (containing rarely changing libs such as DX libs) in my header files. I then add forward declarations for all other classes used in this one.
In my .cpp I include all header files of other classes needed.
It seems like I cannot run into problems this way... is this the correct approach for managing classes in c++?[*]I keep only pointers to all DX specific stuff (Textures, Rendertargetviews etc) which I can easily pass around.
I do the same thing with my own classes (My Renderer Class keeps only a Pointer to my GBuffer class)
Is this okay to do?
Or should I rather define things not as pointers, and then write get methods to pass references to member variables to other classes?
class CDeferredRenderer
CGBuffer *GBuffer;
void CDeferredRenderer::Init( CEngine * Engine, HWND hWnd )
GBuffer = new CGBuffer();
[/source][*]This also means I have to do things like this (although rarely):
[source]void CGBuffer::CreateGTexture( DXGI_FORMAT Format, ID3D11Texture2D* & Texture, ID3D11RenderTargetView* & RTView, ID3D11ShaderResourceView* & ResView )[/source]
Is this okay?[*]Should I make all members private and write Getters for them?
In C# I'm used to do things like:
[source]public CGBuffer GBuffer { get; private set; }[/source]

I obviously can't reproduce this in C++ without writing a Get method for each variable I want to have read-only access to.
Should I really do this, or is it better to focus on functionality rather than wrapping everything with accessor methods?[*]Should I prefer using references over pointers if I'm in a situation where I can use both to achieve the same thing?
I noticed the DirectX11 api doesn't make much use of references. For example:
[source]D3DXMatrixIdentity(D3DXMATRIX *pOut);[/source]
instead of
[source]D3DXMatrixIdentity(D3DXMATRIX & Out);[/source][*]I've seen some code where all member variables are preceded with "m" and pointers with "p" resulting in code like:
[source]ID3D11Texture2D* mpGDiffuse;[/source]
Is this considered a good practice?[/list]


Share this post

Link to post
Share on other sites
smasherprog    568
In general, it is best to use references if you are passing anything because it allows the compiler to do its job and optimize the code better because a reference cannot change, but a pointer can. Getters and Setters I do not use much because its a pain to write out all that code, when I can simply access the variable directly. For simplicity, I usually directly access the member. If I can type the function GetTexture(), I sure as well can type .Texture At least, thats how I look at it. Getters and Setters in my mind should be used when you want to ensure that other things happen when a variable is set. For example, if you set a texture, maybe you want to delete the old one if there is one, and then replace it with the new one. In that case, you need a setter function. But, sometimes you dont need to do any work, nor will you ever need to. In that case, I just go straight to the variable. Same concept with getters. If you think you might need to modify an internal state for each Get call, then create a function. If you are sure you wont need to do any internal work, save yourself some work and access the variable straight.

To your second question about headers and forward declarations, your method is correct. Put your forward declarations in the header, and include the necessary header in the cpp file.

Share this post

Link to post
Share on other sites
MJP    19756
1. Yes, you should generally prefer to handle includes this way whenever possible. Putting includes in header files can cause longer recompilation times when you change an included header file.

2. Generally you only want to use pointers when you have to. In your example of the CDeferredRenderer containing a CGBuffer, there's really no reason to make it a pointer and then dynamically allocate an instance of CGBuffer since you're always going to have one. Instead the C++ way of doing it is to just declare the CGBuffer as a regular member. For passing something to a function you should almost always pass as a reference. If necessary that function/class can convert that reference to a pointer so that it can hold onto it.

3. This is more of an OOP thing and not really C++ specific. If you're used to using properties, you can just stick with writing getters and setters.

4. Yes, if you can use a reference you really probably should. Using references can save you from the many pitfalls of pointers. The reason the DirectX API uses pointers everywhere is because it maintains C compatibility, and C doesn't have references.

5. This also isn't really C++-related, some people do the same in C#. It comes from Microsoft, who used this notation frequently for the Win32 API and MFC library. Some people still like it, some hate it...I would say it's totally your call.

Share this post

Link to post
Share on other sites
Hyunkel    401
Thank you both for your suggestions and explanations, I greatly appreciate it!
This really helps, I was feeling very insecure about these things, but now I have a good idea on how to do things better.


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By lonewolff
      Hi Guys,
      I am presently trying to render a video frame to a quad in DirectX 11 using Microsoft Media Foundations. But I am having a problem with 'TransferVideoFrame'.
      m_spMediaEngine->TransferVideoFrame(texture, rect, rcTarget, &m_bkgColor); The call keeps returning 'invalid parameter'.
      Some googling revealed this -
      Which explains that there is (was??) a bug with the NVidia drivers back in 2013. Other searches say this bug was fixed.
      The very odd thing is, if I run the application through Visual Studio Graphical debugger the video renders perfectly to the quad with no errors, so this would suggest that my code is sound.
      I can't do as the link suggests above and try to create the device as 9_x, as this is an extension that I am creating for GameMaker 2 and I don't have access to renderer creation (only the device handle - which is fine most of the time).
      I am presently downloading VS 2017 to see if it behaves better with more recent SDK's (as I am currently using VS 2015).
      Thanks in advance
    • By AlexWIN32
      A have an issue with my point light shadows realisation.

      First of all, the pixel shader path:
      //.... float3 toLight = - input.posW; float3 fromLight = -toLight; //... float depthL = abs(fromLight.x); if(depthL < abs(fromLight.y)) depthL = abs(fromLight.y); if(depthL < abs(fromLight.z)) depthL = abs(fromLight.z); float4 pH = mul(float4(0.0f, 0.0f, depthL, 1.0f), lightProj); pH /= pH.w; isVisible = lightDepthTex.SampleCmpLevelZero(lightDepthSampler, normalize(fromLight), pH.z).x;

      lightProj matrix creation
      Matrix4x4 projMat = Matrix4x4::PerspectiveFovLH(0.5f * Pi, 0.01f, 1000.0f, 1.0f);  
      thats how i create Depth cube texture
      viewport->TopLeftX = 0.0f; viewport->TopLeftY = 0.0f; viewport->Width = static_cast<float>(1024); viewport->Height = static_cast<float>(1024); viewport->MinDepth = 0.0f; viewport->MaxDepth = 1.0f; D3D11_TEXTURE2D_DESC textureDesc; textureDesc.Width = 1024; textureDesc.Height = 1024; textureDesc.MipLevels = 1; textureDesc.ArraySize = 6; textureDesc.Format = DXGI_FORMAT_R24G8_TYPELESS; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE; ID3D11Texture2D* texturePtr; HR(DeviceKeeper::GetDevice()->CreateTexture2D(&textureDesc, NULL, &texturePtr)); for(int i = 0; i < 6; ++i){ D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; dsvDesc.Flags = 0; dsvDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY; dsvDesc.Texture2DArray = D3D11_TEX2D_ARRAY_DSV{0, i, 1}; ID3D11DepthStencilView *outDsv; HR(DeviceKeeper::GetDevice()->CreateDepthStencilView(texturePtr, &dsvDesc, &outDsv)); edgeDsv = outDsv; } D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; srvDesc.TextureCube = D3D11_TEXCUBE_SRV{0, 1}; ID3D11ShaderResourceView *outSRV; HR(DeviceKeeper::GetDevice()->CreateShaderResourceView(texturePtr, &srvDesc, &outSRV));  
      then i create six target oriented cameras and finally draw scene to cube depth according to each camera
      Cameras creation code:  
      std::vector<Vector3> camDirs = { { 1.0f, 0.0f, 0.0f}, {-1.0f, 0.0f, 0.0f}, { 0.0f, 1.0f, 0.0f}, { 0.0f, -1.0f, 0.0f}, { 0.0f, 0.0f, 1.0f}, { 0.0f, 0.0f, -1.0f}, }; std::vector<Vector3> camUps = { {0.0f, 1.0f, 0.0f}, // +X {0.0f, 1.0f, 0.0f}, // -X {0.0f, 0.0f, -1.0f}, // +Y {0.0f, 0.0f, 1.0f}, // -Y {0.0f, 1.0f, 0.0f}, // +Z {0.0f, 1.0f, 0.0f} // -Z }; for(size_t b = 0; b < camDirs.size(); b++){ edgesCameras.SetPos(pl.GetPos()); edgesCameras.SetTarget(pl.GetPos() + camDirs); edgesCameras.SetUp(camUps); edgesCameras.SetProjMatrix(projMat); }  
      I will be very gratefull for any help!
      P.s sorry for my poor English)
    • By isu diss
      HRESULT FBXLoader::Open(HWND hWnd, char* Filename) { HRESULT hr = S_OK; if (FBXM) { FBXIOS = FbxIOSettings::Create(FBXM, IOSROOT); FBXM->SetIOSettings(FBXIOS); FBXI = FbxImporter::Create(FBXM, ""); if (!(FBXI->Initialize(Filename, -1, FBXIOS))) MessageBox(hWnd, (wchar_t*)FBXI->GetStatus().GetErrorString(), TEXT("ALM"), MB_OK); FBXS = FbxScene::Create(FBXM, "MCS"); if (!FBXS) MessageBox(hWnd, TEXT("Failed to create the scene"), TEXT("ALM"), MB_OK); if (!(FBXI->Import(FBXS))) MessageBox(hWnd, TEXT("Failed to import fbx file content into the scene"), TEXT("ALM"), MB_OK); if (FBXI) FBXI->Destroy(); FbxNode* MainNode = FBXS->GetRootNode(); int NumKids = MainNode->GetChildCount(); FbxNode* ChildNode = NULL; for (int i=0; i<NumKids; i++) { ChildNode = MainNode->GetChild(i); FbxNodeAttribute* NodeAttribute = ChildNode->GetNodeAttribute(); if (NodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh) { FbxMesh* Mesh = ChildNode->GetMesh(); NumVertices = Mesh->GetControlPointsCount();//number of vertices MyV = new FBXVTX[NumVertices]; for (DWORD j = 0; j < NumVertices; j++) { FbxVector4 Vertex = Mesh->GetControlPointAt(j);//Gets the control point at the specified index. MyV[j].Position = XMFLOAT3((float)Vertex.mData[0], (float)Vertex.mData[1], (float)Vertex.mData[2]); } NumIndices = Mesh->GetPolygonVertexCount();//number of indices; for cube 20 MyI = new DWORD[NumIndices]; MyI = (DWORD*)Mesh->GetPolygonVertices();//index array NumFaces = Mesh->GetPolygonCount(); MyF = new FBXFACEX[NumFaces]; for (int l=0;l<NumFaces;l++) { MyF[l].Vertices[0] = MyI[4*l]; MyF[l].Vertices[1] = MyI[4*l+1]; MyF[l].Vertices[2] = MyI[4*l+2]; MyF[l].Vertices[3] = MyI[4*l+3]; } UV = new XMFLOAT2[NumIndices]; for (int i = 0; i < Mesh->GetPolygonCount(); i++)//polygon(=mostly rectangle) count { FbxLayerElementArrayTemplate<FbxVector2>* uvVertices = NULL; Mesh->GetTextureUV(&uvVertices); for (int j = 0; j < Mesh->GetPolygonSize(i); j++)//retrieves number of vertices in a polygon { FbxVector2 uv = uvVertices->GetAt(Mesh->GetTextureUVIndex(i, j)); UV[4*i+j] = XMFLOAT2((float)uv.mData[0], (float)uv.mData[1]); } } } } } else MessageBox(hWnd, TEXT("Failed to create the FBX Manager"), TEXT("ALM"), MB_OK); return hr; } I've been trying to load fbx files(cube.fbx) into my programme. but I get this. Can someone pls help me?

    • By lonewolff
      Hi Guys,
      I am having a bit of a problem with a dynamic texture.
      It is creating without error and I am attempting to initialize the first pixel to white to make sure I am mapping correctly. But when I draw the texture to the quad it displays the whole quad white (instead of just one pixel).
      This is how I am creating, mapping, and setting the first pixel to white. But as mentioned, when I draw the quad, the entire quad is white.
      // Create dynamic texture D3D11_TEXTURE2D_DESC textureDesc = { 0 }; textureDesc.Width = 2048; textureDesc.Height = 2048; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; textureDesc.SampleDesc.Count = 1; textureDesc.Usage = D3D11_USAGE_DYNAMIC; textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; textureDesc.MiscFlags = 0; HRESULT result = d3dDevice->CreateTexture2D(&textureDesc, NULL, &textureDynamic); if (FAILED(result)) return -1; result = d3dDevice->CreateShaderResourceView(textureDynamic, 0, &textureRV); if (FAILED(result)) return -2; D3D11_MAPPED_SUBRESOURCE resource; if (FAILED(d3dContext->Map(textureDynamic, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource))) return -1; memset(resource.pData, 255, 4); d3dContext->Unmap(textureDynamic, 0);  
      Hopefully I have just made an oversight somewhere.
      Any assistance would be greatly appreciated
      (If I change the 255 value to 128 the quad then turns grey, so the mapping is definitely doing something. Just can't work out why it is colouring the whole quad and not the first pixel)
    • By KaiserJohan
      Just a really quick question - is there any overhead to using DrawIndexedInstanced even for geometry you just render once vs using DrawIndexed? Or is the details obfuscated by the graphics driver?
      I would assume no but you never know  
  • Popular Now