• Advertisement
Sign in to follow this  

DX12 DirectX 12 Multi Threading / Low-latency presentation

This topic is 524 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

Hi,

 

Does anyone know if it is safe to call IDXGISwapChain3::Present() on one thread, while at the same time calling ID3D12CommandQueue::ExecuteCommandLists() on another thread?

I have an application that creates two windows, one for each monitor. I have two threads that render to these two windows simultaneously. Each thread has its own ID3D12Device, ID3D12CommandQueue, IDXGISwapChain3, everything... they are completely independent.

Yet the application hangs randomly. Below are the call stacks of the two threads when they hang:

ntdll.dll!NtWaitForAlertByThreadId()
ntdll.dll!RtlpWaitOnAddressWithTimeout()
ntdll.dll!RtlpWaitOnAddress()
ntdll.dll!RtlpWaitOnCriticalSection()
ntdll.dll!RtlpEnterCriticalSectionContended()
D3D12.dll!CCommandQueue<0>::ExecuteCommandLists(unsigned int,struct ID3D12CommandList * const *)
dxgi.dll!CD3D12Device::CloseAndSubmitCommandList(unsigned int,enum CD3D12Device::QueueType)
dxgi.dll!CD3D12Device::PresentExtended(struct DXGI_PRESENTSURFACE const *,struct IDXGIResource * const *,unsigned int,struct IDXGIResource *,void *,unsigned int,unsigned int,int *,unsigned int *)
dxgi.dll!CDXGISwapChain::FlipPresentToDWM(struct SPresentArgs const *,unsigned int,unsigned int,unsigned int &,unsigned int,struct tagRECT const *,struct DXGI_SCROLL_RECT const *,struct DXGI_INTERNAL_CONTENT_PROTECTION const &)
dxgi.dll!CDXGISwapChain::PresentImplCore(struct SPresentArgs const *,unsigned int,unsigned int,unsigned int,struct tagRECT const *,unsigned int,struct DXGI_SCROLL_RECT const *,struct IDXGIResource *,bool &,bool &,bool &)
dxgi.dll!CDXGISwapChain::Present(unsigned int,unsigned int)
MyApp.exe!gui::CDXProc::CJob::Present() Line 963    C++

ntdll.dll!NtWaitForAlertByThreadId()
ntdll.dll!RtlpWaitOnAddressWithTimeout()
ntdll.dll!RtlpWaitOnAddress()
ntdll.dll!RtlpWaitOnCriticalSection()
ntdll.dll!RtlpEnterCriticalSectionContended()
dxgi.dll!CDXGISwapChain::GetCurrentBackBufferIndex(void)
dxgi.dll!CDXGISwapChain::GetCurrentCommandQueue(struct _GUID const &,void * *)
D3D12.dll!CCommandQueue<0>::ExecuteCommandLists(unsigned int,struct ID3D12CommandList * const *)
MyApp.exe!gui::CDXProc::CJob::ExecuteCommandList(ID3D12CommandList * iCommandList) Line 1172    C++

As you can see, the one thread is stuck in the Present() call, while the other thread is stuck inside ExecuteCommandLists().

I can get around the problem by putting a critical section around all calls to Present() and ExecuteCommandLists(), but I do not understand why this is necessary. Any ideas?

 

Edit: Changed the thread title to reflect the direction things are going.
 

Share this post


Link to post
Share on other sites
Advertisement
The first argument to CreateSwapChain is your main commandQueue. I guess that Present makes use of this queue internally, which means that no other thread should be using that queue during a Present call.

Share this post


Link to post
Share on other sites

The first argument to CreateSwapChain is your main commandQueue. I guess that Present makes use of this queue internally, which means that no other thread should be using that queue during a Present call.

Is ID3D12CommandQueue not free threaded? I thought the general idea is that multiple threads can create multiple ID3D12GraphicsCommandLists in parallel, and submit them in parallel to a single ID3D12CommandQueue?

 

But anyway, that is not what I am doing. I created two separate command ID3D12CommandQueues. Or are they perhaps one and the same internally?

Share this post


Link to post
Share on other sites

Is ID3D12CommandQueue not free threaded? I thought the general idea is that multiple threads can create multiple ID3D12GraphicsCommandLists in parallel, and submit them in parallel to a single ID3D12CommandQueue?

You're right: "Any thread may submit a command list to any command queue at any time, and the runtime will automatically serialize submission of the command list in the command queue while preserving the submission order." -- that sounds like the queue has an internal mutex that's acquired for you...

Perhaps there's a bug and Present fails to acquire this mutex? Hopefully someone with deeper knowledge of D3D12 can shed light on this...

Share this post


Link to post
Share on other sites

That particular deadlock was discovered and fixed a while back, if I remember correctly. Make sure you're on the latest version of Windows 10.

I think this is something else - I am on Build 10586.494. Windows Update says: "Your device is up to date. Last checked: ?2016/?08/?09, ??00:35"

I narrowed the deadlock down to a ResourceBarrier I have that straddles VSync. I set a barrier from PRESENT to RENDER_TARGET directly *after* Present(), followed by a Signal()+SetEventOnCompletion()+WaitForSingleObject().

This is the only way I have been able to achieve "Direct Flip" latency. The usual method of waiting on a WAITABLE_OBJECT after Present() does not seem to work, because it does not matter if the window covers only a portion of the monitor or if it covers the entire monitor, I always get the same latency of about 34ms:
(The picture below is from an oscilloscope that I trigger when I start to render a new frame, and then measure how long it takes to see the change on the screen as picked up by a photo diode that I taped to the monitor.)
Tek_Temp1.png
If instead I remove the wait on the WAITABLE_OBJECT, and replace it with a wait on resource barrier, I get the expected behaviour of "Direct Flip" with latency going down to 18ms (a 16ms reduction) for the case where the window covers the entire screen:
Tek_Temp2.png
This worked, but is now causing the deadlock when I do the same thing on two screens simultaneously. I suppose I could also go back to using waitable objects, but then won't get the lower latency of "Direct Flip". Is there some other way of doing the timing?
 

Share this post


Link to post
Share on other sites

