Sign in to follow this  

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

This topic is 2344 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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:

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

// Forward Declarations
class CDeferredRenderer;

class CGBuffer
{
public:
CGBuffer(void);
~CGBuffer(void);

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();

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

void CreateGBufferTextures();
void CreateGTexture( DXGI_FORMAT Format, ID3D11Texture2D* & Texture, ID3D11RenderTargetView* & RTView, ID3D11ShaderResourceView* & ResView );
};[/source]


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

CGBuffer::CGBuffer(void)
{
}

CGBuffer::~CGBuffer(void)
{
}

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

CreateGBufferTextures();
}

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.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
TextureDesc.CPUAccessFlags = 0;
TextureDesc.MiscFlags = 0;

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

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

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

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

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

void CGBuffer::Release()
{
GDiffuse->Release();
GNormal->Release();
GDepth->Release();
GLight->Release();

RTDiffuse->Release();
RTNormal->Release();
RTDepth->Release();
RTLight->Release();

GDiffuseView->Release();
GNormalView->Release();
GDepthView->Release();
GLightView->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] =
{
RTDiffuse,
RTNormal,
RTDepth
};
Context->OMSetRenderTargets(3, RenderTargetViews, DepthBufferView);
}[/source]


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?
[source]
class CDeferredRenderer
{
private:
CGBuffer *GBuffer;
....
};
void CDeferredRenderer::Init( CEngine * Engine, HWND hWnd )
{
...
GBuffer = new CGBuffer();
GBuffer->Init(this);
...
}
[/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]

Cheers,
Hyu

Share this post


Link to post
Share on other sites
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
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
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.

Cheers,
Hyu

Share this post


Link to post
Share on other sites

This topic is 2344 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

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

Create an account

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

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628724
    • Total Posts
      2984404
  • Similar Content

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

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

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


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