Sign in to follow this  
ranakor

DX11 C++ DX API, help me get it?

Recommended Posts

ranakor    439

Ok so i'm coming from a .net background (multiple years of professional development).

I'm checking out microsoft DX11 samples and i just don't get it, am i missing something obvious & there's actually beauty there i'm not seeing? Or is this actually just flat ugly hard code for no reason? Is it legacy or are you actually supposed to write & consume APIs this way?

(just to be clear, this is half rant, half question, i'd be more than happy to learn my rant is unfounded & have this transition from a rant to an answered question, also i'm not saying i'm having a hard time, just to be clear i understand the sample perfectly fine, i just find it painstakingly hard for no reason).

 

Shed some light on all this for me

1) Why the hell is this so damn long & hard? I expected getting a DX11 window up & running (and rendering) with nothing inside to be a 10liner or so, maybe 20 tops, but not 250 like in the sample!

2) Why the typedefs? Seems to be adding confusion for no reason especially on simple types, am i missing something or is this just useless? typedef float               FLOAT

3) Why no constructors? Objects are just declared and initialized element by element, meaning you remove 1 line you don't get a default, you don't even get an exception, you get a nice access violation!

4) Why all the if(failed(bla)) ? Why isn't code throwing?

5) Probably the same as 3 but, why no sensible default values for everything? Declaring any directX object seems to be a full time job & a 10 liner!

6) Why is everything taking a pointer? I get the point for large (or medium) objects but why for example does something like the feature level, which isn't a large object nor an array, and that you're likely to be using once (or hell, maybe twice!) in your whole application get passed by pointer? I'm new at C++ but unless i get it wrong it means you must create a (local or global) variable, assign a value to it, and pass a pointer to it, if it was by reference you could just pass in D3D_FEATURE_LEVEL_11_0 for example

7) Typedef question again, it's confusing enough for float => FLOAT, but hell LPVOID*, i can't believe people starting with C++ make it through this!

8) __uuidof, so you even need custom keywords to get a simple directX sample app going on???

 

I'm not trying to bash C++ here, the only things i can't bare in it are header files and compilation speed, but i just don't get that API design, is it flaws in the API or in the sample? Or am i just getting it wrong? Because if this is the right way to do it this sounds just horrible to me, 250 lines to do nothing, 3X that much for a rotating cube (out of which only 60 lines are rendering, and about 300 setting up the device . . . ). I just don't get it! Hell SharpDX didn't feel that way at all.

 

I'm waiting, please enlighten me!

Share this post


Link to post
Share on other sites
jrh2365    657

Allow me to pick off part of #6:

 

D3D11CreateDeviceAndSwapChain has two parameters that accept pointers to D3D_FEATURE_LEVEL. The first one is a pointer because it is actually looking for an array of D3D_FEATURE_LEVEL (and the parameter following that one is the number of elements in the array). The second one is a pointer because it is an output parameter to where the feature level that was actually selected can be stored.

 

http://msdn.microsoft.com/en-us/library/windows/desktop/ff476083(v=vs.85).aspx

 

[EDIT]

Also, I expect that a lot of the reasons for the API being structured how it is are due to http://en.wikipedia.org/wiki/Component_Object_Model

Edited by jrh2365

Share this post


Link to post
Share on other sites
NumberXaero    2624

1) Short version, modern languages and frameworks tend to do a lot of the work for you. This is the raw api.

2) typedef float FLOAT, might become typedef double FLOAT in the future, dont need to change as much later you can redefine FLOAT.

3) Windows has a long history with C, it tends to be the main focus when extending the windows apis, C has no constructors

4) see 3

5) see 3

6) see 3

7) see 3

8) see 3

Share this post


Link to post
Share on other sites
AvengerDr    751

That's why I keep my distance from C++! Even in C# you need to write a lot of code just to set up a device. It is certainly nicer to look at, less * and & :D But once you begin writing your engine you can abstract away all that. In my own engine everything boils down to a call to DeviceManager.Initialize where I pass my own settings structure... and that's that.

Share this post


Link to post
Share on other sites
Jason Z    6434

As the others have already mentioned, you are comparing two different things.  C++ has direct access to the D3D API, and hence has to do the heavy lifting to get anything going.  But SharpDX is actually just a library that sits between you and the API to make things easier.  Most people don't start from scratch in C++ either - for example, in the Hieroglyph 3 application framework, you just inherit from a class and your window setup, device setup, and all the other goodies are done without any additional code.

Share this post


Link to post
Share on other sites
SiCrane    11839