Well, the Anniversary update was just released as 14393, so I'd recommend giving that one a shot first to see what's going on.

 

You can also try out PresentMon as a software technique for measuring latency. It'll also tell you whether you're in independent flip or getting composed. You might just be using the waitable object incorrectly while trying to get low latency, but that is absolutely our recommended way of controlling your latency, even in D3D12. For example, are you waiting on the object before your first frame? If not, you'll end up with latency that's one frame higher than you'd want, even in independent flip mode.

Share this post


Link to post
Share on other sites

Well, the Anniversary update was just released as 14393, so I'd recommend giving that one a shot first to see what's going on.

 

You can also try out PresentMon as a software technique for measuring latency. It'll also tell you whether you're in independent flip or getting composed. You might just be using the waitable object incorrectly while trying to get low latency, but that is absolutely our recommended way of controlling your latency, even in D3D12. For example, are you waiting on the object before your first frame? If not, you'll end up with latency that's one frame higher than you'd want, even in independent flip mode.

 

According to PresentMon everything is fine, but in reality (when measuring the light coming out of the screen), all is not as it seems. I did the following four tests:
Test 1: Using a "waitable object" on a non-fullscreen window.
Test 2: Using a "waitable object" on a fullscreen window.
Test 3: Using a "wait on barrier" on a non-fullscreen window.
Test 4: Using a "wait on barrier" on a fullscreen window.

Below is the output from PresentMon: (I added a column on the far right with the actual latency as measured using an oscilloscope.)

      Runtime SyncInterval AllowsTearing PresentFlags PresentMode                Dropped TimeInSeconds MsBetweenPresents MsBetweenDisplayChange MsInPresentAPI MsUntilRenderComplete MsUntilDisplayed Measured Latency
      ------- ------------ ------------- ------------ -----------                ------- ------------- ----------------- ---------------------- -------------- --------------------- ---------------- ----------------
Test 1:
      DXGI    1            0             64           Composed: Flip             0       4.134419      16.581            16.756                 0.488          0.429                 32.617           35
      DXGI    1            0             64           Composed: Flip             0       4.151078      16.659            16.605                 0.506          0.5                   32.563           35
      DXGI    1            0             64           Composed: Flip             0       4.167767      16.689            16.673                 0.39           0.512                 32.547           35
Test 2:
      DXGI    1            0             64           Hardware: Independent Flip 0       4.396671      16.611            16.717                 0.466          0.426                 16.311           35
      DXGI    1            0             64           Hardware: Independent Flip 0       4.413443      16.772            16.648                 0.382          0.396                 16.187           35
      DXGI    1            0             64           Hardware: Independent Flip 0       4.430011      16.568            16.734                 0.397          0.41                  16.353           35
Test 3:
      DXGI    1            0             64           Composed: Flip             0       2.242991      16.301            16.689                 0.371          0.431                 32.319           35
      DXGI    1            0             64           Composed: Flip             0       2.259456      16.465            16.67                  0.376          0.347                 32.524           35
      DXGI    1            0             64           Composed: Flip             0       2.276224      16.768            16.694                 0.359          0.434                 32.45            35
Test 4:
      DXGI    1            0             64           Hardware: Independent Flip 0       3.005195      16.478            16.696                 0.43           0.447                 15.927           19
      DXGI    1            0             64           Hardware: Independent Flip 0       3.021999      16.804            16.679                 0.387          0.394                 15.802           19
      DXGI    1            0             64           Hardware: Independent Flip 0       3.038641      16.642            16.72                  0.383          0.391                 15.88            19

Note that in Test 2 (ie using a waitable object on a fullscreen window) there is a 16ms discrepancy between what PresentMon says the latency is and what is measured in hardware.

It might be that I am doing something wrong with the waitable object - I will keep looking... I will also try the Windows 10 upgrade.

Share this post


Link to post
Share on other sites

Well, the Anniversary update was just released as 14393, so I'd recommend giving that one a shot first to see what's going on.

 

You can also try out PresentMon as a software technique for measuring latency. It'll also tell you whether you're in independent flip or getting composed. You might just be using the waitable object incorrectly while trying to get low latency, but that is absolutely our recommended way of controlling your latency, even in D3D12. For example, are you waiting on the object before your first frame? If not, you'll end up with latency that's one frame higher than you'd want, even in independent flip mode.

Sorry, one more thing... I watched your "Presentation Modes" video about 101 times but still don't understand the difference between "Independent Flip" and "True Immediate Independent Flip". Can you perhaps point me to some additional information on the "True Immediate Independent Flip" mode, and under what conditions it becomes active?

 

Also you mentioned in the video that with a DXGI_SWAP_EFFECT_FLIP_DISCARD backbuffer DXGI will render things like the volume control directly on my backbuffer while staying in Independent Flip mode. I have not been able to reproduce this behaviour - as soon as the volume control comes up I can see that DXGI is adding in an extra frame of latency... or am I missing something?

Share this post


Link to post
Share on other sites

True immediate independent flip is engaged either by calling SetFullscreenState with TRUE (Win32 only, not recommended), or using the new DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING and DXGI_PRESENT_ALLOW_TEARING. When independent flip is entered and sync interval is 0, the flip will happen as soon as rendering is complete.

 

The FLIP_SEQUENTIAL and FLIP_DISCARD swap effects allow seamless transitions between independent flip and composition. It is also possible that on systems with hardware composition support (e.g. multiple hardware overlay planes) that things like the volume controls can be rendered without dropping back to software composition and adding back the latency.

 

The PresentMon data looks like what I'd expect. Are you sure that case 2 has data that looks like that at the same time as your monitor latency test? Note that it's possible that independent flip didn't properly engage 100% of the time, but if your results were consistent then it's probably not that.

Share this post


Link to post
Share on other sites

Are you sure that case 2 has data that looks like that at the same time as your monitor latency test? Note that it's possible that independent flip didn't properly engage 100% of the time, but if your results were consistent then it's probably not that.

 

Yes, I am sure. I repeated the tests multiple times, now also on two different computers.

 

In order to rule out the possibility that I am doing something wrong I thought I would start with a working sample, Intel's FlipModelD3D12 sample as documented here. But as I will show below, "Direct Flip" does not seem to work, not even with this unmodified sample.

 

