-
Notifications
You must be signed in to change notification settings - Fork 324
Expand file tree
/
Copy pathFrameInterpolationSwapchainDX12.cpp
More file actions
1573 lines (1239 loc) · 59 KB
/
FrameInterpolationSwapchainDX12.cpp
File metadata and controls
1573 lines (1239 loc) · 59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of the FidelityFX SDK.
//
// Copyright (c) 2023 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <initguid.h>
#include "FrameInterpolationSwapChainDX12.h"
#include <FidelityFX/host/backends/dx12/ffx_dx12.h>
#include "FrameInterpolationSwapchainDX12_UiComposition.h"
FfxErrorCode ffxRegisterFrameinterpolationUiResourceDX12(FfxSwapchain gameSwapChain, FfxResource uiResource)
{
IDXGISwapChain4* swapChain = ffxGetDX12SwapchainPtr(gameSwapChain);
FrameInterpolationSwapChainDX12* framinterpolationSwapchain = nullptr;
if (SUCCEEDED(swapChain->QueryInterface(IID_PPV_ARGS(&framinterpolationSwapchain))))
{
framinterpolationSwapchain->registerUiResource(uiResource);
SafeRelease(framinterpolationSwapchain);
return FFX_OK;
}
return FFX_ERROR_INVALID_ARGUMENT;
}
FFX_API FfxErrorCode ffxSetFrameGenerationConfigToSwapchainDX12(FfxFrameGenerationConfig const* config)
{
FfxErrorCode result = FFX_ERROR_INVALID_ARGUMENT;
if (config->swapChain)
{
IDXGISwapChain4* swapChain = ffxGetDX12SwapchainPtr(config->swapChain);
FrameInterpolationSwapChainDX12* framinterpolationSwapchain = nullptr;
if (SUCCEEDED(swapChain->QueryInterface(IID_PPV_ARGS(&framinterpolationSwapchain))))
{
framinterpolationSwapchain->setFrameGenerationConfig(config);
SafeRelease(framinterpolationSwapchain);
result = FFX_OK;
}
}
return result;
}
FfxResource ffxGetFrameinterpolationTextureDX12(FfxSwapchain gameSwapChain)
{
FfxResource res = { nullptr };
IDXGISwapChain4* swapChain = ffxGetDX12SwapchainPtr(gameSwapChain);
FrameInterpolationSwapChainDX12* framinterpolationSwapchain = nullptr;
if (SUCCEEDED(swapChain->QueryInterface(IID_PPV_ARGS(&framinterpolationSwapchain))))
{
res = framinterpolationSwapchain->interpolationOutput(0);
SafeRelease(framinterpolationSwapchain);
}
return res;
}
FfxErrorCode ffxGetFrameinterpolationCommandlistDX12(FfxSwapchain gameSwapChain, FfxCommandList& gameCommandlist)
{
// 1) query FrameInterpolationSwapChainDX12 from gameSwapChain
// 2) call FrameInterpolationSwapChainDX12::getInterpolationCommandList()
IDXGISwapChain4* swapChain = ffxGetDX12SwapchainPtr(gameSwapChain);
FrameInterpolationSwapChainDX12* framinterpolationSwapchain = nullptr;
if (SUCCEEDED(swapChain->QueryInterface(IID_PPV_ARGS(&framinterpolationSwapchain))))
{
gameCommandlist = framinterpolationSwapchain->getInterpolationCommandList();
SafeRelease(framinterpolationSwapchain);
return FFX_OK;
}
return FFX_ERROR_INVALID_ARGUMENT;
}
FfxErrorCode ffxReplaceSwapchainForFrameinterpolationDX12(FfxCommandQueue gameQueue, FfxSwapchain& gameSwapChain)
{
FfxErrorCode status = FFX_ERROR_INVALID_ARGUMENT;
IDXGISwapChain4* dxgiGameSwapChain = reinterpret_cast<IDXGISwapChain4*>(gameSwapChain);
FFX_ASSERT(dxgiGameSwapChain);
ID3D12CommandQueue* queue = reinterpret_cast<ID3D12CommandQueue*>(gameQueue);
FFX_ASSERT(queue);
// we just need the desc, release the real swapchain as we'll replace that with one doing frameinterpolation
HWND hWnd;
DXGI_SWAP_CHAIN_DESC1 desc1;
DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullscreenDesc;
if (SUCCEEDED(dxgiGameSwapChain->GetDesc1(&desc1)) &&
SUCCEEDED(dxgiGameSwapChain->GetFullscreenDesc(&fullscreenDesc)) &&
SUCCEEDED(dxgiGameSwapChain->GetHwnd(&hWnd))
)
{
FFX_ASSERT_MESSAGE(fullscreenDesc.Windowed == TRUE, "Illegal to release a fullscreen swap chain.");
IDXGIFactory* dxgiFactory = getDXGIFactoryFromSwapChain(dxgiGameSwapChain);
SafeRelease(dxgiGameSwapChain);
FfxSwapchain proxySwapChain;
status = ffxCreateFrameinterpolationSwapchainForHwndDX12(hWnd, &desc1, &fullscreenDesc, queue, dxgiFactory, proxySwapChain);
if (status == FFX_OK)
{
gameSwapChain = proxySwapChain;
}
SafeRelease(dxgiFactory);
}
return status;
}
FfxErrorCode ffxCreateFrameinterpolationSwapchainDX12(const DXGI_SWAP_CHAIN_DESC* desc,
ID3D12CommandQueue* queue,
IDXGIFactory* dxgiFactory,
FfxSwapchain& outGameSwapChain)
{
FFX_ASSERT(desc);
FFX_ASSERT(queue);
FFX_ASSERT(dxgiFactory);
DXGI_SWAP_CHAIN_DESC1 desc1{};
desc1.Width = desc->BufferDesc.Width;
desc1.Height = desc->BufferDesc.Height;
desc1.Format = desc->BufferDesc.Format;
desc1.SampleDesc = desc->SampleDesc;
desc1.BufferUsage = desc->BufferUsage;
desc1.BufferCount = desc->BufferCount;
desc1.SwapEffect = desc->SwapEffect;
desc1.Flags = desc->Flags;
// for clarity, params not part of DXGI_SWAP_CHAIN_DESC
// implicit behavior of DXGI when you call the IDXGIFactory::CreateSwapChain
desc1.Scaling = DXGI_SCALING_STRETCH;
desc1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
desc1.Stereo = FALSE;
DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullscreenDesc{};
fullscreenDesc.Scaling = desc->BufferDesc.Scaling;
fullscreenDesc.RefreshRate = desc->BufferDesc.RefreshRate;
fullscreenDesc.ScanlineOrdering = desc->BufferDesc.ScanlineOrdering;
fullscreenDesc.Windowed = desc->Windowed;
return ffxCreateFrameinterpolationSwapchainForHwndDX12(desc->OutputWindow, &desc1, &fullscreenDesc, queue, dxgiFactory, outGameSwapChain);
}
FfxErrorCode ffxCreateFrameinterpolationSwapchainForHwndDX12(HWND hWnd,
const DXGI_SWAP_CHAIN_DESC1* desc1,
const DXGI_SWAP_CHAIN_FULLSCREEN_DESC* fullscreenDesc,
ID3D12CommandQueue* queue,
IDXGIFactory* dxgiFactory,
FfxSwapchain& outGameSwapChain)
{
// don't assert fullscreenDesc, nullptr valid
FFX_ASSERT(hWnd != 0);
FFX_ASSERT(desc1);
FFX_ASSERT(queue);
FFX_ASSERT(dxgiFactory);
FfxErrorCode err = FFX_ERROR_INVALID_ARGUMENT;
IDXGIFactory2* dxgiFactory2 = nullptr;
if (SUCCEEDED(dxgiFactory->QueryInterface(IID_PPV_ARGS(&dxgiFactory2))))
{
// Create proxy swapchain
FrameInterpolationSwapChainDX12* fiSwapchain = new FrameInterpolationSwapChainDX12();
if (fiSwapchain)
{
if (SUCCEEDED(fiSwapchain->init(hWnd, desc1, fullscreenDesc, queue, dxgiFactory2)))
{
outGameSwapChain = ffxGetSwapchainDX12(fiSwapchain);
err = FFX_OK;
}
else
{
delete fiSwapchain;
err = FFX_ERROR_INVALID_ARGUMENT;
}
}
else
{
err = FFX_ERROR_OUT_OF_MEMORY;
}
SafeRelease(dxgiFactory2);
}
return err;
}
FfxErrorCode ffxWaitForPresents(FfxSwapchain gameSwapChain)
{
IDXGISwapChain4* swapChain = ffxGetDX12SwapchainPtr(gameSwapChain);
FrameInterpolationSwapChainDX12* framinterpolationSwapchain;
if (SUCCEEDED(swapChain->QueryInterface(IID_PPV_ARGS(&framinterpolationSwapchain))))
{
framinterpolationSwapchain->waitForPresents();
SafeRelease(framinterpolationSwapchain);
return FFX_OK;
}
return FFX_ERROR_INVALID_ARGUMENT;
}
void setSwapChainBufferResourceInfo(IDXGISwapChain4* swapChain, bool isInterpolated)
{
uint32_t currBackbufferIndex = swapChain->GetCurrentBackBufferIndex();
ID3D12Resource* swapchainBackbuffer = nullptr;
if (SUCCEEDED(swapChain->GetBuffer(currBackbufferIndex, IID_PPV_ARGS(&swapchainBackbuffer))))
{
FfxFrameInterpolationSwapChainResourceInfo info{};
info.version = FFX_FRAME_INTERPOLATION_SWAP_CHAIN_VERSION;
info.isInterpolated = isInterpolated;
HRESULT hr = swapchainBackbuffer->SetPrivateData(IID_IFfxFrameInterpolationSwapChainResourceInfo, sizeof(info), &info);
FFX_ASSERT(SUCCEEDED(hr));
/*
usage example:
FfxFrameInterpolationSwapChainResourceInfo info{};
UINT size = sizeof(info);
if (SUCCEEDED(swapchainBackbuffer->GetPrivateData(IID_IFfxFrameInterpolationSwapChainResourceInfo, &size, &info))) {
} else {
// buffer was not presented using proxy swapchain
}
*/
SafeRelease(swapchainBackbuffer);
}
}
HRESULT compositeSwapChainFrame(FrameinterpolationPresentInfo* presenter, PacingData* pacingEntry, uint32_t frameID)
{
const PacingData::FrameInfo& frameInfo = pacingEntry->frames[frameID];
presenter->presentQueue->Wait(presenter->interpolationFence, frameInfo.interpolationCompletedFenceValue);
if (pacingEntry->presentCallback)
{
auto gpuCommands = presenter->commandPool.get(presenter->presentQueue, L"compositeSwapChainFrame");
uint32_t currBackbufferIndex = presenter->swapChain->GetCurrentBackBufferIndex();
ID3D12Resource* swapchainBackbuffer = nullptr;
presenter->swapChain->GetBuffer(currBackbufferIndex, IID_PPV_ARGS(&swapchainBackbuffer));
FfxPresentCallbackDescription desc{};
desc.commandList = ffxGetCommandListDX12(gpuCommands->reset());
desc.device = presenter->device;
desc.isInterpolatedFrame = frameID != PacingData::FrameIdentifier::Real;
desc.outputSwapChainBuffer = ffxGetResourceDX12(swapchainBackbuffer, GetFfxResourceDescriptionDX12(swapchainBackbuffer), nullptr, FFX_RESOURCE_STATE_PRESENT);
desc.currentBackBuffer = frameInfo.resource;
desc.currentUI = pacingEntry->uiSurface;
pacingEntry->presentCallback(&desc);
gpuCommands->execute(true);
SafeRelease(swapchainBackbuffer);
}
presenter->presentQueue->Signal(presenter->compositionFence, frameInfo.presentIndex);
return S_OK;
}
void presentToSwapChain(FrameinterpolationPresentInfo* presenter, PacingData* pacingEntry, uint32_t frameID)
{
const PacingData::FrameInfo& frameInfo = pacingEntry->frames[frameID];
const UINT uSyncInterval = pacingEntry->vsync ? 1 : 0;
const bool bExclusiveFullscreen = isExclusiveFullscreen(presenter->swapChain);
const bool bSetAllowTearingFlag = pacingEntry->tearingSupported && !bExclusiveFullscreen && (0 == uSyncInterval);
const UINT uFlags = bSetAllowTearingFlag * DXGI_PRESENT_ALLOW_TEARING;
presenter->swapChain->Present(uSyncInterval, uFlags);
// tick frames sent for presentation
presenter->presentQueue->Signal(presenter->presentFence, frameInfo.presentIndex);
}
DWORD WINAPI presenterThread(LPVOID param)
{
FrameinterpolationPresentInfo* presenter = static_cast<FrameinterpolationPresentInfo*>(param);
if (presenter)
{
UINT64 numFramesSentForPresentation = 0;
while (!presenter->shutdown)
{
WaitForSingleObject(presenter->pacerEvent, INFINITE);
if (!presenter->shutdown)
{
EnterCriticalSection(&presenter->criticalSectionScheduledFrame);
PacingData entry = presenter->scheduledPresents;
presenter->scheduledPresents.invalidate();
LeaveCriticalSection(&presenter->criticalSectionScheduledFrame);
if (entry.numFramesToPresent > 0)
{
// we might have dropped entries so have to update here, otherwise we might deadlock
presenter->presentQueue->Signal(presenter->presentFence, entry.numFramesSentForPresentationBase);
presenter->presentQueue->Wait(presenter->gameFence, entry.gameFenceValue);
for (uint32_t frameID = 0; frameID < PacingData::FrameIdentifier::Count; frameID++)
{
const PacingData::FrameInfo& frameInfo = entry.frames[frameID];
if (frameInfo.doPresent)
{
compositeSwapChainFrame(presenter, &entry, frameID);
// signal replacement buffer availability
if (frameInfo.presentIndex == entry.replacementBufferFenceSignal)
{
presenter->presentQueue->Signal(presenter->replacementBufferFence, entry.replacementBufferFenceSignal);
}
waitForPerformanceCount(frameInfo.presentQpcTarget);
presentToSwapChain(presenter, &entry, frameID);
}
}
numFramesSentForPresentation = entry.numFramesSentForPresentationBase + entry.numFramesToPresent;
}
}
}
waitForFenceValue(presenter->presentFence, numFramesSentForPresentation);
}
return 0;
}
DWORD WINAPI interpolationThread(LPVOID param)
{
FrameinterpolationPresentInfo* presenter = static_cast<FrameinterpolationPresentInfo*>(param);
if (presenter)
{
HANDLE presenterThreadHandle = CreateThread(nullptr, 0, presenterThread, param, 0, nullptr);
FFX_ASSERT(presenterThreadHandle != NULL);
if (presenterThreadHandle != 0)
{
SetThreadPriority(presenterThreadHandle, THREAD_PRIORITY_HIGHEST);
SetThreadDescription(presenterThreadHandle, L"AMD FSR Presenter Thread");
SimpleMovingAverage<2, double> frameTime{};
SimpleMovingAverage<2, double> compositionTime{};
int64_t previousQpc = 0;
while (!presenter->shutdown)
{
WaitForSingleObject(presenter->presentEvent, INFINITE);
if (!presenter->shutdown)
{
EnterCriticalSection(&presenter->criticalSectionScheduledFrame);
PacingData entry = presenter->scheduledInterpolations;
presenter->scheduledInterpolations.invalidate();
LeaveCriticalSection(&presenter->criticalSectionScheduledFrame);
waitForFenceValue(presenter->interpolationFence,
entry.frames[PacingData::FrameIdentifier::Interpolated_1].interpolationCompletedFenceValue);
SetEvent(presenter->interpolationEvent);
int64_t currentQpc = 0;
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(¤tQpc));
const double deltaQpc = double(currentQpc - previousQpc) * (previousQpc > 0);
previousQpc = currentQpc;
// reset pacing averaging if delta > 10 fps,
int64_t qpcFrequency;
QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(&qpcFrequency));
const float fTimeoutInSeconds = 0.1f;
double deltaQpcResetThreashold = double(qpcFrequency * fTimeoutInSeconds);
if (deltaQpc > deltaQpcResetThreashold)
{
frameTime.reset();
compositionTime.reset();
}
else
{
frameTime.update(deltaQpc);
}
// set presentation time for the real frame
const int64_t deltaToUse = int64_t(frameTime.getAverage() * 0.5) + int64_t(compositionTime.getAverage());
entry.frames[PacingData::FrameIdentifier::Real].presentQpcTarget = currentQpc + deltaToUse;
// schedule presents
EnterCriticalSection(&presenter->criticalSectionScheduledFrame);
presenter->scheduledPresents = entry;
LeaveCriticalSection(&presenter->criticalSectionScheduledFrame);
SetEvent(presenter->pacerEvent);
// estimate gpu composition time if both interpolated and real frames are to be presented
if (entry.vsync == false &&
entry.frames[PacingData::FrameIdentifier::Interpolated_1].doPresent &&
entry.frames[PacingData::FrameIdentifier::Real].doPresent)
{
int64_t compositionBeginQpc = 0;
int64_t compositionEndQpc = 0;
// wait for interpolated frame present to finish
waitForFenceValue(presenter->presentFence, entry.frames[PacingData::FrameIdentifier::Interpolated_1].presentIndex);
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(&compositionBeginQpc));
// wait for real frame composition to finish
waitForFenceValue(presenter->compositionFence, entry.frames[PacingData::FrameIdentifier::Real].presentIndex);
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(&compositionEndQpc));
const double duration = double(compositionEndQpc - compositionBeginQpc);
compositionTime.update(duration);
}
else
{
compositionTime.reset();
}
}
}
// signal event to allow thread to finish
SetEvent(presenter->pacerEvent);
WaitForSingleObject(presenterThreadHandle, INFINITE);
SafeCloseHandle(presenterThreadHandle);
}
}
return 0;
}
bool FrameInterpolationSwapChainDX12::verifyBackbufferDuplicateResources()
{
HRESULT hr = S_OK;
ID3D12Device8* device = nullptr;
ID3D12Resource* buffer = nullptr;
if (SUCCEEDED(real()->GetBuffer(0, IID_PPV_ARGS(&buffer))))
{
if (SUCCEEDED(buffer->GetDevice(IID_PPV_ARGS(&device))))
{
auto bufferDesc = buffer->GetDesc();
D3D12_HEAP_PROPERTIES heapProperties{};
D3D12_HEAP_FLAGS heapFlags;
buffer->GetHeapProperties(&heapProperties, &heapFlags);
heapFlags &= ~D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;
heapFlags &= ~D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES;
heapFlags &= ~D3D12_HEAP_FLAG_DENY_BUFFERS;
heapFlags &= ~D3D12_HEAP_FLAG_ALLOW_DISPLAY;
for (size_t i = 0; i < gameBufferCount_; i++)
{
if (replacementSwapBuffers_[i].resource == nullptr)
{
// create game render output resource
if (FAILED(device->CreateCommittedResource(&heapProperties,
heapFlags,
&bufferDesc,
D3D12_RESOURCE_STATE_PRESENT,
nullptr,
IID_PPV_ARGS(&replacementSwapBuffers_[i].resource))))
{
hr |= E_FAIL;
}
else
{
replacementSwapBuffers_[i].resource->SetName(L"AMD FSR Replacement BackBuffer");
}
}
}
for (size_t i = 0; i < _countof(interpolationOutputs_); i++)
{
// create interpolation output resource
bufferDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
if (interpolationOutputs_[i].resource == nullptr)
{
if (FAILED(device->CreateCommittedResource(
&heapProperties, heapFlags, &bufferDesc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&interpolationOutputs_[i].resource))))
{
hr |= E_FAIL;
}
else
{
interpolationOutputs_[i].resource->SetName(L"AMD FSR Interpolation Output");
}
}
}
SafeRelease(device);
}
SafeRelease(realBackBuffer0_);
realBackBuffer0_ = buffer;
}
return SUCCEEDED(hr);
}
HRESULT FrameInterpolationSwapChainDX12::init(HWND hWnd,
const DXGI_SWAP_CHAIN_DESC1* desc,
const DXGI_SWAP_CHAIN_FULLSCREEN_DESC* fullscreenDesc,
ID3D12CommandQueue* queue,
IDXGIFactory2* dxgiFactory)
{
FFX_ASSERT(desc);
FFX_ASSERT(queue);
FFX_ASSERT(dxgiFactory);
// store values we modify, to return when application asks for info
gameBufferCount_ = desc->BufferCount;
gameFlags_ = desc->Flags;
gameSwapEffect_ = desc->SwapEffect;
// set default ui composition / frame interpolation present function
presentCallback_ = ffxFrameInterpolationUiComposition;
HRESULT hr = E_FAIL;
if (SUCCEEDED(queue->GetDevice(IID_PPV_ARGS(&presentInfo_.device))))
{
presentInfo_.gameQueue = queue;
InitializeCriticalSection(&criticalSection_);
InitializeCriticalSection(&presentInfo_.criticalSectionScheduledFrame);
presentInfo_.presentEvent = CreateEvent(NULL, FALSE, FALSE, nullptr);
presentInfo_.interpolationEvent = CreateEvent(NULL, FALSE, TRUE, nullptr);
presentInfo_.pacerEvent = CreateEvent(NULL, FALSE, FALSE,nullptr);
tearingSupported_ = isTearingSupported(dxgiFactory);
// Create presentation queue
D3D12_COMMAND_QUEUE_DESC presentQueueDesc = queue->GetDesc();
presentQueueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
presentQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
presentQueueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_HIGH;
presentQueueDesc.NodeMask = 0;
presentInfo_.device->CreateCommandQueue(&presentQueueDesc, IID_PPV_ARGS(&presentInfo_.presentQueue));
presentInfo_.presentQueue->SetName(L"AMD FSR PresentQueue");
// Setup pass-through swapchain default state is disabled/passthrough
IDXGISwapChain1* pSwapChain1 = nullptr;
DXGI_SWAP_CHAIN_DESC1 realDesc = getInterpolationEnabledSwapChainDescription(desc);
hr = dxgiFactory->CreateSwapChainForHwnd(presentInfo_.presentQueue, hWnd, &realDesc, fullscreenDesc, nullptr, &pSwapChain1);
if (SUCCEEDED(hr) && queue)
{
if (SUCCEEDED(hr = pSwapChain1->QueryInterface(IID_PPV_ARGS(&presentInfo_.swapChain))))
{
// Register proxy swapchain to the real swap chain object
presentInfo_.swapChain->SetPrivateData(IID_IFfxFrameInterpolationSwapChain, sizeof(FrameInterpolationSwapChainDX12*), this);
SafeRelease(pSwapChain1);
}
else
{
FFX_ASSERT(hr == S_OK);
return hr;
}
}
else
{
FFX_ASSERT(hr == S_OK);
return hr;
}
// init min and lax luminance according to monitor metadata
// in case app doesn't set it through SetHDRMetadata
getMonitorLuminanceRange(presentInfo_.swapChain, &minLuminance_, &maxLuminance_);
presentInfo_.device->CreateFence(gameFenceValue_, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&presentInfo_.gameFence));
presentInfo_.gameFence->SetName(L"AMD FSR GameFence");
presentInfo_.device->CreateFence(interpolationFenceValue_, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&presentInfo_.interpolationFence));
presentInfo_.interpolationFence->SetName(L"AMD FSR InterpolationFence");
presentInfo_.device->CreateFence(framesSentForPresentation_, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&presentInfo_.presentFence));
presentInfo_.presentFence->SetName(L"AMD FSR PresentFence");
presentInfo_.device->CreateFence(framesSentForPresentation_, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&presentInfo_.replacementBufferFence));
presentInfo_.replacementBufferFence->SetName(L"AMD FSR ReplacementBufferFence");
presentInfo_.device->CreateFence(framesSentForPresentation_, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&presentInfo_.compositionFence));
presentInfo_.compositionFence->SetName(L"AMD FSR CompositionFence");
replacementFrameLatencyWaitableObjectHandle_ = CreateEvent(0, FALSE, TRUE, nullptr);
// Create interpolation queue
D3D12_COMMAND_QUEUE_DESC queueDesc = queue->GetDesc();
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_HIGH;
queueDesc.NodeMask = 0;
presentInfo_.device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&presentInfo_.asyncComputeQueue));
presentInfo_.asyncComputeQueue->SetName(L"AMD FSR AsyncComputeQueue");
// Default to dispatch interpolation workloads on the game queue
presentInfo_.interpolationQueue = presentInfo_.gameQueue;
}
return hr;
}
FrameInterpolationSwapChainDX12::FrameInterpolationSwapChainDX12()
{
}
FrameInterpolationSwapChainDX12::~FrameInterpolationSwapChainDX12()
{
shutdown();
}
UINT FrameInterpolationSwapChainDX12::getInterpolationEnabledSwapChainFlags(UINT nonAdjustedFlags)
{
UINT flags = nonAdjustedFlags;
flags &= ~DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
if (tearingSupported_)
{
flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
}
return flags;
}
DXGI_SWAP_CHAIN_DESC1 FrameInterpolationSwapChainDX12::getInterpolationEnabledSwapChainDescription(const DXGI_SWAP_CHAIN_DESC1* nonAdjustedDesc)
{
DXGI_SWAP_CHAIN_DESC1 fiDesc = *nonAdjustedDesc;
// adjust swap chain descriptor to fit FI requirements
fiDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
fiDesc.BufferCount = 3;
fiDesc.Flags = getInterpolationEnabledSwapChainFlags(fiDesc.Flags);
return fiDesc;
}
IDXGISwapChain4* FrameInterpolationSwapChainDX12::real()
{
return presentInfo_.swapChain;
}
HRESULT FrameInterpolationSwapChainDX12::shutdown()
{
//m_pDevice will be nullptr already shutdown
if (presentInfo_.device)
{
releaseUiBlitGpuResources();
destroyReplacementResources();
killPresenterThread();
SafeCloseHandle(presentInfo_.presentEvent);
SafeCloseHandle(presentInfo_.interpolationEvent);
SafeCloseHandle(presentInfo_.pacerEvent);
presentInfo_.interpolationQueue->Signal(presentInfo_.interpolationFence, ++interpolationFenceValue_);
waitForFenceValue(presentInfo_.interpolationFence, interpolationFenceValue_);
SafeRelease(presentInfo_.asyncComputeQueue);
SafeRelease(presentInfo_.presentQueue);
SafeRelease(presentInfo_.interpolationFence);
SafeRelease(presentInfo_.presentFence);
SafeRelease(presentInfo_.replacementBufferFence);
SafeRelease(presentInfo_.compositionFence);
UINT sc_refCount = SafeRelease(presentInfo_.swapChain);
waitForFenceValue(presentInfo_.gameFence, gameFenceValue_);
SafeRelease(presentInfo_.gameFence);
DeleteCriticalSection(&criticalSection_);
DeleteCriticalSection(&presentInfo_.criticalSectionScheduledFrame);
UINT device_refCount = SafeRelease(presentInfo_.device);
}
return S_OK;
}
bool FrameInterpolationSwapChainDX12::killPresenterThread()
{
if (interpolationThreadHandle_ != NULL)
{
// prepare present CPU thread for shutdown
presentInfo_.shutdown = true;
// signal event to allow thread to finish
SetEvent(presentInfo_.presentEvent);
WaitForSingleObject(interpolationThreadHandle_, INFINITE);
SafeCloseHandle(interpolationThreadHandle_);
}
return interpolationThreadHandle_ == nullptr;
}
bool FrameInterpolationSwapChainDX12::spawnPresenterThread()
{
if (interpolationThreadHandle_ == NULL)
{
presentInfo_.shutdown = false;
interpolationThreadHandle_ = CreateThread(nullptr, 0, interpolationThread, reinterpret_cast<void*>(&presentInfo_), 0, nullptr);
FFX_ASSERT(interpolationThreadHandle_ != NULL);
if (interpolationThreadHandle_ != 0)
{
SetThreadPriority(interpolationThreadHandle_, THREAD_PRIORITY_HIGHEST);
SetThreadDescription(interpolationThreadHandle_, L"AMD FSR Interpolation Thread");
}
SetEvent(presentInfo_.interpolationEvent);
}
return interpolationThreadHandle_ != NULL;
}
void FrameInterpolationSwapChainDX12::discardOutstandingInterpolationCommandLists()
{
// drop any outstanding interpolaton command lists
for (int i = 0; i < _countof(registeredInterpolationCommandLists_); i++)
{
if (registeredInterpolationCommandLists_[i] != nullptr)
{
registeredInterpolationCommandLists_[i]->drop(true);
registeredInterpolationCommandLists_[i] = nullptr;
}
}
}
void FrameInterpolationSwapChainDX12::setFrameGenerationConfig(FfxFrameGenerationConfig const* config)
{
FFX_ASSERT(config);
EnterCriticalSection(&criticalSection_);
FfxPresentCallbackFunc inputPresentCallback = (nullptr != config->presentCallback) ? config->presentCallback : ffxFrameInterpolationUiComposition;
ID3D12CommandQueue* inputInterpolationQueue = config->allowAsyncWorkloads ? presentInfo_.asyncComputeQueue : presentInfo_.gameQueue;
presentInterpolatedOnly_ = config->onlyPresentInterpolated;
if (presentInfo_.interpolationQueue != inputInterpolationQueue)
{
waitForPresents();
discardOutstandingInterpolationCommandLists();
// change interpolation queue and reset fence value
presentInfo_.interpolationQueue = inputInterpolationQueue;
interpolationFenceValue_ = 0;
presentInfo_.interpolationQueue->Signal(presentInfo_.interpolationFence, interpolationFenceValue_);
}
if (interpolationEnabled_ != config->frameGenerationEnabled ||
presentCallback_ != inputPresentCallback ||
frameGenerationCallback_ != config->frameGenerationCallback)
{
waitForPresents();
presentCallback_ = inputPresentCallback;
frameGenerationCallback_ = config->frameGenerationCallback;
// handle interpolation mode change
if (interpolationEnabled_ != config->frameGenerationEnabled)
{
interpolationEnabled_ = config->frameGenerationEnabled;
if (interpolationEnabled_)
{
frameInterpolationResetCondition_ = true;
nextPresentWaitValue_ = framesSentForPresentation_;
spawnPresenterThread();
}
else
{
killPresenterThread();
}
}
}
LeaveCriticalSection(&criticalSection_);
}
bool FrameInterpolationSwapChainDX12::destroyReplacementResources()
{
HRESULT hr = S_OK;
EnterCriticalSection(&criticalSection_);
waitForPresents();
const bool recreatePresenterThread = interpolationThreadHandle_ != nullptr;
if (recreatePresenterThread)
{
killPresenterThread();
}
discardOutstandingInterpolationCommandLists();
{
for (size_t i = 0; i < _countof(replacementSwapBuffers_); i++)
{
replacementSwapBuffers_[i].destroy();
}
SafeRelease(realBackBuffer0_);
for (size_t i = 0; i < _countof(interpolationOutputs_); i++)
{
interpolationOutputs_[i].destroy();
}
}
// reset counters used in buffer management
framesSentForPresentation_ = 0;
nextPresentWaitValue_ = 0;
replacementSwapBufferIndex_ = 0;
presentCount_ = 0;
interpolationFenceValue_ = 0;
gameFenceValue_ = 0;
presentInfo_.gameFence->Signal(gameFenceValue_);
presentInfo_.interpolationFence->Signal(interpolationFenceValue_);
presentInfo_.presentFence->Signal(framesSentForPresentation_);
presentInfo_.replacementBufferFence->Signal(framesSentForPresentation_);
presentInfo_.compositionFence->Signal(framesSentForPresentation_);
frameInterpolationResetCondition_ = true;
if (recreatePresenterThread)
{
spawnPresenterThread();
}
discardOutstandingInterpolationCommandLists();
LeaveCriticalSection(&criticalSection_);
return SUCCEEDED(hr);
}
bool FrameInterpolationSwapChainDX12::waitForPresents()
{
// wait for interpolation to finish
waitForFenceValue(presentInfo_.gameFence, gameFenceValue_);
waitForFenceValue(presentInfo_.interpolationFence, interpolationFenceValue_);
waitForFenceValue(presentInfo_.presentFence, framesSentForPresentation_);
return true;
}
FfxResource FrameInterpolationSwapChainDX12::interpolationOutput(int index)
{
index = interpolationBufferIndex_;
FfxResourceDescription interpolateDesc = GetFfxResourceDescriptionDX12(interpolationOutputs_[index].resource);
return ffxGetResourceDX12(interpolationOutputs_[index].resource, interpolateDesc, nullptr, FFX_RESOURCE_STATE_UNORDERED_ACCESS);
}
//IUnknown
HRESULT STDMETHODCALLTYPE FrameInterpolationSwapChainDX12::QueryInterface(REFIID riid, void** ppvObject)
{
const GUID guidReplacements[] = {
__uuidof(this),
IID_IUnknown,
IID_IDXGIObject,
IID_IDXGIDeviceSubObject,
IID_IDXGISwapChain,
IID_IDXGISwapChain1,
IID_IDXGISwapChain2,
IID_IDXGISwapChain3,
IID_IDXGISwapChain4,
IID_IFfxFrameInterpolationSwapChain
};
for (auto guid : guidReplacements)
{
if (IsEqualGUID(riid, guid) == TRUE)
{
AddRef();
*ppvObject = this;
return S_OK;
}
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE FrameInterpolationSwapChainDX12::AddRef()
{
InterlockedIncrement(&refCount_);
return refCount_;
}
ULONG STDMETHODCALLTYPE FrameInterpolationSwapChainDX12::Release()
{
ULONG ref = InterlockedDecrement(&refCount_);
if (ref != 0)
{
return refCount_;
}
delete this;
return 0;
}
// IDXGIObject
HRESULT STDMETHODCALLTYPE FrameInterpolationSwapChainDX12::SetPrivateData(REFGUID Name, UINT DataSize, const void* pData)
{
return real()->SetPrivateData(Name, DataSize, pData);
}
HRESULT STDMETHODCALLTYPE FrameInterpolationSwapChainDX12::SetPrivateDataInterface(REFGUID Name, const IUnknown* pUnknown)
{
return real()->SetPrivateDataInterface(Name, pUnknown);
}
HRESULT STDMETHODCALLTYPE FrameInterpolationSwapChainDX12::GetPrivateData(REFGUID Name, UINT* pDataSize, void* pData)
{
return real()->GetPrivateData(Name, pDataSize, pData);
}
HRESULT STDMETHODCALLTYPE FrameInterpolationSwapChainDX12::GetParent(REFIID riid, void** ppParent)
{
return real()->GetParent(riid, ppParent);
}
// IDXGIDeviceSubObject
HRESULT STDMETHODCALLTYPE FrameInterpolationSwapChainDX12::GetDevice(REFIID riid, void** ppDevice)
{
return real()->GetDevice(riid, ppDevice);
}
void FrameInterpolationSwapChainDX12::registerUiResource(FfxResource uiResource)
{
EnterCriticalSection(&criticalSection_);
presentInfo_.currentUiSurface = uiResource;
LeaveCriticalSection(&criticalSection_);
}
void FrameInterpolationSwapChainDX12::presentPassthrough(UINT SyncInterval, UINT Flags)
{
ID3D12Resource* dx12SwapchainBuffer = nullptr;
UINT currentBackBufferIndex = presentInfo_.swapChain->GetCurrentBackBufferIndex();
presentInfo_.swapChain->GetBuffer(currentBackBufferIndex, IID_PPV_ARGS(&dx12SwapchainBuffer));
auto passthroughList = presentInfo_.commandPool.get(presentInfo_.presentQueue, L"passthroughList()");
auto list = passthroughList->reset();
ID3D12Resource* dx12ResourceSrc = replacementSwapBuffers_[replacementSwapBufferIndex_].resource;
ID3D12Resource* dx12ResourceDst = dx12SwapchainBuffer;
D3D12_TEXTURE_COPY_LOCATION dx12SourceLocation = {};
dx12SourceLocation.pResource = dx12ResourceSrc;
dx12SourceLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
dx12SourceLocation.SubresourceIndex = 0;
D3D12_TEXTURE_COPY_LOCATION dx12DestinationLocation = {};
dx12DestinationLocation.pResource = dx12ResourceDst;
dx12DestinationLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;