-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy pathfsrapirendermodule.cpp
More file actions
1980 lines (1700 loc) · 100 KB
/
fsrapirendermodule.cpp
File metadata and controls
1980 lines (1700 loc) · 100 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) 2025 Advanced Micro Devices, Inc.
//
// 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 "fsrapirendermodule.h"
#include <cauldron2/dx12/framework/render/rendermodules/ui/uirendermodule.h>
#include <cauldron2/dx12/framework/render/rasterview.h>
#include <cauldron2/dx12/framework/render/dynamicresourcepool.h>
#include <cauldron2/dx12/framework/render/dx12/dynamicbufferpool_dx12.h>
#include <cauldron2/dx12/framework/render/dx12/parameterset_dx12.h>
#include <cauldron2/dx12/framework/render/dx12/pipelineobject_dx12.h>
#include <cauldron2/dx12/framework/render/dx12/rootsignaturedesc_dx12.h>
#include <cauldron2/dx12/framework/render/dx12/commandlist_dx12.h>
#include <cauldron2/dx12/framework/render/dx12/device_dx12.h>
#include <cauldron2/dx12/framework/render/dx12/swapchain_dx12.h>
#include <cauldron2/dx12/framework/render/dx12/resourceviewallocator_dx12.h>
#include <cauldron2/dx12/framework/core/backend_interface.h>
#include <cauldron2/dx12/framework/core/scene.h>
#include <cauldron2/dx12/framework/misc/assert.h>
#include <cauldron2/dx12/framework/render/profiler.h>
#include <cauldron2/dx12/rendermodules/translucency/translucencyrendermodule.h>
#include <cauldron2/dx12/framework/core/framework.h>
#include <cauldron2/dx12/framework/core/win/framework_win.h>
#include <cauldron2/dx12/framework/render/dx12/device_dx12.h>
#include <cauldron2/dx12/framework/render/dx12/commandlist_dx12.h>
#include <FidelityFX/api/include/dx12/ffx_api_dx12.hpp>
#include <FidelityFX/framegeneration/include/dx12/ffx_api_framegeneration_dx12.hpp>
#include <functional>
using namespace std;
using namespace cauldron;
void RestoreApplicationSwapChain(bool recreateSwapchain = true);
void FSRRenderModule::Init(const json& initData)
{
m_pTAARenderModule = static_cast<TAARenderModule*>(GetFramework()->GetRenderModule("TAARenderModule"));
m_pTransRenderModule = static_cast<TranslucencyRenderModule*>(GetFramework()->GetRenderModule("TranslucencyRenderModule"));
m_pToneMappingRenderModule = static_cast<ToneMappingRenderModule*>(GetFramework()->GetRenderModule("ToneMappingRenderModule"));
CauldronAssert(ASSERT_CRITICAL, m_pTAARenderModule, L"FidelityFX FSR Sample: Error: Could not find TAA render module.");
CauldronAssert(ASSERT_CRITICAL, m_pTransRenderModule, L"FidelityFX FSR Sample: Error: Could not find Translucency render module.");
CauldronAssert(ASSERT_CRITICAL, m_pToneMappingRenderModule, L"FidelityFX FSR Sample: Error: Could not find Tone Mapping render module.");
// Fetch needed resources
m_pColorTarget = GetFramework()->GetColorTargetForCallback(GetName());
m_pTonemappedColorTarget = GetFramework()->GetRenderTexture(L"SwapChainProxy");
m_pDepthTarget = GetFramework()->GetRenderTexture(L"DepthTarget");
m_pMotionVectors = GetFramework()->GetRenderTexture(L"GBufferMotionVectorRT");
m_pDistortionField[0] = GetFramework()->GetRenderTexture(L"DistortionField0");
m_pDistortionField[1] = GetFramework()->GetRenderTexture(L"DistortionField1");
m_pReactiveMask = GetFramework()->GetRenderTexture(L"ReactiveMask");
m_pCompositionMask = GetFramework()->GetRenderTexture(L"TransCompMask");
CauldronAssert(ASSERT_CRITICAL, m_pMotionVectors && m_pDistortionField[0] && m_pDistortionField[1] && m_pReactiveMask && m_pCompositionMask, L"Could not get one of the needed resources for FSR Rendermodule.");
m_pInterpolationOutput = GetFramework()->GetRenderTexture(L"InterpolationOutput");
// Get a CPU resource view that we'll use to map the render target to
GetResourceViewAllocator()->AllocateCPURenderViews(&m_pRTResourceView);
// Create render resolution opaque render target to use for auto-reactive mask generation
TextureDesc desc = m_pColorTarget->GetDesc();
const ResolutionInfo& resInfo = GetFramework()->GetResolutionInfo();
desc.Width = resInfo.RenderWidth;
desc.Height = resInfo.RenderHeight;
desc.Name = L"FSR_OpaqueTexture";
m_pOpaqueTexture = GetDynamicResourcePool()->CreateRenderTexture(&desc, [](TextureDesc& desc, uint32_t displayWidth, uint32_t displayHeight, uint32_t renderingWidth, uint32_t renderingHeight)
{
desc.Width = renderingWidth;
desc.Height = renderingHeight;
});
// Register additional exports for translucency pass
BlendDesc reactiveCompositionBlend = {
true, Blend::InvDstColor, Blend::One, BlendOp::Add, Blend::One, Blend::Zero, BlendOp::Add, static_cast<uint32_t>(ColorWriteMask::Red)};
OptionalTransparencyOptions transOptions;
transOptions.OptionalTargets.emplace_back(m_pReactiveMask, reactiveCompositionBlend);
transOptions.OptionalTargets.emplace_back(m_pCompositionMask, reactiveCompositionBlend);
transOptions.OptionalAdditionalOutputs = L"float ReactiveTarget : SV_TARGET1; float CompositionTarget : SV_TARGET2;";
transOptions.OptionalAdditionalExports =
L"float hasAnimatedTexture = 0.f; output.ReactiveTarget = ReactiveMask; output.CompositionTarget = max(Alpha, hasAnimatedTexture);";
// Add additional exports for FSR to translucency pass
m_pTransRenderModule->AddOptionalTransparencyOptions(transOptions);
// Create temporary texture to copy color into before upscale
{
TextureDesc desc = m_pColorTarget->GetDesc();
desc.Name = L"UpscaleIntermediateTarget";
desc.Width = m_pColorTarget->GetDesc().Width;
desc.Height = m_pColorTarget->GetDesc().Height;
m_pTempTexture = GetDynamicResourcePool()->CreateRenderTexture(
&desc, [](TextureDesc& desc, uint32_t displayWidth, uint32_t displayHeight, uint32_t renderingWidth, uint32_t renderingHeight) {
desc.Width = displayWidth;
desc.Height = displayHeight;
});
CauldronAssert(ASSERT_CRITICAL, m_pTempTexture, L"Couldn't create intermediate texture.");
}
// Create raster views on the reactive mask and composition masks (for clearing and rendering)
m_RasterViews.resize(2);
m_RasterViews[0] = GetRasterViewAllocator()->RequestRasterView(m_pReactiveMask, ViewDimension::Texture2D);
m_RasterViews[1] = GetRasterViewAllocator()->RequestRasterView(m_pCompositionMask, ViewDimension::Texture2D);
// Set our render resolution function as that to use during resize to get render width/height from display width/height
m_pUpdateFunc = [this](uint32_t displayWidth, uint32_t displayHeight) { return this->UpdateResolution(displayWidth, displayHeight); };
//////////////////////////////////////////////////////////////////////////
// Register additional execution callbacks during the frame
// Register a post-lighting callback to copy opaque texture
ExecuteCallback callbackPreTrans = [this](double deltaTime, CommandList* pCmdList) {
this->PreTransCallback(deltaTime, pCmdList);
};
ExecutionTuple callbackPreTransTuple = std::make_pair(L"FSRRenderModule::PreTransCallback", std::make_pair(this, callbackPreTrans));
GetFramework()->RegisterExecutionCallback(L"LightingRenderModule", false, callbackPreTransTuple);
// Register a post-transparency callback to generate reactive mask
ExecuteCallback callbackPostTrans = [this](double deltaTime, CommandList* pCmdList) {
this->PostTransCallback(deltaTime, pCmdList);
};
ExecutionTuple callbackPostTransTuple = std::make_pair(L"FSRRenderModule::PostTransCallback", std::make_pair(this, callbackPostTrans));
GetFramework()->RegisterExecutionCallback(L"TranslucencyRenderModule", false, callbackPostTransTuple);
m_curUiTextureIndex = 0;
// Get the proper UI color target
m_pUiTexture[0] = GetFramework()->GetRenderTexture(L"UITarget0");
m_pUiTexture[1] = GetFramework()->GetRenderTexture(L"UITarget1");
// Create FrameInterpolationSwapchain
// Separate from FSR generation so it can be done when the engine creates the swapchain
// should not be created and destroyed with FSR, as it requires a switch to windowed mode
m_FrameInterpolationAvailable = true;
m_AsyncComputeAvailable = true;
#if defined(FFX_API_VK)
// const cauldron::FIQueue* pAsyncComputeQueue = cauldron::GetDevice()->GetImpl()->GetFIAsyncComputeQueue();
// const cauldron::FIQueue* pPresentQueue = cauldron::GetDevice()->GetImpl()->GetFIPresentQueue();
// const cauldron::FIQueue* pImageAcquireQueue = cauldron::GetDevice()->GetImpl()->GetFIImageAcquireQueue();
//
// m_FrameInterpolationAvailable = pPresentQueue->queue != VK_NULL_HANDLE && pImageAcquireQueue->queue != VK_NULL_HANDLE;
// m_AsyncComputeAvailable = m_FrameInterpolationAvailable && pAsyncComputeQueue->queue != VK_NULL_HANDLE;
#endif //defined(FFX_API_VK)
if (!m_FrameInterpolationAvailable)
{
m_FrameInterpolation = false;
s_uiRenderMode = UICompositionMode::No_UI_Handling;
s_uiRenderModeNextFrame = UICompositionMode::No_UI_Handling;
CauldronWarning(L"Frame interpolation isn't available on this device.");
}
if (!m_AsyncComputeAvailable)
{
m_EnableAsyncCompute = false;
m_PendingEnableAsyncCompute = false;
m_AllowAsyncCompute = false;
CauldronWarning(L"Async compute Frame interpolation isn't available on this device.");
}
if (m_FrameInterpolationAvailable)
{
EnableFrameInterpolationSwapchain(true);
m_EnableFrameInterpolationSwapchain = true;
}
// Fetch hudless texture resources
m_pHudLessTexture[0] = GetFramework()->GetRenderTexture(L"HudlessTarget0");
m_pHudLessTexture[1] = GetFramework()->GetRenderTexture(L"HudlessTarget1");
// Start disabled as this will be enabled externally
cauldron::RenderModule::SetModuleEnabled(false);
{
// Register upscale method picker picker
UISection* uiSection = GetUIManager()->RegisterUIElements("Upscaling", UISectionType::Sample);
InitUI(uiSection);
}
//////////////////////////////////////////////////////////////////////////
// Finish up init
// That's all we need for now
SetModuleReady(true);
SwitchUpscaler(m_UiUpscaleMethod);
}
FSRRenderModule::~FSRRenderModule()
{
// Destroy the FSR context
UpdateFSRContext(false);
if (m_SwapChainContext != nullptr)
{
// Restore the application's swapchain
ffx::DestroyContext(m_SwapChainContext);
m_SwapChainContext = nullptr;
if(latencyWaitableObj)
{
CloseHandle(latencyWaitableObj);
latencyWaitableObj = 0;
}
RestoreApplicationSwapChain(false);
}
}
void FSRRenderModule::EnableModule(bool enabled)
{
// If disabling the render module, we need to disable the upscaler with the framework
if (!enabled)
{
// Toggle this now so we avoid the context changes in OnResize
SetModuleEnabled(enabled);
// Destroy the FSR context
UpdateFSRContext(false);
if (GetFramework()->UpscalerEnabled())
GetFramework()->EnableUpscaling(false);
if (GetFramework()->FrameInterpolationEnabled())
GetFramework()->EnableFrameInterpolation(false);
if (GetFramework()->IsSwapchainUsingFrameGenerationCallback())
GetFramework()->EnableSwapchainFrameGenerationCallback(false);
UIRenderModule* uimod = static_cast<UIRenderModule*>(GetFramework()->GetRenderModule("UIRenderModule"));
uimod->SetAsyncRender(false);
uimod->SetRenderToTexture(false);
uimod->SetCopyHudLessTexture(false);
CameraComponent::SetJitterCallbackFunc(nullptr);
}
else
{
UIRenderModule* uimod = static_cast<UIRenderModule*>(GetFramework()->GetRenderModule("UIRenderModule"));
uimod->SetAsyncRender(s_uiRenderMode == UICompositionMode::UiCallback);
uimod->SetRenderToTexture(s_uiRenderMode == UICompositionMode::UiTexture);
uimod->SetCopyHudLessTexture(s_uiRenderMode == UICompositionMode::PreUiBackbuffer);
// Setup everything needed when activating FSR
// Will also enable upscaling and FG in the framework
UpdatePreset(nullptr);
// Toggle this now so we avoid the context changes in OnResize
SetModuleEnabled(enabled);
// Create the FSR context
UpdateFSRContext(true);
if (m_UpscaleMethod == Upscaler_FSRAPI)
{
// Set the jitter callback to use
CameraJitterCallback jitterCallback = [this](Vec2& values) {
// Increment jitter index for frame
++m_JitterIndex;
// Update FSR jitter for built in TAA
const ResolutionInfo& resInfo = GetFramework()->GetResolutionInfo();
ffx::ReturnCode retCode;
int32_t jitterPhaseCount;
ffx::QueryDescUpscaleGetJitterPhaseCount getJitterPhaseDesc{};
getJitterPhaseDesc.displayWidth = resInfo.DisplayWidth;
getJitterPhaseDesc.renderWidth = resInfo.RenderWidth;
getJitterPhaseDesc.pOutPhaseCount = &jitterPhaseCount;
retCode = ffx::Query(m_UpscalingContext, getJitterPhaseDesc);
CauldronAssert(ASSERT_CRITICAL, retCode == ffx::ReturnCode::Ok,
L"ffxQuery(UpscalingContext,GETJITTERPHASECOUNT) returned %d", (uint32_t)retCode);
ffx::QueryDescUpscaleGetJitterOffset getJitterOffsetDesc{};
getJitterOffsetDesc.index = m_JitterIndex;
getJitterOffsetDesc.phaseCount = jitterPhaseCount;
getJitterOffsetDesc.pOutX = &m_JitterX;
getJitterOffsetDesc.pOutY = &m_JitterY;
retCode = ffx::Query(m_UpscalingContext, getJitterOffsetDesc);
CauldronAssert(ASSERT_CRITICAL, retCode == ffx::ReturnCode::Ok,
L"ffxQuery(UpscalingContext,FSR_GETJITTEROFFSET) returned %d", (uint32_t)retCode);
values = Vec2(-2.f * m_JitterX / resInfo.RenderWidth, 2.f * m_JitterY / resInfo.RenderHeight);
};
CameraComponent::SetJitterCallbackFunc(jitterCallback);
}
ClearReInit();
}
// Show or hide UI elements for active upscaler
for (auto& i : m_UIElements)
{
i->Show(enabled);
}
}
FfxErrorCode waitCallback(wchar_t* fenceName, uint64_t fenceValueToWaitFor)
{
CAUDRON_LOG_DEBUG(L"waiting on '%ls' with value %llu", fenceName, fenceValueToWaitFor);
return FFX_API_RETURN_OK;
}
void FSRRenderModule::InitUI(UISection* pUISection)
{
static const bool alwaysTrue = true;
std::vector<const char*> comboOptions = {"Native", "FSR (ffxapi)"};
pUISection->RegisterUIElement<UICombo>("Method", (int32_t&)m_UiUpscaleMethod, std::move(comboOptions), [this](int32_t cur, int32_t old) { SwitchUpscaler(cur); });
m_UIElements.emplace_back(
pUISection->RegisterUIElement<UICheckBox>("Override FSR Version", m_overrideVersion, [this](int32_t, int32_t) { m_NeedReInit = true; }, false));
// get FSR version info from ffxapi
{
struct ffxQueryDescGetVersions versionQuery = { 0 };
versionQuery.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS;
ffxReturnCode_t retCode_t;
versionQuery.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE;
versionQuery.device = GetDevice()->GetImpl()->DX12Device();
uint64_t versionCount = 0;
versionQuery.outputCount = &versionCount;
retCode_t = ffxQuery(nullptr, &versionQuery.header);
CauldronAssert(ASSERT_WARNING, retCode_t == FFX_API_RETURN_OK,
L"ffxQuery(nullptr,GetVersionsUpscaleCount) returned %d", retCode_t);
m_FsrVersionIds.resize(versionCount);
m_FsrVersionNames.resize(versionCount);
versionQuery.versionIds = m_FsrVersionIds.data();
versionQuery.versionNames = m_FsrVersionNames.data();
retCode_t = ffxQuery(nullptr, &versionQuery.header);
CauldronAssert(ASSERT_WARNING, retCode_t == FFX_API_RETURN_OK,
L"ffxQuery(nullptr,GetVersionsUpscaleIdsNames) returned %d", retCode_t);
}
ffx::CreateContextDescOverrideVersion versionOverride{};
ffx::QueryDescUpscaleGetResourceRequirements upscaleResourceRequirementsDesc{};
ffx::ReturnCode retCode;
for (size_t index = 0; index < m_FsrVersionIds.size(); index++)
{
versionOverride.versionId = m_FsrVersionIds[index];
retCode = ffx::Query(upscaleResourceRequirementsDesc, versionOverride);
CauldronAssert(ASSERT_WARNING, retCode == ffx::ReturnCode::Ok,
L"ffxQuery(nullptr,GetResourceRequirements,VersionOverride %S) returned %d", m_FsrVersionNames[index], (uint32_t)retCode);
CAUDRON_LOG_INFO(L"Upscaler %S: required_resources: %llu optional_resources: %llu",
m_FsrVersionNames[index], upscaleResourceRequirementsDesc.required_resources, upscaleResourceRequirementsDesc.optional_resources);
}
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>(
"FSR Version", (int32_t&)m_FsrVersionIndex, m_FsrVersionNames, m_overrideVersion, [this](int32_t, int32_t) { m_NeedReInit = true; }, false));
// Setup scale preset options
std::vector<const char*> presetComboOptions = { "Native AA (1.0x)", "Quality (1.5x)", "Balanced (1.7x)", "Performance (2x)", "Ultra Performance (3x)", "Custom", "Custom (DRS)" };
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>(
"Scale Preset", (int32_t&)m_ScalePreset, std::move(presetComboOptions), m_IsNonNative, [this](int32_t cur, int32_t old) { UpdatePreset(&old); }, false));
// Setup mip bias
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISlider<float>>(
"Mip LOD Bias",
m_MipBias,
-5.f, 0.f,
[this](float cur, float old) {
UpdateMipBias(&old);
},
false
));
// Setup scale factor (disabled for all but custom)
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISlider<float>>(
"Custom Scale",
m_UpscaleRatio,
1.f, 2.5f,
m_UpscaleRatioEnabled,
[this](float cur, float old) {
UpdateUpscaleRatio(&old);
},
false
));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISlider<float>>(
"Letterbox size", m_LetterboxRatio, 0.1f, 1.f, [this](float cur, float old) { UpdateUpscaleRatio(&old); }, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UIButton>("Reset Upscaling", [this]() { m_ResetUpscale = true; }));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Draw upscaler debug view", m_DrawUpscalerDebugView, nullptr, false));
// hint colorspace
std::vector<const char*> presetColorSpaceComboOptions = {
"Default (Linear)", "Assume Non-Linear", "Expect sRGB", "Expect PQ"};
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>(
"Upscale Color Space",
(int32_t&)m_colorSpace,
std::move(presetColorSpaceComboOptions),
m_EnableMaskOptions,
[this](int32_t cur, int32_t old) {
if (cur == 0 || cur == 1)
{
m_NeedReInit = true;
}
},
false));
// Reactive mask
std::vector<const char*> maskComboOptions{ "Disabled", "Manual Reactive Mask Generation", "Autogen FSR2 Helper Function" };
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>("Reactive Mask Mode", (int32_t&)m_MaskMode, std::move(maskComboOptions), m_EnableMaskOptions, nullptr, false));
// Use mask
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Use Transparency and Composition Mask", m_UseMask, m_EnableMaskOptions, nullptr, false));
// Sharpening
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("RCAS Sharpening", m_RCASSharpen, nullptr, false, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISlider<float>>("Sharpness", m_Sharpness, 0.f, 1.f, m_RCASSharpen, nullptr, false));
//Set Upscaler CB KeyValue post context creation
std::vector<const char*> configureUpscaleKeyLabels = { "fVelocity", "fReactivenessScale", "fShadingChangeScale", "fAccumulationAddedPerFrame", "fMinDisocclusionAccumulation"};
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>(
"Upscaler CB Key to set",
m_UpscalerCBKey,
configureUpscaleKeyLabels,
m_EnableMaskOptions,
[this](int32_t, int32_t) { m_UpscalerCBValue = m_UpscalerCBValueStore[m_UpscalerCBKey]; },
m_EnableMaskOptions));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISlider<float>>(
"Upscaler CB Value to set",
m_UpscalerCBValue,
-1.f, 2.f,
m_EnableMaskOptions,
[this](float, float) { m_UpscalerCBValueStore[m_UpscalerCBKey] = m_UpscalerCBValue; SetUpscaleConstantBuffer(m_UpscalerCBKey, m_UpscalerCBValue); },
m_EnableMaskOptions));
// Debug Checker
std::vector<const char*> debugMessageComboOptions{ "Disabled",
"Enabled. nullptr message callback. GLOBALDEBUG_LEVEL_SILENCE",
"Enabled. nullptr message callback. GLOBALDEBUG_LEVEL_ERRORS",
"Enabled. nullptr message callback. GLOBALDEBUG_LEVEL_WARNINGS",
"Enabled. Cauldron message callback. GLOBALDEBUG_LEVEL_SILENCE",
"Enabled. Cauldron message callback. GLOBALDEBUG_LEVEL_ERRORS",
"Enabled. Cauldron message callback. GLOBALDEBUG_LEVEL_WARNINGS"
};
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>("Debug Checker", (int32_t&)m_GlobalDebugCheckerMode, debugMessageComboOptions,
[this](int32_t nextVal, int32_t prevVal)
{
if ((prevVal == FSRDebugCheckerMode::Disabled && nextVal != FSRDebugCheckerMode::Disabled) || (prevVal != FSRDebugCheckerMode::Disabled && nextVal == FSRDebugCheckerMode::Disabled))
{
SetGlobalDebugCheckerMode(static_cast<FSRDebugCheckerMode> (nextVal), true);
}
else
{
SetGlobalDebugCheckerMode(static_cast<FSRDebugCheckerMode> (nextVal), false);
}
}));
// Frame interpolation
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISeparator>());
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Frame Interpolation", m_FrameInterpolation, m_FrameInterpolationAvailable,
[this](bool, bool)
{
m_OfUiEnabled = m_FrameInterpolation && s_enableSoftwareMotionEstimation;
// Ask main loop to re-initialize.
m_NeedReInit = true;
},
false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Frame Interpolation Swapchain", m_EnableFrameInterpolationSwapchain, m_FrameInterpolationAvailable,
[this](bool, bool)
{
m_OfUiEnabled = m_FrameInterpolation && s_enableSoftwareMotionEstimation;
s_uiRenderModeNextFrame = m_EnableFrameInterpolationSwapchain == false ? UICompositionMode::No_UI_Handling : s_uiRenderModeNextFrame; //if no proxy swapchain, then render UI directly to backbuffer for present
// Ask main loop to re-initialize.
m_NeedReInit = true;
},
false));
// get FG version info from ffxapi
{
struct ffxQueryDescGetVersions versionQuery = { 0 };
versionQuery.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS;
ffxReturnCode_t retCode_t;
versionQuery.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_FRAMEGENERATION;
versionQuery.device = GetDevice()->GetImpl()->DX12Device();
uint64_t versionCount = 0;
versionQuery.outputCount = &versionCount;
retCode_t = ffxQuery(nullptr, &versionQuery.header);
CauldronAssert(ASSERT_WARNING, retCode_t == FFX_API_RETURN_OK,
L"ffxQuery(nullptr,GetVersionsFGCount) returned %d", retCode_t);
m_FgVersionIds.resize(versionCount);
m_FgVersionNames.resize(versionCount);
versionQuery.versionIds = m_FgVersionIds.data();
versionQuery.versionNames = m_FgVersionNames.data();
retCode_t = ffxQuery(nullptr, &versionQuery.header);
CauldronAssert(ASSERT_WARNING, retCode_t == FFX_API_RETURN_OK,
L"ffxQuery(nullptr,GetVersionsFGIdsNames) returned %d", retCode_t);
m_currentFgContextVersion = m_FgVersionNames[m_FgVersionIndex];
m_FrameGenerationDebugViewEnabled = m_FrameInterpolation && m_currentFgContextVersion.major < 4;
}
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>(
"Frame Generation Version", (int32_t&)m_FgVersionIndex, m_FgVersionNames, m_overrideVersion, [this](int32_t next, int32_t prev)
{
m_currentFgContextVersion = m_FgVersionNames[next];
m_NeedReInit = true;
m_FrameGenerationDebugViewEnabled = m_FrameInterpolation && m_currentFgContextVersion.major < 4;
}, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Support Async Compute", m_PendingEnableAsyncCompute,
m_AsyncComputeAvailable,
[this](bool, bool)
{
// Ask main loop to re-initialize.
m_NeedReInit = true;
},
false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Allow async compute", m_AllowAsyncCompute, m_PendingEnableAsyncCompute, nullptr, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Use callback",
m_UseCallback,
m_FrameInterpolation,
[this](bool, bool)
{
GetFramework()->EnableSwapchainFrameGenerationCallback(m_UseCallback);
},
false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Use Distortion Field Input", m_UseDistortionField, m_FrameInterpolation, nullptr, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Draw frame generation tear lines", m_DrawFrameGenerationDebugTearLines, m_FrameInterpolation, nullptr, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Draw frame generation pacing lines", m_DrawFrameGenerationDebugPacingLines, m_FrameInterpolation, nullptr, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Draw frame generation reset indicators", m_DrawFrameGenerationDebugResetIndicators, m_FrameInterpolation, nullptr, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Draw frame generation debug view", m_DrawFrameGenerationDebugView, m_FrameGenerationDebugViewEnabled,nullptr,false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("Present interpolated only", m_PresentInterpolatedOnly, m_FrameInterpolation, nullptr, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UIButton>("Reset Frame Interpolation", m_FrameInterpolation, [this]() { m_ResetFrameInterpolation = true; }));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UIButton>("Simulate present skip", m_FrameInterpolation, [this]() { m_SimulatePresentSkip = true; }));
std::vector<const char*> uiRenderModeLabels = { "No UI handling (not recommended)", "UiTexture", "UiCallback", "Pre-Ui Backbuffer" };
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>(
"UI Composition Mode",
s_uiRenderModeNextFrame,
uiRenderModeLabels,
m_EnableFrameInterpolationSwapchain,
[this](int32_t, int32_t)
{
// Ask main loop to re-initialize at start of next frame. Next frame set s_uiRenderMode = s_uiRenderModeNextFrame.
m_NeedReInit = true;
},
false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>("DoubleBuffer UI resource in swapchain", m_DoublebufferInSwapchain, m_FrameInterpolation, nullptr, false));
std::vector<const char*> waitCallbackModeLabels = { "nullptr", "CAUDRON_LOG_DEBUG(\"waitCallback\")"};
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>(
"WaitCallback Mode",
m_waitCallbackMode,
waitCallbackModeLabels,
m_EnableWaitCallbackModeUI,
[this](int32_t, int32_t)
{
ffx::ConfigureDescFrameGenerationSwapChainKeyValueDX12 m_swapchainKeyValueConfig{};
#if defined(FFX_API_VK)
// ffx::ConfigureDescFrameGenerationSwapChainKeyValueVK m_swapchainKeyValueConfig{};
#endif //defined(FFX_API_VK)
m_swapchainKeyValueConfig.key = FFX_API_CONFIGURE_FG_SWAPCHAIN_KEY_WAITCALLBACK;
if (m_waitCallbackMode == 0)
{
m_swapchainKeyValueConfig.ptr = nullptr;
}
else if (m_waitCallbackMode == 1)
{
m_swapchainKeyValueConfig.ptr = waitCallback;
}
ffx::Configure(m_SwapChainContext, m_swapchainKeyValueConfig);
},
m_EnableMaskOptions));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISlider<float>>(
"Frame Pacing safetyMarginInMs",
m_SafetyMarginInMs,
0.0f, 1.0f,
m_FrameInterpolation,
[this](float, float) {
ffx::ConfigureDescFrameGenerationSwapChainKeyValueDX12 m_swapchainKeyValueConfig{};
#if defined(FFX_API_VK)
// ffx::ConfigureDescFrameGenerationSwapChainKeyValueVK m_swapchainKeyValueConfig{};
#endif //defined(FFX_API_VK)
m_swapchainKeyValueConfig.key = FFX_API_CONFIGURE_FG_SWAPCHAIN_KEY_FRAMEPACINGTUNING;
m_swapchainKeyValueConfig.ptr = &framePacingTuning;
framePacingTuning.safetyMarginInMs = m_SafetyMarginInMs;
ffx::Configure(m_SwapChainContext, m_swapchainKeyValueConfig);
},
m_FrameInterpolation));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISlider<float>>(
"Frame Pacing varianceFactor",
m_VarianceFactor,
0.0f, 1.0f,
m_FrameInterpolation,
[this](float, float) {
ffx::ConfigureDescFrameGenerationSwapChainKeyValueDX12 m_swapchainKeyValueConfig{};
#if defined(FFX_API_VK)
// ffx::ConfigureDescFrameGenerationSwapChainKeyValueVK m_swapchainKeyValueConfig{};
#endif //defined(FFX_API_VK)
m_swapchainKeyValueConfig.key = FFX_API_CONFIGURE_FG_SWAPCHAIN_KEY_FRAMEPACINGTUNING;
m_swapchainKeyValueConfig.ptr = &framePacingTuning;
framePacingTuning.varianceFactor = m_VarianceFactor;
ffx::Configure(m_SwapChainContext, m_swapchainKeyValueConfig);
},
m_FrameInterpolation));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>(
"Frame Pacing allowHybridSpin",
m_AllowHybridSpin,
m_FrameInterpolation,
[this](bool, bool) {
ffx::ConfigureDescFrameGenerationSwapChainKeyValueDX12 m_swapchainKeyValueConfig{};
#if defined(FFX_API_VK)
// ffx::ConfigureDescFrameGenerationSwapChainKeyValueVK m_swapchainKeyValueConfig{};
#endif //defined(FFX_API_VK)
m_swapchainKeyValueConfig.key = FFX_API_CONFIGURE_FG_SWAPCHAIN_KEY_FRAMEPACINGTUNING;
m_swapchainKeyValueConfig.ptr = &framePacingTuning;
framePacingTuning.allowHybridSpin = m_AllowHybridSpin;
ffx::Configure(m_SwapChainContext, m_swapchainKeyValueConfig);
}));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UISlider<int32_t>>(
"hybridSpinTime in timer resolution units",
(int32_t&) m_HybridSpinTime,
0, 10,
m_FrameInterpolation,
[this](int32_t, int32_t) {
ffx::ConfigureDescFrameGenerationSwapChainKeyValueDX12 m_swapchainKeyValueConfig{};
#if defined(FFX_API_VK)
// ffx::ConfigureDescFrameGenerationSwapChainKeyValueVK m_swapchainKeyValueConfig{};
#endif //defined(FFX_API_VK)
m_swapchainKeyValueConfig.key = FFX_API_CONFIGURE_FG_SWAPCHAIN_KEY_FRAMEPACINGTUNING;
m_swapchainKeyValueConfig.ptr = &framePacingTuning;
framePacingTuning.hybridSpinTime = m_HybridSpinTime;
ffx::Configure(m_SwapChainContext, m_swapchainKeyValueConfig);
},
m_FrameInterpolation));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>(
"allowWaitForSingleObjectOnFence",
m_AllowWaitForSingleObjectOnFence,
m_FrameInterpolation,
[this](bool, bool) {
ffx::ConfigureDescFrameGenerationSwapChainKeyValueDX12 m_swapchainKeyValueConfig{};
#if defined(FFX_API_VK)
// ffx::ConfigureDescFrameGenerationSwapChainKeyValueVK m_swapchainKeyValueConfig{};
#endif //defined(FFX_API_VK)
m_swapchainKeyValueConfig.key = FFX_API_CONFIGURE_FG_SWAPCHAIN_KEY_FRAMEPACINGTUNING;
m_swapchainKeyValueConfig.ptr = &framePacingTuning;
framePacingTuning.allowWaitForSingleObjectOnFence = m_AllowWaitForSingleObjectOnFence;
ffx::Configure(m_SwapChainContext, m_swapchainKeyValueConfig);
}));
// Camera animation options
std::vector<const char*> uiAnimationModesLabels = { "None", "Sinusoidal" /*, "Circle"*/ };
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICombo>(
"Camera animation mode", (int32_t&)m_CameraAnimationMode, uiAnimationModesLabels, m_FrameInterpolation,
[this](int32_t, int32_t)
{
auto pCamera = cauldron::GetScene()->GetCurrentCamera();
pCamera->SetAnimation(static_cast<CameraAnimation>(m_CameraAnimationMode),
static_cast<CameraAnimationRotationDirection>(m_ChangeCameraAnimationDirection), // there are only two directions, so use the bool directly
m_EnableCameraAnimationNoise);
}, false));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>(
"Change animation direction",
m_ChangeCameraAnimationDirection,
m_FrameInterpolation,
[this](bool, bool) {
auto pCamera = cauldron::GetScene()->GetCurrentCamera();
pCamera->SetAnimation(static_cast<CameraAnimation>(m_CameraAnimationMode),
static_cast<CameraAnimationRotationDirection>(m_ChangeCameraAnimationDirection), // there are only two directions, so use the bool directly
m_EnableCameraAnimationNoise);
}));
m_UIElements.emplace_back(pUISection->RegisterUIElement<UICheckBox>(
"Enable camera animation noise",
m_EnableCameraAnimationNoise,
m_FrameInterpolation,
[this](bool, bool) {
auto pCamera = cauldron::GetScene()->GetCurrentCamera();
pCamera->SetAnimation(static_cast<CameraAnimation>(m_CameraAnimationMode),
static_cast<CameraAnimationRotationDirection>(m_ChangeCameraAnimationDirection), // there are only two directions, so use the bool directly
m_EnableCameraAnimationNoise);
}));
EnableModule(true);
}
void FSRRenderModule::SwitchUpscaler(int32_t newUpscaler)
{
// Flush everything out of the pipe before disabling/enabling things
GetDevice()->FlushAllCommandQueues();
if (ModuleEnabled())
EnableModule(false);
// 0 = native, 1 = FFXAPI
SetFilter(newUpscaler);
switch (newUpscaler)
{
case 0:
m_pTAARenderModule->EnableModule(false);
m_pToneMappingRenderModule->EnableModule(true);
m_EnableMaskOptions = false;
break;
case 1:
ClearReInit();
// Also disable TAA render module
m_pTAARenderModule->EnableModule(false);
m_pToneMappingRenderModule->EnableModule(true);
m_EnableMaskOptions = true;
break;
default:
CauldronCritical(L"Unsupported upscaler requested.");
break;
}
m_EnableWaitCallbackModeUI = m_EnableMaskOptions && m_FrameInterpolationAvailable;
m_UpscaleMethod = newUpscaler;
// Enable the new one
EnableModule(true);
ClearReInit();
}
void FSRRenderModule::UpdatePreset(const int32_t* pOldPreset)
{
if ((pOldPreset && *pOldPreset == static_cast<int32_t>(FSRScalePreset::CustomDRS)) || m_ScalePreset == FSRScalePreset::CustomDRS)
{
m_NeedReInit = true;
}
switch (m_ScalePreset)
{
case FSRScalePreset::NativeAA:
m_UpscaleRatio = 1.0f;
break;
case FSRScalePreset::Quality:
m_UpscaleRatio = 1.5f;
break;
case FSRScalePreset::Balanced:
m_UpscaleRatio = 1.7f;
break;
case FSRScalePreset::Performance:
m_UpscaleRatio = 2.0f;
break;
case FSRScalePreset::UltraPerformance:
m_UpscaleRatio = 3.0f;
break;
case FSRScalePreset::CustomDRS:
case FSRScalePreset::Custom:
default:
// Leave the upscale ratio at whatever it was
break;
}
// Update whether we can update the custom scale slider
m_UpscaleRatioEnabled = (m_ScalePreset == FSRScalePreset::Custom || m_ScalePreset == FSRScalePreset::CustomDRS);
// Update mip bias
float oldValue = m_MipBias;
if (m_ScalePreset != FSRScalePreset::Custom && m_ScalePreset != FSRScalePreset::CustomDRS)
m_MipBias = cMipBias[static_cast<uint32_t>(m_ScalePreset)];
else
m_MipBias = m_MipBias = CalculateMipBias(m_UpscaleRatio);
UpdateMipBias(&oldValue);
// Update resolution since rendering ratios have changed
GetFramework()->EnableUpscaling(true, m_pUpdateFunc);
GetFramework()->EnableFrameInterpolation(m_FrameInterpolation);
GetFramework()->EnableSwapchainFrameGenerationCallback(m_UseCallback);
}
void FSRRenderModule::UpdateUpscaleRatio(const float* pOldRatio)
{
void* ffxSwapChain;
ffxSwapChain = GetSwapChain()->GetImpl()->DX12SwapChain();
#if defined(FFX_API_VK)
// ffxSwapChain = GetSwapChain()->GetImpl()->VKSwapChain();
#endif //defined(FFX_API_VK)
m_FrameGenerationConfig.frameGenerationEnabled = false;
m_FrameGenerationConfig.swapChain = ffxSwapChain;
m_FrameGenerationConfig.presentCallback = nullptr;
m_FrameGenerationConfig.HUDLessColor = FfxApiResource({});
auto retCode = ffx::Configure(m_FrameGenContext, m_FrameGenerationConfig);
CauldronAssert(ASSERT_CRITICAL, !!retCode, L"Configuring FSR FG before destroy failed: %d", (uint32_t)retCode);
// Disable/Enable FSR since resolution ratios have changed
GetFramework()->EnableUpscaling(true, m_pUpdateFunc);
}
void FSRRenderModule::UpdateMipBias(const float* pOldBias)
{
// Update the scene MipLODBias to use
GetScene()->SetMipLODBias(m_MipBias);
}
void FSRRenderModule::FfxMsgCallback(uint32_t type, const wchar_t* message)
{
if (type == FFX_API_MESSAGE_TYPE_ERROR)
{
CauldronError(L"FSR_API_DEBUG_ERROR: %ls", message);
}
else if (type == FFX_API_MESSAGE_TYPE_WARNING)
{
CauldronWarning(L"FSR_API_DEBUG_WARNING: %ls", message);
}
}
ffxReturnCode_t FSRRenderModule::UiCompositionCallback(ffxCallbackDescFrameGenerationPresent* params)
{
if (s_uiRenderMode != UICompositionMode::UiCallback)
return FFX_API_RETURN_ERROR_PARAMETER;
// Get a handle to the UIRenderModule for UI composition (only do this once as there's a search cost involved)
if (!m_pUIRenderModule)
{
m_pUIRenderModule = static_cast<UIRenderModule*>(GetFramework()->GetRenderModule("UIRenderModule"));
CauldronAssert(ASSERT_CRITICAL, m_pUIRenderModule, L"Could not get a handle to the UIRenderModule.");
}
// Wrap everything in cauldron wrappers to allow backend agnostic execution of UI render.
CommandList* pCmdList = CommandList::GetWrappedCmdListFromSDK(L"UI_CommandList", CommandQueue::Graphics, params->commandList);
SetAllResourceViewHeaps(pCmdList); // Set the resource view heaps to the wrapped command list
ResourceState rtResourceState = SDKWrapper::GetFrameworkState((FfxApiResourceState)params->outputSwapChainBuffer.state);
ResourceState bbResourceState = SDKWrapper::GetFrameworkState((FfxApiResourceState)params->currentBackBuffer.state);
TextureDesc rtDesc = SDKWrapper::GetFrameworkTextureDescription(params->outputSwapChainBuffer.description);
TextureDesc bbDesc = SDKWrapper::GetFrameworkTextureDescription(params->currentBackBuffer.description);
GPUResource* pRTResource = GPUResource::GetWrappedResourceFromSDK(L"UI_RenderTarget", params->outputSwapChainBuffer.resource, &rtDesc, rtResourceState);
GPUResource* pBBResource = GPUResource::GetWrappedResourceFromSDK(L"BackBuffer", params->currentBackBuffer.resource, &bbDesc, bbResourceState);
std::vector<Barrier> barriers;
barriers = {Barrier::Transition(pRTResource, rtResourceState, ResourceState::CopyDest),
Barrier::Transition(pBBResource, bbResourceState, ResourceState::CopySource)};
ResourceBarrier(pCmdList, (uint32_t)barriers.size(), barriers.data());
TextureCopyDesc copyDesc(pBBResource, pRTResource);
CopyTextureRegion(pCmdList, ©Desc);
barriers[0].SourceState = barriers[0].DestState;
barriers[0].DestState = ResourceState::RenderTargetResource;
swap(barriers[1].SourceState, barriers[1].DestState);
ResourceBarrier(pCmdList, (uint32_t)barriers.size(), barriers.data());
// Create and set RTV, required for async UI render.
FfxApiResourceDescription rdesc = params->outputSwapChainBuffer.description;
TextureDesc rtResourceDesc = TextureDesc::Tex2D(L"UI_RenderTarget",
SDKWrapper::GetFrameworkSurfaceFormat((FfxApiSurfaceFormat)rdesc.format),
rdesc.width,
rdesc.height,
rdesc.depth,
rdesc.mipCount,
ResourceFlags::AllowRenderTarget);
m_pRTResourceView->BindTextureResource(pRTResource, rtResourceDesc, ResourceViewType::RTV, ViewDimension::Texture2D, 0, 1, 0);
ResourceViewInfo viewInfo = m_pRTResourceView->GetViewInfo(0);
m_pUIRenderModule->ExecuteAsync(pCmdList, &viewInfo);
Barrier barrier = Barrier::Transition(pRTResource, ResourceState::RenderTargetResource, rtResourceState);
ResourceBarrier(pCmdList, 1, &barrier);
// Clean up wrapped resources for the frame
delete pBBResource;
delete pRTResource;
delete pCmdList;
return FFX_API_RETURN_OK;
}
void FSRRenderModule::UpdateFSRContext(bool enabled)
{
if (enabled)
{
const ResolutionInfo& resInfo = GetFramework()->GetResolutionInfo();
static bool s_InvertedDepth = GetConfig()->InvertedDepth;
// Backend creation (for both FFXAPI contexts, FG and Upscale)
ffx::CreateBackendDX12Desc backendDesc{};
backendDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_DX12;
backendDesc.device = GetDevice()->GetImpl()->DX12Device();
#if defined(FFX_API_VK)
// DeviceInternal *device = GetDevice()->GetImpl();
// ffx::CreateBackendVKDesc backendDesc{};
// backendDesc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK;
// backendDesc.vkDevice = device->VKDevice();
// backendDesc.vkPhysicalDevice = device->VKPhysicalDevice();
// backendDesc.vkDeviceProcAddr = vkGetDeviceProcAddr;
#endif //defined(FFX_API_VK)
if (m_UpscaleMethod == Upscaler_FSRAPI)
{
ffx::CreateContextDescUpscale createFsr{};
ffx::ReturnCode retCode;
ffxReturnCode_t retCode_t;
createFsr.maxRenderSize = {resInfo.RenderWidth, resInfo.RenderHeight};
createFsr.maxUpscaleSize = { resInfo.UpscaleWidth, resInfo.UpscaleHeight };
createFsr.flags = FFX_UPSCALE_ENABLE_AUTO_EXPOSURE;
createFsr.flags |= FFX_UPSCALE_ENABLE_DEBUG_VISUALIZATION;
if (m_ScalePreset == FSRScalePreset::CustomDRS)
{
createFsr.flags |= FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION;
}
if (s_InvertedDepth)
{
createFsr.flags |= FFX_UPSCALE_ENABLE_DEPTH_INVERTED | FFX_UPSCALE_ENABLE_DEPTH_INFINITE;
}
createFsr.flags |= FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE;
createFsr.flags |= m_colorSpace == FSRColorSpace::NonLinearColorSpace ? FFX_UPSCALE_ENABLE_NON_LINEAR_COLORSPACE : 0;
createFsr.fpMessage = nullptr;
if (m_GlobalDebugCheckerMode != FSRDebugCheckerMode::Disabled)
{
createFsr.flags |= FFX_UPSCALE_ENABLE_DEBUG_CHECKING;
}
// Create the FSR context
{
//Before creating any of FSR contexts, query VRAM size
struct FfxApiEffectMemoryUsage gpuMemoryUsageUpscaler = {0};
struct ffxQueryDescUpscaleGetGPUMemoryUsageV2 upscalerGetGPUMemoryUsageV2 = {0};
upscalerGetGPUMemoryUsageV2.header.type = FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2;
upscalerGetGPUMemoryUsageV2.device = GetDevice()->GetImpl()->DX12Device();
#if defined(FFX_API_VK)
//upscalerGetGPUMemoryUsageV2.device = GetDevice()->GetImpl()->VKDevice();
#endif //defined(FFX_API_VK)
upscalerGetGPUMemoryUsageV2.maxRenderSize = { resInfo.RenderWidth, resInfo.RenderHeight };
upscalerGetGPUMemoryUsageV2.maxUpscaleSize = { resInfo.UpscaleWidth, resInfo.UpscaleHeight };
upscalerGetGPUMemoryUsageV2.flags = createFsr.flags;
upscalerGetGPUMemoryUsageV2.gpuMemoryUsageUpscaler = &gpuMemoryUsageUpscaler;
ffx::CreateContextDescUpscaleVersion headerVersion = {};
headerVersion.version = FFX_UPSCALER_VERSION;
// lifetime of this must last until after CreateContext call!
struct ffxOverrideVersion versionOverride = {0};
versionOverride.header.type = FFX_API_DESC_TYPE_OVERRIDE_VERSION;
if (m_FsrVersionIndex < m_FsrVersionIds.size() && m_overrideVersion)
{
versionOverride.versionId = m_FsrVersionIds[m_FsrVersionIndex];
upscalerGetGPUMemoryUsageV2.header.pNext = &versionOverride.header;
retCode_t = ffxQuery(nullptr, &upscalerGetGPUMemoryUsageV2.header);
CauldronAssert(ASSERT_WARNING, retCode_t == FFX_API_RETURN_OK,
L"ffxQuery(nullptr,UpscaleGetGPUMemoryUsageV2, %S) returned %d", m_FsrVersionNames[m_FsrVersionIndex], retCode_t);
CAUDRON_LOG_INFO(L"Upscaler version %S Query GPUMemoryUsageV2 VRAM totalUsageInBytes %f MB aliasableUsageInBytes %f MB", m_FsrVersionNames[m_FsrVersionIndex], gpuMemoryUsageUpscaler.totalUsageInBytes / 1048576.f, gpuMemoryUsageUpscaler.aliasableUsageInBytes / 1048576.f);
retCode = ffx::CreateContext(m_UpscalingContext, nullptr, createFsr, backendDesc, headerVersion, versionOverride);
}
else
{
retCode = ffx::Query(upscalerGetGPUMemoryUsageV2);
CauldronAssert(ASSERT_WARNING, retCode == ffx::ReturnCode::Ok,
L"ffxQuery(nullptr,UpscaleGetGPUMemoryUsageV2) returned %d", (uint32_t)retCode);
CAUDRON_LOG_INFO(L"Default Upscaler Query GPUMemoryUsageV2 totalUsageInBytes %f MB aliasableUsageInBytes %f MB", gpuMemoryUsageUpscaler.totalUsageInBytes / 1048576.f, gpuMemoryUsageUpscaler.aliasableUsageInBytes / 1048576.f);
retCode = ffx::CreateContext(m_UpscalingContext, nullptr, createFsr, backendDesc, headerVersion);