Firstly, running in a window I get the expected best case of two frames of latency - one frame for rendering plus the one frame for compositing:

 

Untitled2.jpg

 

 

Next, going to fullscreen to enable "Direct Flip" (or "Independent Flip"), the results however remain the same - still two frames of latency:

 

Untitled1.jpg

 

 

This is the output of PresentMon during the window-to-fullscreen transition:

                                           Runtime SyncInterval AllowsTearing PresentFlags PresentMode                Dropped TimeInSeconds MsBetweenPresents MsBetweenDisplayChange MsInPresentAPI MsUntilRenderComplete MsUntilDisplayed
                                           ------- ------------ ------------- ------------ -----------                ------- ------------- ----------------- ---------------------- -------------- --------------------- ----------------
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Composed: Flip             0       3.472288      16.614            16.659                 0.195          0.74                  22.975
                   1008 0x000001E61C854480 DXGI    1            0             0            Hardware: Legacy Flip      0       3.495689      16.659            16.715                 0.228          0.449                 16.251
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Composed: Flip             0       3.488948      16.659            16.707                 0.218          0.808                 23.023
                   1008 0x000001E61C854480 DXGI    1            0             0            Hardware: Legacy Flip      0       3.51256       16.871            16.616                 0.184          0.445                 15.996
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Composed: Flip             0       3.505638      16.69             16.622                 0.238          0.645                 22.954
                   1008 0x000001E61C854480 DXGI    1            0             0            Hardware: Legacy Flip      0       3.529297      16.737            16.669                 0.166          0.475                 15.928
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Composed: Flip             0       3.522536      16.897            16.66                  0.207          0.575                 22.717
                   1008 0x000001E61C854480 DXGI    1            0             0            Hardware: Legacy Flip      0       3.546146      16.848            16.73                  0.14           0.117                 15.809
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Composed: Flip             0       3.53896       16.424            16.76                  0.196          0.787                 23.052
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Composed: Flip             1       3.555698      16.738            0                      0.241          1.015                 0
                   1008 0x000001E61C854480 DXGI    1            0             0            Hardware: Legacy Flip      0       3.562076      15.93             16.712                 0.119          0.12                  16.591
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Hardware: Independent Flip 0       3.572275      16.578            33.322                 0.213          8.253                 23.059
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Hardware: Independent Flip 0       3.590761      18.486            16.669                 0.204          6.514                 21.242
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Hardware: Independent Flip 0       3.607514      16.753            16.73                  0.213          6.378                 21.219
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Hardware: Independent Flip 0       3.624395      16.881            16.632                 0.261          6.284                 20.97
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Hardware: Independent Flip 0       3.640937      16.542            16.696                 0.213          6.308                 21.125
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Hardware: Independent Flip 0       3.657528      16.591            16.657                 0.206          6.488                 21.191
FlipModelD3D12.exe 6996 0x000001F27D6B42C0 DXGI    1            0             0            Hardware: Independent Flip 0       3.674217      16.689            16.698                 0.2            6.37                  21.2

So PresentMon says that in fullsceen we are in Independent Flip, but according to the FlipModelID3D12 sample we are still getting two frames of latency.

 

In order to resolve this discrepancy I added six lines of code to the FlipModelID3D12 sample program that allows me to measure the latency with an oscilloscope:

(Basically all I do is, for one in every eight frames, I set a RS232 port line high at the start of render, and low again at the end of render. I also set the background color to black in this frame so that I can pick it up on screen with a photo diode.)

 

Tek_Temp.png

 

So the latency measured is about 33ms (two frames), as predicted by the FlipModelID3D12 app, and NOT the 16ms (or one frame) as you would expect for Independent Flip mode.

 

Originally I did all these tests on my main PC which is:

  Windows 10 build 10586, multi monitor, Nvidia discrete GPU.

 

Thinking that there is something wrong with this computer I repeated everything on a:

  Windows 10 build 14393, single monitor, Intel integrated GPU.

 

But the results are exactly the same.

 

I don't really know what to try next - any help would be appreciated.

Share this post


Link to post
Share on other sites

PresentMon agrees with you for your tests with the Intel flip model sample app - it says 21ms of latency from the time Present() is called until it hits the screen, not 16ms. The reason for that in the sample is that it doesn't work properly :) notice the 6ms it takes to render, but only when in fullscreen. That's because the app is rendering too early to get just 1 frame of latency; I suspect there's a bug which causes it to drop a wait on the waitable object, accidentally causing it to run with latency of 2.

 

I'm interested in focusing on the discrepency between PresentMon and your hardware measurements. If PresentMon says you should be getting 16ms, then you legitimately should be - it's not a predictive tool based on inputs into the system, it measures events from the components responsible for getting contents on screen. When it says you've flipped, we've really requested the hardware to flip.

 

As something to try, just to see what happens, try increasing the buffer count to 3?

Share this post


Link to post
Share on other sites

As something to try, just to see what happens, try increasing the buffer count to 3?

 

When changing the buffers to 3 the diagram displayed by FlipModelID3D12 looks slightly different:

 

Untitled3.jpg

 

However, the latency is still two frames.

 

If FlipModelID3D12 is not working correctly now, it must have been working before because the image on Intel's web page looks like they had it running with one frame latency:

 

3_minimumlatency.png

 

 

I am going to see if I can move the timing pulse to wrap only the Present() call, to see how the hardware measurements compare with PresentMon.

Share this post


Link to post
Share on other sites

I changed FlipModelD3D12 adding a pulse around only the Present() call so that I can measure the latency from Present() to when the image is on the screen. I tested:
  1) FlipModelD3D12 running in a window with 2 buffers.
  2) FlipModelD3D12 running full screen with 2 buffers.
  3) FlipModelD3D12 running full screen with 3 buffers.

The results are:

                               PresentMon MsUntilDisplayed        Hardware measurement
  1) Windowed 2 buffers   :    26.3                               27.6
  2) Fullscreen 2 buffers :    22.9                               23.6
  3) Fullscreen 3 buffers :    26.3                               27.6