One thing not a lot of people realize is that most of the Windows API samples are written so that non-C and C++ programmers will understand them. For instance, when initializing structs the API samples will use ZeroMemory() despite the fact that = {} will do the same thing. However, non-C or C++ programmers won't necessarily understand that, so the explicit ZeroMemory() call is used instead.

Share this post


Link to post
Share on other sites
ranakor    439

Ok so as i expected most of it is to be blamed on legacy or COM, actually makes me quite happy to hear that.

 

Is there any library on the C++ side that does the same as SharpDX for .net? (keep the same low level API access, but wrap it in namespaced classes with default constructors etc, something that would feel more "modern C++ish" without being an engine but that would be a good base for starting one without doing my own wrappers on everything?)

Share this post


Link to post
Share on other sites
ongamex92    3255
4) Why all the if(failed(bla)) ? Why isn't code throwing? 

 

 NEVER use exceptions in C++! I love HRESULT error codes
 

6) Why is everything taking a pointer? I get the point for large (or medium) objects but why for example does something like the feature level, which isn't a large object nor an array, and that you're likely to be using once (or hell, maybe twice!) in your whole application get passed by pointer? I'm new at C++ but unless i get it wrong it means you must create a (local or global) variable, assign a value to it, and pass a pointer to it, if it was by reference you could just pass in D3D_FEATURE_LEVEL_11_0 for example

 

 Use CComPtr(atlbase.h) if you dont like pointers...

 

LPVOID

 

well.... i really dont care about PVOID LPVOID FLOAT ect...


D3D is designed for performance and user-control.. If you dont like that then you can use something like irrlicht/ogre/panda/whatever

Share this post


Link to post
Share on other sites
ranakor    439

 

4) Why all the if(failed(bla)) ? Why isn't code throwing? 

 

 NEVER use exceptions in C++! I love HRESULT error codes
 

6) Why is everything taking a pointer? I get the point for large (or medium) objects but why for example does something like the feature level, which isn't a large object nor an array, and that you're likely to be using once (or hell, maybe twice!) in your whole application get passed by pointer? I'm new at C++ but unless i get it wrong it means you must create a (local or global) variable, assign a value to it, and pass a pointer to it, if it was by reference you could just pass in D3D_FEATURE_LEVEL_11_0 for example

 

 Use CComPtr(atlbase.h) if you dont like pointers...

 

LPVOID

 

well.... i really dont care about PVOID LPVOID FLOAT ect...


D3D is designed for performance and user-control.. If you dont like that then you can use something like irrlicht/ogre/panda/whatever

 

None of this relates to performance at all, unless you consider "setting up directx" a performance critical part of any application where it's important to saveup nanoseconds in object instantiation and saving 4 bytes copies here & there? Performance is no reason here (i could get it if it was in per frame actions, but just not here), nor does it relate to user control at all. Anyway i already had my answers earlier on this thread, it's just com limitations & legacy code.

 

So now just looking for a thin wrapper around it, NOT an engine, something like a directX for actual C++ and not com/C.