I think that looks pretty good - the hardware measurement is out by maybe one ms, but that is not unexpected considering the simple measuring technique.

So what do you think can be wrong with FlipModelD3D12 that makes fullscreen no better than windowed?

Is there perhaps another sample I can try that is known to be good?

Edited by Barnett

Share this post


Link to post
Share on other sites

I managed to get FlipModelID3D12 working very nicely with a solid 16.6ms one frame latency:

 

Untitled4.jpg

 

 

PresentMon reports about 9.9ms latency, but that is from Present()->screen, so it will obviously be a bit shorter than the "Start Of Render"->screen displayed by FlipModelID3D12:

FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.065275,16.737,16.655,0.061,2.298,9.809
FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.081854,16.579,16.662,0.054,2.374,9.892
FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.098540,16.685,16.660,0.051,2.384,9.866
FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.115118,16.579,16.660,0.052,2.463,9.948
FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.132057,16.938,16.667,0.077,2.322,9.676
FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.148549,16.493,16.658,0.057,2.468,9.842
FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.165347,16.798,16.665,0.067,2.391,9.709
FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.181797,16.450,16.656,0.053,2.515,9.916
FlipModelD3D12.exe,2772,0x000001E13F9D5800,DXGI,1,0,0,Hardware: Independent Flip,0,1.198429,16.632,16.662,0.051,2.582,9.945

My hardware measurements confirm these numbers as well.

 

To make it work I had to add an additional IDXGIOutput::WaitForVBlank() call directly after the wait on waitable object. I think there is a bug in Windows causing the waitable object to be kicked one frame too early when in Independent Flip mode. Perhaps they forgot to compensate for the lower latency when switching from composition to Independent Flip? That is all I can think.

 

Obviously you cannot always just call WaitForVBlank() to add the one frame delay because most of the time the waitable object works correctly. So you will have to wrap that call in some or other if statement. So the next problem now will be to come up with the logic for doing that reliably...

Share this post


Link to post
Share on other sites

Hm, that's unexpected. It's possible that we have a bug with independent flip causing the waitable object to be signaled when the frame is queued instead of released... If I find out anything more I'll update this thread.

Share this post


Link to post
Share on other sites

Hm, that's unexpected. It's possible that we have a bug with independent flip causing the waitable object to be signaled when the frame is queued instead of released... If I find out anything more I'll update this thread.

 

Thanks for all your help - greatly appreciated.

 

Can you perhaps shed some light on how presentation to secondary monitors are handled? How are they different from the main monitor? I cannot seem to get a secondary monitor to go into Independent Flip.

 

Rendering to Main Monitor:

  0x00000218C02CADC0,DXGI,1,0,0,Hardware: Independent Flip,0,3.555798,16.532,16.637,0.508,0.509,15.843

 

Same code rendering to Secondary Monitor:

  0x00000218C4C1FF10,DXGI,1,0,0,Composed: Flip,0,3.522093,15.864,16.663,0.222,0.377,49.643

 

 

In a previous post you explained "True Immediate Independent Flip", which I think I understand now. But what then is the difference between "Direct Flip" and "Independent Flip"?

Share this post


Link to post
Share on other sites

Yep, secondary monitors may not support independent flip yet. Additionally, PresentMon can't properly detect direct flip and classifies it as composed.

 

Direct flip occurs when the compositor detects that it doesn't need to compose because only one app is covering the screen - it just uses that app's contents when it would normally compose to one of its own surfaces.

 

Independent flip occurs when the compositor decides it no longer even needs to wake up, because that app will continue covering the screen until some other event happens. It tells the system to continue flipping independently; at that point, it can start to get even faster than the compositor's rate (immediate independent flip).

 

Edit: Clarifying, secondary monitor independent flip requires the Anniversary update, along with newer drivers, and isn't guaranteed to be supported even then.