Anyone could recommand such a thing? Something very thin where i could still refer to DX documentation, but just use it in a more "modern C++" way, C++11 is fine (within visual studio 2013's limitations)

Share this post


Link to post
Share on other sites
Matt-D    1574

So now just looking for a thin wrapper around it, NOT an engine, something like a directX for actual C++ and not com/C.

Anyone could recommand such a thing? Something very thin where i could still refer to DX documentation, but just use it in a more "modern C++" way, C++11 is fine (within visual studio 2013's limitations)

 

 

Take a look at "A Modern C++ Library for DirectX Programming" by Kenny Kerr:

http://msdn.microsoft.com/en-us/magazine/dn201741.aspx

http://dx.codeplex.com/

 

Seems to be exactly what you're describing:

I didn’t want to produce yet another heavy wrapper around DirectX. Instead, I decided to leverage C++11 to produce a simpler API for DirectX without imposing any space and time overheard to the core DirectX API.

 

If you'd like to have something on a yet higher level, check out SFML (Simple and Fast Multimedia Library):

http://www.sfml-dev.org/

Edited by Matt-D

Share this post


Link to post
Share on other sites
ATEFred    1700


None of this relates to performance at all

 

Exceptions have a noticeable performance impact, which is one of the reasons many game projects at least do not use them. From that perspective it makes sense from an API point of view to not rely on them (in addition to C legacy)

 

I don't know of any wrappers like that you are describing, but you could take just the API abstraction layer of any openly available engine and start with that instead of interfacing directly with d3d if you really wanted to. It would be better to use it natively if you want to learn how it works though I think.
 

Share this post


Link to post
Share on other sites
uglybdavis    1065


None of this relates to performance at all, unless you consider "setting up directx" a performance critical part of any application where it's important to saveup nanoseconds in object instantiation and saving 4 bytes copies here & there? Performance is no reason here (i could get it if it was in per frame actions, but just not here), nor does it relate to user control at all. Anyway i already had my answers earlier on this thread, it's just com limitations & legacy code.

 

Setting up DirectX can be a "performance critical" part. Just depends whom you work for. 

Some places have STRICT requirements on startup times.

Last company i worked at our game window had to be up and displaying something in under three seconds or all hell broke loose.

Share this post


Link to post
Share on other sites
Jason Z    6434

Jason Z's (http://hieroglyph3.codeplex.com/) has really good wrappers!

 

Like he said, Hieroglyph 3 is a layered framework that can be used at a high level or at a lower level.  At the very least, you can take a look at it and see if it does what you want.  There are lots of sample applications, ranging from very simple (just clearing the window to a different color) all the way up to volume rendering, Kinect integration, and deferred/light pre-pass rendering.

 

If you want something very light, you can grab pieces of the framework and use them as you see fit - it is licensed under MIT, so it is quite liberal for you to use.

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 isu diss
       I'm trying to code Rayleigh part of Nishita's model (Display Method of the Sky Color Taking into Account Multiple Scattering). I get black screen no colors. Can anyone find the issue for me?
       
      #define InnerRadius 6320000 #define OutterRadius 6420000 #define PI 3.141592653 #define Isteps 20 #define Ksteps 10 static float3 RayleighCoeffs = float3(6.55e-6, 1.73e-5, 2.30e-5); RWTexture2D<float4> SkyColors : register (u0); cbuffer CSCONSTANTBUF : register( b0 ) { float fHeight; float3 vSunDir; } float Density(float Height) { return exp(-Height/8340); } float RaySphereIntersection(float3 RayOrigin, float3 RayDirection, float3 SphereOrigin, float Radius) { float t1, t0; float3 L = SphereOrigin - RayOrigin; float tCA = dot(L, RayDirection); if (tCA < 0) return -1; float lenL = length(L); float D2 = (lenL*lenL) - (tCA*tCA); float Radius2 = (Radius*Radius); if (D2<=Radius2) { float tHC = sqrt(Radius2 - D2); t0 = tCA-tHC; t1 = tCA+tHC; } else return -1; return t1; } float RayleighPhaseFunction(float cosTheta) { return ((3/(16*PI))*(1+cosTheta*cosTheta)); } float OpticalDepth(float3 StartPosition, float3 EndPosition) { float3 Direction = normalize(EndPosition - StartPosition); float RayLength = RaySphereIntersection(StartPosition, Direction, float3(0, 0, 0), OutterRadius); float SampleLength = RayLength / Isteps; float3 tmpPos = StartPosition + 0.5 * SampleLength * Direction; float tmp; for (int i=0; i<Isteps; i++) { tmp += Density(length(tmpPos)-InnerRadius); tmpPos += SampleLength * Direction; } return tmp*SampleLength; } static float fExposure = -2; float3 HDR( float3 LDR) { return 1.0f - exp( fExposure * LDR ); } [numthreads(32, 32, 1)] //disptach 8, 8, 1 it's 256 by 256 image void ComputeSky(uint3 DTID : SV_DispatchThreadID) { float X = ((2 * DTID.x) / 255) - 1; float Y = 1 - ((2 * DTID.y) / 255); float r = sqrt(((X*X)+(Y*Y))); float Theta = r * (PI); float Phi = atan2(Y, X); static float3 Eye = float3(0, 10, 0); float ViewOD = 0, SunOD = 0, tmpDensity = 0; float3 Attenuation = 0, tmp = 0, Irgb = 0; //if (r<=1) { float3 ViewDir = normalize(float3(sin(Theta)*cos(Phi), cos(Theta),sin(Theta)*sin(Phi) )); float ViewRayLength = RaySphereIntersection(Eye, ViewDir, float3(0, 0, 0), OutterRadius); float SampleLength = ViewRayLength / Ksteps; //vSunDir = normalize(vSunDir); float cosTheta = dot(normalize(vSunDir), ViewDir); float3 tmpPos = Eye + 0.5 * SampleLength * ViewDir; for(int k=0; k<Ksteps; k++) { float SunRayLength = RaySphereIntersection(tmpPos, vSunDir, float3(0, 0, 0), OutterRadius); float3 TopAtmosphere = tmpPos + SunRayLength*vSunDir; ViewOD = OpticalDepth(Eye, tmpPos); SunOD = OpticalDepth(tmpPos, TopAtmosphere); tmpDensity = Density(length(tmpPos)-InnerRadius); Attenuation = exp(-RayleighCoeffs*(ViewOD+SunOD)); tmp += tmpDensity*Attenuation; tmpPos += SampleLength * ViewDir; } Irgb = RayleighCoeffs*RayleighPhaseFunction(cosTheta)*tmp*SampleLength; SkyColors[DTID.xy] = float4(Irgb, 1); } }  
    • By Endurion
      I have a gaming framework with an renderer interface. Those support DX8, DX9 and latest, DX11. Both DX8 and DX9 use fixed function pipeline, while DX11 obviously uses shaders. I've got most of the parts working fine, as in I can switch renderers and notice almost no difference. The most advanced features are 2 directional lights with a single texture  
      My last problem is lighting; albeit there's documentation on the D3D lighting model I still can't get the behaviour right. My mistake shows most prominently in the dark side opposite the lights. I'm pretty sure the ambient calculation is off, but that one's supposed to be the most simple one and should be hard to get wrong.
      Interestingly I've been searching high and low, and have yet to find a resource that shows how to build a HLSL shader where diffuse, ambient and specular are used together with material properties. I've got various shaders for all the variations I'm supporting. I stepped through the shader with the graphics debugger, but the calculation seems to do what I want. I'm just not sure the formula is correct.
      This one should suffice though, it's doing two directional lights, texture modulated with vertex color and a normal. Maybe someone can spot one (or more mistakes). And yes, this is in the vertex shader and I'm aware lighting will be as "bad" as in fixed function; that's my goal currently.
      // A constant buffer that stores the three basic column-major matrices for composing geometry. cbuffer ModelViewProjectionConstantBuffer : register(b0) { matrix model; matrix view; matrix projection; matrix ortho2d; }; struct DirectionLight { float3 Direction; float PaddingL1; float4 Ambient; float4 Diffuse; float4 Specular; }; cbuffer LightsConstantBuffer : register( b1 ) { float4 Ambient; float3 EyePos; float PaddingLC1; DirectionLight Light[8]; }; struct Material { float4 MaterialEmissive; float4 MaterialAmbient; float4 MaterialDiffuse; float4 MaterialSpecular; float MaterialSpecularPower; float3 MaterialPadding; }; cbuffer MaterialConstantBuffer : register( b2 ) { Material _Material; }; // Per-vertex data used as input to the vertex shader. struct VertexShaderInput { float3 pos : POSITION; float3 normal : NORMAL; float4 color : COLOR0; float2 tex : TEXCOORD0; }; // Per-pixel color data passed through the pixel shader. struct PixelShaderInput { float4 pos : SV_POSITION; float2 tex : TEXCOORD0; float4 color : COLOR0; }; // Simple shader to do vertex processing on the GPU. PixelShaderInput main(VertexShaderInput input) { PixelShaderInput output; float4 pos = float4( input.pos, 1.0f ); // Transform the vertex position into projected space. pos = mul(pos, model); pos = mul(pos, view); pos = mul(pos, projection); output.pos = pos; // pass texture coords output.tex = input.tex; // Calculate the normal vector against the world matrix only. //set required lighting vectors for interpolation float3 normal = mul( input.normal, ( float3x3 )model ); normal = normalize( normal ); float4 ambientEffect = Ambient; float4 diffuseEffect = float4( 0, 0, 0, 0 ); float4 specularEffect = float4( 0, 0, 0, 0 ); for ( int i = 0; i < 2; ++i ) { // Invert the light direction for calculations. float3 lightDir = -Light[i].Direction; float lightFactor = max( dot( lightDir, input.normal ), 0 ); ambientEffect += Light[i].Ambient * _Material.MaterialAmbient; diffuseEffect += saturate( Light[i].Diffuse * dot( normal, lightDir ) );// * _Material.MaterialDiffuse; //specularEffect += Light[i].Specular * dot( normal, halfangletolight ) * _Material.MaterialSpecularPower; } specularEffect *= _Material.MaterialSpecular; //ambientEffect.w = 1.0; ambientEffect = normalize( ambientEffect ); /* Ambient effect: (L1.ambient + L2.ambient) * object ambient color Diffuse effect: (L1.diffuse * Dot(VertexNormal, Light1.Direction) + L2.diffuse * Dot(VertexNormal, Light2.Direction)) * object diffuse color Specular effect: (L1.specular * Dot(VertexNormal, HalfAngleToLight1) * Object specular reflection power + L2.specular * Dot(VertexNormal, HalfAngleToLight2) * Object specular reflection power ) * object specular color Resulting color = Ambient effect + diffuse effect + specular effect*/ float4 totalFactor = ambientEffect + diffuseEffect + specularEffect; totalFactor.w = 1.0; output.color = input.color * totalFactor; return output; }   Edit: This message editor is driving me nuts (Arrrr!) - I don't write code in Word.
    • By Mercesa
      Hey folks. So I'm having this problem in which if my camera is close to a surface, the SSAO pass suddenly spikes up to around taking 16 milliseconds.
      When still looking towards the same surface, but less close. The framerate resolves itself and becomes regular again.
      This happens with ANY surface of my model, I am a bit clueless in regards to what could cause this. Any ideas?
      In attached image: y axis is time in ms, x axis is current frame. The dips in SSAO milliseconds are when I moved away from the surface, the peaks happen when I am very close to the surface.

       
      Edit: So I've done some more in-depth profiling with Nvidia nsight. So these are the facts from my results
      Count of command buffers goes from 4 (far away from surface) to ~20(close to surface).
      The command buffer duration in % goes from around ~30% to ~99%
      Sometimes the CPU duration takes up to 0.03 to 0.016 milliseconds per frame while comparatively usually it takes around 0.002 milliseconds.
      I am using a vertex shader which generates my full-screen quad and afterwards I do my SSAO calculations in my pixel shader, could this be a GPU driver bug? I'm a bit lost myself. It seems there could be a CPU/GPU resource stall. But why would the amount of command buffers be variable depending on distance from a surface?
       
       
      Edit n2: Any resolution above 720p starts to have this issue, and I am fairly certain my SSAO is not that performance heavy it would crap itself at a bit higher resolutions.
       
    • By turanszkij
      In DirectX 11 we have a 24 bit integer depth + 8bit stencil format for depth-stencil resources ( DXGI_FORMAT_D24_UNORM_S8_UINT ). However, in an AMD GPU documentation for consoles I have seen they mentioned, that internally this format is implemented as a 64 bit resource with 32 bits for depth (but just truncated for 24 bits) and 32 bits for stencil (truncated to 8 bits). AMD recommends using a 32 bit floating point depth buffer instead with 8 bit stencil which is this format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT.
      Does anyone know why this is? What is the usual way of doing this, just follow the recommendation and use a 64 bit depthstencil? Are there performance considerations or is it just recommended to not waste memory? What about Nvidia and Intel, is using a 24 bit depthbuffer relevant on their hardware?
      Cheers!
       
    • By gsc
      Hi! I am trying to implement simple SSAO postprocess. The main source of my knowledge on this topic is that awesome tutorial.
      But unfortunately something doesn't work... And after a few long hours I need some help. Here is my hlsl shader:
      float3 randVec = _noise * 2.0f - 1.0f; // noise: vec: {[0;1], [0;1], 0} float3 tangent = normalize(randVec - normalVS * dot(randVec, normalVS)); float3 bitangent = cross(tangent, normalVS); float3x3 TBN = float3x3(tangent, bitangent, normalVS); float occlusion = 0.0; for (int i = 0; i < kernelSize; ++i) { float3 samplePos = samples[i].xyz; // samples: {[-1;1], [-1;1], [0;1]} samplePos = mul(samplePos, TBN); samplePos = positionVS.xyz + samplePos * ssaoRadius; float4 offset = float4(samplePos, 1.0f); offset = mul(offset, projectionMatrix); offset.xy /= offset.w; offset.y = -offset.y; offset.xy = offset.xy * 0.5f + 0.5f; float sampleDepth = tex_4.Sample(textureSampler, offset.xy).a; sampleDepth = vsPosFromDepth(sampleDepth, offset.xy).z; const float threshold = 0.025f; float rangeCheck = abs(positionVS.z - sampleDepth) < ssaoRadius ? 1.0 : 0.0; occlusion += (sampleDepth <= samplePos.z + threshold ? 1.0 : 0.0) * rangeCheck; } occlusion = saturate(1 - (occlusion / kernelSize)); And current result: http://imgur.com/UX2X1fc
      I will really appreciate for any advice!
  • Popular Now