Edited by Jesse Natalie

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By DiligentDev
      This article uses material originally posted on Diligent Graphics web site.
      Introduction
      Graphics APIs have come a long way from small set of basic commands allowing limited control of configurable stages of early 3D accelerators to very low-level programming interfaces exposing almost every aspect of the underlying graphics hardware. Next-generation APIs, Direct3D12 by Microsoft and Vulkan by Khronos are relatively new and have only started getting widespread adoption and support from hardware vendors, while Direct3D11 and OpenGL are still considered industry standard. New APIs can provide substantial performance and functional improvements, but may not be supported by older hardware. An application targeting wide range of platforms needs to support Direct3D11 and OpenGL. New APIs will not give any advantage when used with old paradigms. It is totally possible to add Direct3D12 support to an existing renderer by implementing Direct3D11 interface through Direct3D12, but this will give zero benefits. Instead, new approaches and rendering architectures that leverage flexibility provided by the next-generation APIs are expected to be developed.
      There are at least four APIs (Direct3D11, Direct3D12, OpenGL/GLES, Vulkan, plus Apple's Metal for iOS and osX platforms) that a cross-platform 3D application may need to support. Writing separate code paths for all APIs is clearly not an option for any real-world application and the need for a cross-platform graphics abstraction layer is evident. The following is the list of requirements that I believe such layer needs to satisfy:
      Lightweight abstractions: the API should be as close to the underlying native APIs as possible to allow an application leverage all available low-level functionality. In many cases this requirement is difficult to achieve because specific features exposed by different APIs may vary considerably. Low performance overhead: the abstraction layer needs to be efficient from performance point of view. If it introduces considerable amount of overhead, there is no point in using it. Convenience: the API needs to be convenient to use. It needs to assist developers in achieving their goals not limiting their control of the graphics hardware. Multithreading: ability to efficiently parallelize work is in the core of Direct3D12 and Vulkan and one of the main selling points of the new APIs. Support for multithreading in a cross-platform layer is a must. Extensibility: no matter how well the API is designed, it still introduces some level of abstraction. In some cases the most efficient way to implement certain functionality is to directly use native API. The abstraction layer needs to provide seamless interoperability with the underlying native APIs to provide a way for the app to add features that may be missing. Diligent Engine is designed to solve these problems. Its main goal is to take advantages of the next-generation APIs such as Direct3D12 and Vulkan, but at the same time provide support for older platforms via Direct3D11, OpenGL and OpenGLES. Diligent Engine exposes common C++ front-end for all supported platforms and provides interoperability with underlying native APIs. It also supports integration with Unity and is designed to be used as graphics subsystem in a standalone game engine, Unity native plugin or any other 3D application. Full source code is available for download at GitHub and is free to use.
      Overview
      Diligent Engine API takes some features from Direct3D11 and Direct3D12 as well as introduces new concepts to hide certain platform-specific details and make the system easy to use. It contains the following main components:
      Render device (IRenderDevice  interface) is responsible for creating all other objects (textures, buffers, shaders, pipeline states, etc.).
      Device context (IDeviceContext interface) is the main interface for recording rendering commands. Similar to Direct3D11, there are immediate context and deferred contexts (which in Direct3D11 implementation map directly to the corresponding context types). Immediate context combines command queue and command list recording functionality. It records commands and submits the command list for execution when it contains sufficient number of commands. Deferred contexts are designed to only record command lists that can be submitted for execution through the immediate context.
      An alternative way to design the API would be to expose command queue and command lists directly. This approach however does not map well to Direct3D11 and OpenGL. Besides, some functionality (such as dynamic descriptor allocation) can be much more efficiently implemented when it is known that a command list is recorded by a certain deferred context from some thread.
      The approach taken in the engine does not limit scalability as the application is expected to create one deferred context per thread, and internally every deferred context records a command list in lock-free fashion. At the same time this approach maps well to older APIs.
      In current implementation, only one immediate context that uses default graphics command queue is created. To support multiple GPUs or multiple command queue types (compute, copy, etc.), it is natural to have one immediate contexts per queue. Cross-context synchronization utilities will be necessary.
      Swap Chain (ISwapChain interface). Swap chain interface represents a chain of back buffers and is responsible for showing the final rendered image on the screen.
      Render device, device contexts and swap chain are created during the engine initialization.
      Resources (ITexture and IBuffer interfaces). There are two types of resources - textures and buffers. There are many different texture types (2D textures, 3D textures, texture array, cubmepas, etc.) that can all be represented by ITexture interface.
      Resources Views (ITextureView and IBufferView interfaces). While textures and buffers are mere data containers, texture views and buffer views describe how the data should be interpreted. For instance, a 2D texture can be used as a render target for rendering commands or as a shader resource.
      Pipeline State (IPipelineState interface). GPU pipeline contains many configurable stages (depth-stencil, rasterizer and blend states, different shader stage, etc.). Direct3D11 uses coarse-grain objects to set all stage parameters at once (for instance, a rasterizer object encompasses all rasterizer attributes), while OpenGL contains myriad functions to fine-grain control every individual attribute of every stage. Both methods do not map very well to modern graphics hardware that combines all states into one monolithic state under the hood. Direct3D12 directly exposes pipeline state object in the API, and Diligent Engine uses the same approach.
      Shader Resource Binding (IShaderResourceBinding interface). Shaders are programs that run on the GPU. Shaders may access various resources (textures and buffers), and setting correspondence between shader variables and actual resources is called resource binding. Resource binding implementation varies considerably between different API. Diligent Engine introduces a new object called shader resource binding that encompasses all resources needed by all shaders in a certain pipeline state.
      API Basics
      Creating Resources
      Device resources are created by the render device. The two main resource types are buffers, which represent linear memory, and textures, which use memory layouts optimized for fast filtering. Graphics APIs usually have a native object that represents linear buffer. Diligent Engine uses IBuffer interface as an abstraction for a native buffer. To create a buffer, one needs to populate BufferDesc structure and call IRenderDevice::CreateBuffer() method as in the following example:
      BufferDesc BuffDesc; BufferDesc.Name = "Uniform buffer"; BuffDesc.BindFlags = BIND_UNIFORM_BUFFER; BuffDesc.Usage = USAGE_DYNAMIC; BuffDesc.uiSizeInBytes = sizeof(ShaderConstants); BuffDesc.CPUAccessFlags = CPU_ACCESS_WRITE; m_pDevice->CreateBuffer( BuffDesc, BufferData(), &m_pConstantBuffer ); While there is usually just one buffer object, different APIs use very different approaches to represent textures. For instance, in Direct3D11, there are ID3D11Texture1D, ID3D11Texture2D, and ID3D11Texture3D objects. In OpenGL, there is individual object for every texture dimension (1D, 2D, 3D, Cube), which may be a texture array, which may also be multisampled (i.e. GL_TEXTURE_2D_MULTISAMPLE_ARRAY). As a result there are nine different GL texture types that Diligent Engine may create under the hood. In Direct3D12, there is only one resource interface. Diligent Engine hides all these details in ITexture interface. There is only one  IRenderDevice::CreateTexture() method that is capable of creating all texture types. Dimension, format, array size and all other parameters are specified by the members of the TextureDesc structure:
      TextureDesc TexDesc; TexDesc.Name = "My texture 2D"; TexDesc.Type = TEXTURE_TYPE_2D; TexDesc.Width = 1024; TexDesc.Height = 1024; TexDesc.Format = TEX_FORMAT_RGBA8_UNORM; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_SHADER_RESOURCE | BIND_RENDER_TARGET | BIND_UNORDERED_ACCESS; TexDesc.Name = "Sample 2D Texture"; m_pRenderDevice->CreateTexture( TexDesc, TextureData(), &m_pTestTex ); If native API supports multithreaded resource creation, textures and buffers can be created by multiple threads simultaneously.
      Interoperability with native API provides access to the native buffer/texture objects and also allows creating Diligent Engine objects from native handles. It allows applications seamlessly integrate native API-specific code with Diligent Engine.
      Next-generation APIs allow fine level-control over how resources are allocated. Diligent Engine does not currently expose this functionality, but it can be added by implementing IResourceAllocator interface that encapsulates specifics of resource allocation and providing this interface to CreateBuffer() or CreateTexture() methods. If null is provided, default allocator should be used.
      Initializing the Pipeline State
      As it was mentioned earlier, Diligent Engine follows next-gen APIs to configure the graphics/compute pipeline. One big Pipelines State Object (PSO) encompasses all required states (all shader stages, input layout description, depth stencil, rasterizer and blend state descriptions etc.). This approach maps directly to Direct3D12/Vulkan, but is also beneficial for older APIs as it eliminates pipeline misconfiguration errors. With many individual calls tweaking various GPU pipeline settings it is very easy to forget to set one of the states or assume the stage is already properly configured when in fact it is not. Using pipeline state object helps avoid these problems as all stages are configured at once.
      Creating Shaders
      While in earlier APIs shaders were bound separately, in the next-generation APIs as well as in Diligent Engine shaders are part of the pipeline state object. The biggest challenge when authoring shaders is that Direct3D and OpenGL/Vulkan use different shader languages (while Apple uses yet another language in their Metal API). Maintaining two versions of every shader is not an option for real applications and Diligent Engine implements shader source code converter that allows shaders authored in HLSL to be translated to GLSL. To create a shader, one needs to populate ShaderCreationAttribs structure. SourceLanguage member of this structure tells the system which language the shader is authored in:
      SHADER_SOURCE_LANGUAGE_DEFAULT - The shader source language matches the underlying graphics API: HLSL for Direct3D11/Direct3D12 mode, and GLSL for OpenGL and OpenGLES modes. SHADER_SOURCE_LANGUAGE_HLSL - The shader source is in HLSL. For OpenGL and OpenGLES modes, the source code will be converted to GLSL. SHADER_SOURCE_LANGUAGE_GLSL - The shader source is in GLSL. There is currently no GLSL to HLSL converter, so this value should only be used for OpenGL and OpenGLES modes. There are two ways to provide the shader source code. The first way is to use Source member. The second way is to provide a file path in FilePath member. Since the engine is entirely decoupled from the platform and the host file system is platform-dependent, the structure exposes pShaderSourceStreamFactory member that is intended to provide the engine access to the file system. If FilePath is provided, shader source factory must also be provided. If the shader source contains any #include directives, the source stream factory will also be used to load these files. The engine provides default implementation for every supported platform that should be sufficient in most cases. Custom implementation can be provided when needed.
      When sampling a texture in a shader, the texture sampler was traditionally specified as separate object that was bound to the pipeline at run time or set as part of the texture object itself. However, in most cases it is known beforehand what kind of sampler will be used in the shader. Next-generation APIs expose new type of sampler called static sampler that can be initialized directly in the pipeline state. Diligent Engine exposes this functionality: when creating a shader, textures can be assigned static samplers. If static sampler is assigned, it will always be used instead of the one initialized in the texture shader resource view. To initialize static samplers, prepare an array of StaticSamplerDesc structures and initialize StaticSamplers and NumStaticSamplers members. Static samplers are more efficient and it is highly recommended to use them whenever possible. On older APIs, static samplers are emulated via generic sampler objects.
      The following is an example of shader initialization:
      ShaderCreationAttribs Attrs; Attrs.Desc.Name = "MyPixelShader"; Attrs.FilePath = "MyShaderFile.fx"; Attrs.SearchDirectories = "shaders;shaders\\inc;"; Attrs.EntryPoint = "MyPixelShader"; Attrs.Desc.ShaderType = SHADER_TYPE_PIXEL; Attrs.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL; BasicShaderSourceStreamFactory BasicSSSFactory(Attrs.SearchDirectories); Attrs.pShaderSourceStreamFactory = &BasicSSSFactory; ShaderVariableDesc ShaderVars[] = {     {"g_StaticTexture", SHADER_VARIABLE_TYPE_STATIC},     {"g_MutableTexture", SHADER_VARIABLE_TYPE_MUTABLE},     {"g_DynamicTexture", SHADER_VARIABLE_TYPE_DYNAMIC} }; Attrs.Desc.VariableDesc = ShaderVars; Attrs.Desc.NumVariables = _countof(ShaderVars); Attrs.Desc.DefaultVariableType = SHADER_VARIABLE_TYPE_STATIC; StaticSamplerDesc StaticSampler; StaticSampler.Desc.MinFilter = FILTER_TYPE_LINEAR; StaticSampler.Desc.MagFilter = FILTER_TYPE_LINEAR; StaticSampler.Desc.MipFilter = FILTER_TYPE_LINEAR; StaticSampler.TextureName = "g_MutableTexture"; Attrs.Desc.NumStaticSamplers = 1; Attrs.Desc.StaticSamplers = &StaticSampler; ShaderMacroHelper Macros; Macros.AddShaderMacro("USE_SHADOWS", 1); Macros.AddShaderMacro("NUM_SHADOW_SAMPLES", 4); Macros.Finalize(); Attrs.Macros = Macros; RefCntAutoPtr<IShader> pShader; m_pDevice->CreateShader( Attrs, &pShader );
      Creating the Pipeline State Object
      After all required shaders are created, the rest of the fields of the PipelineStateDesc structure provide depth-stencil, rasterizer, and blend state descriptions, the number and format of render targets, input layout format, etc. For instance, rasterizer state can be described as follows:
      PipelineStateDesc PSODesc; RasterizerStateDesc &RasterizerDesc = PSODesc.GraphicsPipeline.RasterizerDesc; RasterizerDesc.FillMode = FILL_MODE_SOLID; RasterizerDesc.CullMode = CULL_MODE_NONE; RasterizerDesc.FrontCounterClockwise = True; RasterizerDesc.ScissorEnable = True; RasterizerDesc.AntialiasedLineEnable = False; Depth-stencil and blend states are defined in a similar fashion.
      Another important thing that pipeline state object encompasses is the input layout description that defines how inputs to the vertex shader, which is the very first shader stage, should be read from the memory. Input layout may define several vertex streams that contain values of different formats and sizes:
      // Define input layout InputLayoutDesc &Layout = PSODesc.GraphicsPipeline.InputLayout; LayoutElement TextLayoutElems[] = {     LayoutElement( 0, 0, 3, VT_FLOAT32, False ),     LayoutElement( 1, 0, 4, VT_UINT8, True ),     LayoutElement( 2, 0, 2, VT_FLOAT32, False ), }; Layout.LayoutElements = TextLayoutElems; Layout.NumElements = _countof( TextLayoutElems ); Finally, pipeline state defines primitive topology type. When all required members are initialized, a pipeline state object can be created by IRenderDevice::CreatePipelineState() method:
      // Define shader and primitive topology PSODesc.GraphicsPipeline.PrimitiveTopologyType = PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; PSODesc.GraphicsPipeline.pVS = pVertexShader; PSODesc.GraphicsPipeline.pPS = pPixelShader; PSODesc.Name = "My pipeline state"; m_pDev->CreatePipelineState(PSODesc, &m_pPSO); When PSO object is bound to the pipeline, the engine invokes all API-specific commands to set all states specified by the object. In case of Direct3D12 this maps directly to setting the D3D12 PSO object. In case of Direct3D11, this involves setting individual state objects (such as rasterizer and blend states), shaders, input layout etc. In case of OpenGL, this requires a number of fine-grain state tweaking calls. Diligent Engine keeps track of currently bound states and only calls functions to update these states that have actually changed.
      Binding Shader Resources
      Direct3D11 and OpenGL utilize fine-grain resource binding models, where an application binds individual buffers and textures to certain shader or program resource binding slots. Direct3D12 uses a very different approach, where resource descriptors are grouped into tables, and an application can bind all resources in the table at once by setting the table in the command list. Resource binding model in Diligent Engine is designed to leverage this new method. It introduces a new object called shader resource binding that encapsulates all resource bindings required for all shaders in a certain pipeline state. It also introduces the classification of shader variables based on the frequency of expected change that helps the engine group them into tables under the hood:
      Static variables (SHADER_VARIABLE_TYPE_STATIC) are variables that are expected to be set only once. They may not be changed once a resource is bound to the variable. Such variables are intended to hold global constants such as camera attributes or global light attributes constant buffers. Mutable variables (SHADER_VARIABLE_TYPE_MUTABLE) define resources that are expected to change on a per-material frequency. Examples may include diffuse textures, normal maps etc. Dynamic variables (SHADER_VARIABLE_TYPE_DYNAMIC) are expected to change frequently and randomly. Shader variable type must be specified during shader creation by populating an array of ShaderVariableDesc structures and initializing ShaderCreationAttribs::Desc::VariableDesc and ShaderCreationAttribs::Desc::NumVariables members (see example of shader creation above).
      Static variables cannot be changed once a resource is bound to the variable. They are bound directly to the shader object. For instance, a shadow map texture is not expected to change after it is created, so it can be bound directly to the shader:
      PixelShader->GetShaderVariable( "g_tex2DShadowMap" )->Set( pShadowMapSRV ); Mutable and dynamic variables are bound via a new Shader Resource Binding object (SRB) that is created by the pipeline state (IPipelineState::CreateShaderResourceBinding()):
      m_pPSO->CreateShaderResourceBinding(&m_pSRB); Note that an SRB is only compatible with the pipeline state it was created from. SRB object inherits all static bindings from shaders in the pipeline, but is not allowed to change them.
      Mutable resources can only be set once for every instance of a shader resource binding. Such resources are intended to define specific material properties. For instance, a diffuse texture for a specific material is not expected to change once the material is defined and can be set right after the SRB object has been created:
      m_pSRB->GetVariable(SHADER_TYPE_PIXEL, "tex2DDiffuse")->Set(pDiffuseTexSRV); In some cases it is necessary to bind a new resource to a variable every time a draw command is invoked. Such variables should be labeled as dynamic, which will allow setting them multiple times through the same SRB object:
      m_pSRB->GetVariable(SHADER_TYPE_VERTEX, "cbRandomAttribs")->Set(pRandomAttrsCB); Under the hood, the engine pre-allocates descriptor tables for static and mutable resources when an SRB objcet is created. Space for dynamic resources is dynamically allocated at run time. Static and mutable resources are thus more efficient and should be used whenever possible.
      As you can see, Diligent Engine does not expose low-level details of how resources are bound to shader variables. One reason for this is that these details are very different for various APIs. The other reason is that using low-level binding methods is extremely error-prone: it is very easy to forget to bind some resource, or bind incorrect resource such as bind a buffer to the variable that is in fact a texture, especially during shader development when everything changes fast. Diligent Engine instead relies on shader reflection system to automatically query the list of all shader variables. Grouping variables based on three types mentioned above allows the engine to create optimized layout and take heavy lifting of matching resources to API-specific resource location, register or descriptor in the table.
      This post gives more details about the resource binding model in Diligent Engine.
      Setting the Pipeline State and Committing Shader Resources
      Before any draw or compute command can be invoked, the pipeline state needs to be bound to the context:
      m_pContext->SetPipelineState(m_pPSO); Under the hood, the engine sets the internal PSO object in the command list or calls all the required native API functions to properly configure all pipeline stages.
      The next step is to bind all required shader resources to the GPU pipeline, which is accomplished by IDeviceContext::CommitShaderResources() method:
      m_pContext->CommitShaderResources(m_pSRB, COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES); The method takes a pointer to the shader resource binding object and makes all resources the object holds available for the shaders. In the case of D3D12, this only requires setting appropriate descriptor tables in the command list. For older APIs, this typically requires setting all resources individually.
      Next-generation APIs require the application to track the state of every resource and explicitly inform the system about all state transitions. For instance, if a texture was used as render target before, while the next draw command is going to use it as shader resource, a transition barrier needs to be executed. Diligent Engine does the heavy lifting of state tracking.  When CommitShaderResources() method is called with COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES flag, the engine commits and transitions resources to correct states at the same time. Note that transitioning resources does introduce some overhead. The engine tracks state of every resource and it will not issue the barrier if the state is already correct. But checking resource state is an overhead that can sometimes be avoided. The engine provides IDeviceContext::TransitionShaderResources() method that only transitions resources:
      m_pContext->TransitionShaderResources(m_pPSO, m_pSRB); In some scenarios it is more efficient to transition resources once and then only commit them.
      Invoking Draw Command
      The final step is to set states that are not part of the PSO, such as render targets, vertex and index buffers. Diligent Engine uses Direct3D11-syle API that is translated to other native API calls under the hood:
      ITextureView *pRTVs[] = {m_pRTV}; m_pContext->SetRenderTargets(_countof( pRTVs ), pRTVs, m_pDSV); // Clear render target and depth buffer const float zero[4] = {0, 0, 0, 0}; m_pContext->ClearRenderTarget(nullptr, zero); m_pContext->ClearDepthStencil(nullptr, CLEAR_DEPTH_FLAG, 1.f); // Set vertex and index buffers IBuffer *buffer[] = {m_pVertexBuffer}; Uint32 offsets[] = {0}; Uint32 strides[] = {sizeof(MyVertex)}; m_pContext->SetVertexBuffers(0, 1, buffer, strides, offsets, SET_VERTEX_BUFFERS_FLAG_RESET); m_pContext->SetIndexBuffer(m_pIndexBuffer, 0); Different native APIs use various set of function to execute draw commands depending on command details (if the command is indexed, instanced or both, what offsets in the source buffers are used etc.). For instance, there are 5 draw commands in Direct3D11 and more than 9 commands in OpenGL with something like glDrawElementsInstancedBaseVertexBaseInstance not uncommon. Diligent Engine hides all details with single IDeviceContext::Draw() method that takes takes DrawAttribs structure as an argument. The structure members define all attributes required to perform the command (primitive topology, number of vertices or indices, if draw call is indexed or not, if draw call is instanced or not, if draw call is indirect or not, etc.). For example:
      DrawAttribs attrs; attrs.IsIndexed = true; attrs.IndexType = VT_UINT16; attrs.NumIndices = 36; attrs.Topology = PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; pContext->Draw(attrs); For compute commands, there is IDeviceContext::DispatchCompute() method that takes DispatchComputeAttribs structure that defines compute grid dimension.
      Source Code
      Full engine source code is available on GitHub and is free to use. The repository contains two samples, asteroids performance benchmark and example Unity project that uses Diligent Engine in native plugin.
      AntTweakBar sample is Diligent Engine’s “Hello World” example.

       
      Atmospheric scattering sample is a more advanced example. It demonstrates how Diligent Engine can be used to implement various rendering tasks: loading textures from files, using complex shaders, rendering to multiple render targets, using compute shaders and unordered access views, etc.

      Asteroids performance benchmark is based on this demo developed by Intel. It renders 50,000 unique textured asteroids and allows comparing performance of Direct3D11 and Direct3D12 implementations. Every asteroid is a combination of one of 1000 unique meshes and one of 10 unique textures.

      Finally, there is an example project that shows how Diligent Engine can be integrated with Unity.

      Future Work
      The engine is under active development. It currently supports Windows desktop, Universal Windows and Android platforms. Direct3D11, Direct3D12, OpenGL/GLES backends are now feature complete. Vulkan backend is coming next, and support for more platforms is planned.
    • By AxeGuywithanAxe
      I wanted to see how others are currently handling descriptor heap updates and management.
      I've read a few articles and there tends to be three major strategies :
      1 ) You split up descriptor heaps per shader stage ( i.e one for vertex shader , pixel , hull, etc)
      2) You have one descriptor heap for an entire pipeline
      3) You split up descriptor heaps for update each update frequency (i.e EResourceSet_PerInstance , EResourceSet_PerPass , EResourceSet_PerMaterial, etc)
      The benefits of the first two approaches is that it makes it easier to port current code, and descriptor / resource descriptor management and updating tends to be easier to manage, but it seems to be not as efficient.
      The benefits of the third approach seems to be that it's the most efficient because you only manage and update objects when they change.
    • By VietNN
      Hi all,
      I want to copy  just 1 mipmap level of a texture and I am doing like this:
      void CopyTextureRegion( &CD3DX12_TEXTURE_COPY_LOCATION(pDstData, mipmapIndex), 0, 0, 0, &CD3DX12_TEXTURE_COPY_LOCATION(pSrcData, pLayout), nullptr ); - pDstData : is DEFAULT_HEAP, pSrcData is UPLOAD_HEAP(buffer size was get by GetCopyableFootprints from pDstData with highest miplevel), pLayout is D3D12_PLACED_SUBRESOURCE_FOOTPRINT
      - I think the mipmapIndex will point the exact location data of Dest texture, but does it know where to get data location from Src texture because pLayout just contain info of this mipmap(Offset and Footprint).  (???)
      - pLayout has a member name Offset, and I try to modify it but it(Offset) need 512 Alignment but real offset in Src texture does not.
      So what I need to do to match the location of mip texture in Src Texture ?
      @SoldierOfLight @galop1n
    • By _void_
      Hello!
      I am wondering if there is a way to find out how many resources you could bind to the command list directly without putting them in a descriptor table.
      Specifically, I am referring to these guys:
      - SetGraphicsRoot32BitConstant
      - SetGraphicsRoot32BitConstants
      - SetGraphicsRootConstantBufferView
      - SetGraphicsRootShaderResourceView
      - SetGraphicsRootUnorderedAccessView
      I remember from early presentations on D3D12 that the count of allowed resources is hardware dependent and quite small. But I would like to learn some more concrete figures.
    • By lubbe75
      I am trying to set up my sampler correctly so that textures are filtered the way I want. I want to use linear filtering for both min and mag, and I don't want to use any mipmap at all.
      To make sure that mipmap is turned off I set the MipLevels to 1 for my textures.
      For the sampler filter I have tried all kind of combinations, but somehow the mag filter works fine while the min filter doesn't seem to work at all. As I zoom out there seems to be a nearest point filter.
      Is there a catch in Dx12 that makes my min filter not working?
      Do I need to filter manually in my shader? I don't think so since the mag filter works correctly.
      My pixel shader is just a simple texture lookup:
      textureMap.Sample(g_sampler, input.uv); My sampler setup looks like this (SharpDX):
      sampler = new StaticSamplerDescription() { Filter = Filter.MinMagLinearMipPoint, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, ComparisonFunc = Comparison.Never, BorderColor = StaticBorderColor.TransparentBlack, ShaderRegister = 0, RegisterSpace = 0, ShaderVisibility = ShaderVisibility.Pixel, };  
  • Advertisement