-
Notifications
You must be signed in to change notification settings - Fork 10
/
Game.cpp
4705 lines (3974 loc) · 148 KB
/
Game.cpp
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
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#define versionString L"v0.970"
#pragma once
#include "pch.h"
#include "winioctl.h"
#include "ntddvdeo.h"
#include "dwmapi.h"
//#include "BasicMath.h"
#include "ColorSpaces.h"
#include "Game.h"
#define BRIGHTNESS_SLIDER_FACTOR (m_rawOutDesc.MaxLuminance / m_outputDesc.MaxLuminance)
#define G2G_LUMINANCE_BAR (995.f)
//using namespace concurrency;
using namespace winrt::Windows::Devices;
using namespace winrt::Windows::Devices::Display;
using namespace winrt::Windows::Devices::Enumeration;
void ACPipeline();
extern void ExitGame();
using namespace DirectX;
using Microsoft::WRL::ComPtr;
Game::Game(const wchar_t* appTitle)
{
m_appTitle = appTitle;
ConstructorInternal();
}
#define SQUARE_COUNT 10
void Game::ConstructorInternal()
{
if (!QueryPerformanceFrequency(&m_qpcFrequency)) // initialize clock frequency (of this machine)
{
throw std::exception("QueryPerformanceFrequency");
}
m_shiftKey = false; // Whether the shift key is pressed
m_pModeList = NULL; // ptr to list of display modes on this output.
m_numModes = 0;
m_logging = false; // start out not writing to a log file
m_mediaPresentDuration = 0; // Duration when using SwapChainMedia for hardware syncs.
// Units are in 0.1us or 100ns intervals. Zero 0 = off.
m_mediaVsyncCount = 1; // number of times to repeat the same frame for media playback
m_vTotalFixedSupported = false; // assume we don't support fixed V-Total mode
m_vTotalModeRequested = VTotalMode::Fixed; // default to try for PresentDuration mode
m_vTotalFixedApproved = false; // default to assuming it's not working
m_MPO = false; // assume no overlay plane initially
m_minFrameRate = 10; // fps these will be overridden by the detection logic.
m_maxFrameRate = 120;
m_minFrameRateOverride = 0; // so user can override OS values
m_maxFrameRateOverride = 0; // zero means do not override
m_FrameRateRatio = 1.0;
m_minDuration = 0; // min frame time for Fixed V-Total mode -default to 0 for adaptive only
m_maxDuration = 0; // max frame time for Fixed V-Total mode -default to 0 for adaptive only
m_autoResetAverageStatsCounts = MAXINT64;
m_connectionDescriptorKind = DisplayMonitorDescriptorKind::DisplayId;
m_color = 0.f; // black by default
m_currentTest = TestPattern::StartOfTest;
m_flickerRateIndex = 0; // select between min, max, etc for Flicker test 2
m_waveCounter = SQUARE_COUNT;
m_waveEnum = WaveEnum::ZigZag; // default 3
m_waveUp = true; // for use in zigzag wave 3
m_waveAngle = 0.; // how far along we are in the sine wave 3
m_waveInterval = 360; // duration of sine wave period in frames 3
m_frameRateMargin = 0.0; // keeps from getting too close to the limits 3
// parameters from DisplayID v2.1 to limit size of sudden changes in frame rate
m_SuccessiveFrameDurationIncreaseInterval = 50;
m_SuccessiveFrameDurationDecreaseInterval = 50;
m_latencyRateIndex = 0; // select between 60, 90, 120, 180, 240Hz for Latency tests 4
m_mediaRateIndex = 0; // select between 60, 90, 120, 180, 240Hz for Jitter 5
m_latencyTestFrameRate = 1; // Flag for default to max 4
m_sensorConnected = false; //
m_sensorNits = 27.0f; // threshold for detection by sensor in nits 4
m_sensing = false; //
m_flash = false; // whether we are flashing the photocell this frame 4
m_lastFlash = false; // whether last frame was a flash 4
m_lastLastFlash = false; // whether last frame was a flash 4
ResetSensorStats(); // initialize the sensor tracking data 4
AutoResetAverageStats(); // initialize the frame timing data
m_avgInputTime = 0.006; // hard coded at 6ms until dongle can drive input
#define USB_TIME (0.002) // time for 1 round trip on USB wire 2ms? 4
m_autoG2G = false; // if we are in automatic sequence mode 5
m_g2gFrom = true; // start with "From" color 5
m_g2gFromIndex = 0; // subtest for Gray To Gray test 5
m_g2gToIndex = 0; // subtest for Gray To Gray test 5
m_g2gFrameRate = 1; // flag for default to max 5
m_g2gCounter = 0; // counter for interval of gray periods 5
m_g2gInterval = 16; // default interval for G2G switching 5
numGtGValues = 5; //default 5x5 post toggleing 9x9
m_toggleG2gPattern5x5Or9x9 = false;
m_brightWarmup = false; // if we are using a brighter warmup and G2G 5
m_frameDropRateEnum = DropRateEnum::Max; // default to max 6
m_frameDropGamma = 1.; // used to balance brightness in square/random tests 6
m_frameLockRateIndex = 0; // select sutbtest for frameDrop test 7
m_MotionBlurIndex = maxMotionBlurs; // start with frame fraction 100% 8
m_motionBlurFrameRate = 60.; // 8
m_judderTestFrameRate = 1.; // flag for default to max 9
m_fAngle = 0; // angle of object moving around screen 8,9
m_tearingTestFrameRate = 1; // flag for default to max 0
m_sweepPos = 0; // position of bar in Tearing test 0
m_targetFrameRate = 60.f;
m_frameTime = 0.016667;
m_lastFrameTime = 0.016667;
m_sleepDelay = 16.0; // ms simulate workload of app (just used for some tests)
m_frameCount = 0; // number of frames in current stats
m_presentCount = 0; // number of Presents in current stats
m_frameCounter = 0; // frames rendered since swapchain creation
// m_presentCounter = 0; // frames presented since swapchain creation
m_totalTimeSinceStart = 0; // init clock since app start
m_paused = 0; // start out unpaused
m_fileCounter = 0; // next file name we can use
// map the storage into the pointer array
for (int i = 0; i < frameLogLength; i++)
{
m_frameEvents[i].clickCounts = 0;
m_frameEvents[i].readCounts = 0;
m_frameEvents[i].sleepCounts = 0;
m_frameEvents[i].updateCounts = 0;
m_frameEvents[i].drawCounts = 0;
m_frameEvents[i].presentCounts = 0;
m_frameEvents[i].syncCounts = 0;
m_frameEvents[i].photonCounts = 0;
m_frameLog[i] = &m_frameEvents[i];
}
m_currentProfileTile = 0; // which intensity profile tile we are on
m_maxPQCode = 1;
m_maxProfileTile = 1;
m_testingTier = TestingTier::DisplayHDR400;
m_outputDesc = { 0 };
m_rawOutDesc.MaxLuminance = 0.f;
m_rawOutDesc.MaxFullFrameLuminance = 0.f;
m_rawOutDesc.MinLuminance = 0.f;
m_showExplanatoryText = true;
m_deviceResources = std::make_unique<DX::DeviceResources>();
m_hideTextString = std::wstring(L"Press SPACE to hide this text.");
m_deviceResources->RegisterDeviceNotify(this);
}
// Shuffle all the entries in the frame log down to make room for one more
void Game::RotateFrameLog()
{
// swap the last pointer for after
FrameEvents* temp = m_frameLog[frameLogLength - 1];
// shuffle all the others down.
for (int i = frameLogLength - 1; i > 0; i--)
{
m_frameLog[i] = m_frameLog[i - 1];
}
// move last entry to front
m_frameLog[0] = temp;
// and clear it
m_frameLog[0]->frameID = 0;
m_frameLog[0]->presentID = 0;
m_frameLog[0]->clickCounts;
m_frameLog[0]->readCounts;
m_frameLog[0]->sleepCounts;
m_frameLog[0]->updateCounts;
m_frameLog[0]->drawCounts;
m_frameLog[0]->presentCounts;
m_frameLog[0]->syncCounts;
m_frameLog[0]->photonCounts;
}
// Initialize the Direct3D resources required to run.
void Game::Initialize(HWND window, int width, int height)
{
m_deviceResources->SetWindow(window, width, height);
m_deviceResources->CreateDeviceResources();
m_deviceResources->SetDpi(96.0f); // TODO: using default 96 DPI for now
m_deviceResources->CreateWindowSizeDependentResources();
CreateDeviceIndependentResources();
CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
void Game::ToggleG2gPattern5x5Or9x9()
{
if (!m_toggleG2gPattern5x5Or9x9) //value of m_toggleG2gPattern5x5Or9x9 true => 9x9 pattern false=>5x5 patter
{
m_toggleG2gPattern5x5Or9x9 = true;
numGtGValues = 9;
}
else
{
m_toggleG2gPattern5x5Or9x9 = false;
numGtGValues = 5;
}
}
enum Game::VTotalMode Game::GetVTotalMode()
{
return m_vTotalModeRequested;
}
// for UI to request a VTotal mode
void Game::ToggleVTotalMode()
{
if (m_vTotalModeRequested == VTotalMode::Adaptive)
{
m_vTotalModeRequested = VTotalMode::Fixed;
// tell deviceResources object so it can handle next swapchain resize properly TODO it probably has to be recreated...
m_deviceResources->SetVTotalMode(true);
}
else
{
m_vTotalModeRequested = VTotalMode::Adaptive;
// tell deviceResources object so it can handle next swapchain resize properly TODO it probably has to be recreated...
m_deviceResources->SetVTotalMode(false);
}
// clear the stats counters since we are changing policy
AutoResetAverageStats();
}
void Game::ToggleLogging()
{
if (!m_logging)
{
m_fileCounter++;
switch (m_currentTest)
{
// cases where a media oriented fixed-frame rate is best
case TestPattern::FlickerConstant: // 2
sprintf_s(m_logFileName, 999, "AdaptSyncTest2_FlickerConst%03d.csv", m_fileCounter);
break;
case TestPattern::FlickerVariable: // 3
sprintf_s(m_logFileName, 999, "AdaptSyncTest3_FlickerVar%03d.csv", m_fileCounter);
break;
case TestPattern::DisplayLatency: // 4
sprintf_s(m_logFileName, 999, "AdaptSyncTest4_Latency%03d.csv", m_fileCounter);
break;
case TestPattern::GrayToGray: // 5
sprintf_s(m_logFileName, 999, "AdaptSyncTest5_GrayToGray%03d.csv", m_fileCounter);
if (m_autoG2G)
{
sprintf_s(m_autoG2GLogFile, 999, "TimeMarkerGrayToGray%03d.csv", m_fileCounter);
}
break;
case TestPattern::FrameDrop: // 6
sprintf_s(m_logFileName, 999, "AdaptSyncTest6_Framedrop%03d.csv", m_fileCounter);
break;
case TestPattern::FrameLock: // 7
sprintf_s(m_logFileName, 999, "AdaptSyncTest7_Jitter%03d.csv", m_fileCounter);
break;
case TestPattern::MotionBlur: // 8
sprintf_s(m_logFileName, 999, "AdaptSyncTest8_Blur%03d.csv", m_fileCounter);
break;
case TestPattern::GameJudder: // 9
sprintf_s(m_logFileName, 999, "AdaptSyncTest9_Judder%03d.csv", m_fileCounter);
break;
case TestPattern::Tearing: // 0
sprintf_s(m_logFileName, 999, "AdaptSyncTest10_Tearing%03d.csv", m_fileCounter);
break;
default:
break;
}
// open log file
int err = 0;
err = fopen_s(&m_logFile, m_logFileName, "w");
fprintf_s(m_logFile, "Time, Mode, Target, Current, FrmStats, Brightness\n");
m_logTime = 0;
m_lastLogTime = 0;
if (m_autoG2G)
{
err = fopen_s(&m_logfile_AutoG2G, m_autoG2GLogFile, "w");
// fprintf_s(m_logfile_AutoG2G, "Mid Timestamp, Color, Frame Number, Total Frames\n");
}
m_logging = true;
}
else
{
fclose(m_logFile);
if (m_autoG2G)
{
fclose(m_logfile_AutoG2G);
}
m_logging = false;
}
}
void Game::ChangeMargin( INT32 increment )
{
if (increment > 0)
m_frameRateMargin += 0.1;
else
if ( increment < 0)
m_frameRateMargin -= 0.1;
m_frameRateMargin = clamp(m_frameRateMargin, 0.0, 2.0);
}
void Game::TogglePause()
{
m_paused = !m_paused;
}
void Game::ToggleSensing()
{
if (m_currentTest == TestPattern::DisplayLatency)
{
m_sensing = !m_sensing;
}
}
void Game::ToggleAutoG2G()
{
if (m_currentTest == TestPattern::GrayToGray)
{
m_autoG2G = !m_autoG2G; // automatic sequence mode 5
if (m_autoG2G == false)
{
m_g2gFromIndex = 0; // reset these on return to manual control
m_g2gToIndex = 0;
}
}
}
uint64_t myQPC()
{
static const uint64_t TicksPerSecond = 10000000; // microseconds
LARGE_INTEGER cycles, qpcFrequency;
QueryPerformanceFrequency(&qpcFrequency);
QueryPerformanceCounter(&cycles);
uint64_t r = cycles.QuadPart * TicksPerSecond;
return r;
}
void mySleep(double mseconds) // All routines named "sleep" must take milliseconds ms
{
LARGE_INTEGER qpcFrequency, counts; // args to system calls
uint64_t time, timeLimit; // 64b ints for intermediate checking
if (mseconds <= 0) // validate input
{
Sleep(0); // in case this is in a loop
return;
}
QueryPerformanceFrequency(&qpcFrequency); // get counts per second
QueryPerformanceCounter(&counts);
timeLimit = counts.QuadPart;
timeLimit += static_cast<uint64_t>((mseconds * static_cast<double>(qpcFrequency.QuadPart)) / 1000.0); // convert time limit from ms into counts
time = 0;
while (time < timeLimit)
{
Sleep(0); // cede control to OS for other processes
QueryPerformanceCounter(&counts);
time = counts.QuadPart;
}
}
INT64 getPerfCounts(void)
{
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
return time.QuadPart;
}
// clear all the stat tracking from the sensor
void Game::ResetSensorStats()
{
m_sensorCount = 0;
m_totalSensorTime = 0.;
m_totalSensorTime2 = 0.;
m_minSensorTime = 0.999999;
m_maxSensorTime = 0.;
}
void Game::ResetAverageStats()
{
m_frameCount = 1; // for stats on frames
m_totalFrameTime = m_lastFrameTime; // reset accumulator
m_totalFrameTime2 = m_lastFrameTime * m_lastFrameTime; // square of above used for variance math
m_totalRunningTime = 0.; // not sure we really ever want to reset this though...
m_totalRunningTime2 = 0.;
m_totalRenderTime = 0.;
m_totalRenderTime2 = 0.;
m_presentCount = 0; // for stats on Presents
m_totalPresentTime = 0.;
m_totalPresentTime2 = 0.;
m_minPresentTime = 1.;
m_maxPresentTime = 0.;
}
// this version is deferred so things settle down a bit first.
void Game::AutoResetAverageStats(void)
{
// start timer out at current QPC time
m_autoResetAverageStatsCounts = getPerfCounts();
}
// clears the accumulators for the current mode -bound to 's' key
// immediate, not deferrred.
void Game::ResetCurrentStats()
{
if (m_sensing)
ResetSensorStats();
else
ResetAverageStats();
}
// Returns whether the reported display metadata consists of
// default values generated by Windows.
bool Game::CheckForDefaults()
{
return (
// Default SDR display values (RS2)
(270.0f == m_rawOutDesc.MaxLuminance && 270.0f == m_rawOutDesc.MaxFullFrameLuminance && 0.5f == m_rawOutDesc.MinLuminance) ||
// Default HDR display values (RS2)
(550.0f == m_rawOutDesc.MaxLuminance && 450.0f == m_rawOutDesc.MaxFullFrameLuminance && 0.5f == m_rawOutDesc.MinLuminance) ||
// Default HDR display values (RS3)
(1499.0f == m_rawOutDesc.MaxLuminance && 799.0f == m_rawOutDesc.MaxFullFrameLuminance && 0.01f == m_rawOutDesc.MinLuminance));
}
// Default to tier based on what the EDID specified
Game::TestingTier Game::GetTestingTier()
{
#define SAFETY (0.970)
if (m_rawOutDesc.MaxLuminance >= SAFETY * 10000.0f)
return TestingTier::DisplayHDR10000;
else if (m_rawOutDesc.MaxLuminance >= SAFETY * 6000.0f)
return TestingTier::DisplayHDR6000;
else if (m_rawOutDesc.MaxLuminance >= SAFETY * 4000.0f)
return TestingTier::DisplayHDR4000;
else if (m_rawOutDesc.MaxLuminance >= SAFETY * 3000.0f)
return TestingTier::DisplayHDR3000;
else if (m_rawOutDesc.MaxLuminance >= SAFETY * 2000.0f)
return TestingTier::DisplayHDR2000;
else if (m_rawOutDesc.MaxLuminance >= SAFETY * 1400.0f)
return TestingTier::DisplayHDR1400;
else if (m_rawOutDesc.MaxLuminance >= SAFETY * 1000.0f)
return TestingTier::DisplayHDR1000;
else if (m_rawOutDesc.MaxLuminance >= SAFETY * 600.0f)
return TestingTier::DisplayHDR600;
else if (m_rawOutDesc.MaxLuminance >= SAFETY * 500.0f)
return TestingTier::DisplayHDR500;
else
return TestingTier::DisplayHDR400;
}
const wchar_t* Game::GetTierName(Game::TestingTier tier)
{
if (tier == DisplayHDR400)
return L"DisplayHDR400";
else if (tier == DisplayHDR500)
return L"DisplayHDR500";
else if (tier == DisplayHDR600)
return L"DisplayHDR600";
else if (tier == DisplayHDR1000)
return L"DisplayHDR1000";
else if (tier == DisplayHDR1400)
return L"DisplayHDR1400";
else if (tier == DisplayHDR2000)
return L"DisplayHDR2000";
else if (tier == DisplayHDR3000)
return L"DisplayHDR3000";
else if (tier == DisplayHDR4000)
return L"DisplayHDR4000";
else if (tier == DisplayHDR6000)
return L"DisplayHDR6000";
else if (tier == DisplayHDR10000)
return L"DisplayHDR10000";
else
return L"Unsupported DisplayHDR Tier";
}
float Game::GetTierLuminance(Game::TestingTier tier)
{
if (tier == DisplayHDR400)
return 400.f;
else if (tier == DisplayHDR500)
return 500.f;
else if (tier == DisplayHDR600)
return 600.f;
else if (tier == DisplayHDR1000)
return 1015.27f;
else if (tier == DisplayHDR1400)
return 1400.f;
else if (tier == DisplayHDR2000)
return 2000.f;
else if (tier == DisplayHDR3000)
return 3000.f;
else if (tier == DisplayHDR4000)
return 4000.f;
else if (tier == DisplayHDR6000)
return 6000.f;
else if (tier == DisplayHDR10000)
return 10000.f;
else
return -1.0f;
}
// Determines whether tearing support is available for fullscreen borderless windows.
void Game::CheckTearingSupport()
{
#ifndef PIXSUPPORT
ComPtr<IDXGIFactory6> factory;
HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory));
BOOL allowTearing = FALSE;
if (SUCCEEDED(hr))
{
hr = factory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing));
}
m_tearingSupport = SUCCEEDED(hr) && allowTearing;
#else
m_tearingSupport = TRUE;
#endif
}
#pragma region Frame Update
// Executes the basic game-style animation loop.
bool Game::isMedia()
{
switch (m_currentTest)
{
// cases where a media oriented fixed-frame rate is best
case TestPattern::FlickerConstant: // 2
case TestPattern::FrameDrop: // 6
case TestPattern::FrameLock: // 7
case TestPattern::MotionBlur: // 8
return true;
// cases where a game-oriented adaptive frame rate is best
case TestPattern::FlickerVariable: // 3
case TestPattern::DisplayLatency: // 4
case TestPattern::GrayToGray: // 5
case TestPattern::GameJudder: // 9
case TestPattern::Tearing: // 0
return false;
default:
return false;
}
}
HANDLE Game::GetFrameLatencyHandle()
{
return m_deviceResources->GetFrameLatencyHandle();
}
void Game::LogFrameStats()
{
// poll frame stats to see if we have newer data
auto sc = m_deviceResources->GetSwapChain();
DXGI_FRAME_STATISTICS frameStats;
sc->GetFrameStatistics(&frameStats);
// correct for case where framestats are from an older frame relative to current frameCounter
m_frameStatsLag = m_frameCounter - static_cast<uint64_t>(frameStats.PresentCount);
// m_frameStatsLag = 2;
if (m_frameStatsLag < 0) // clamp positive
m_frameStatsLag = 0;
if (m_frameStatsLag >= frameLogLength - 1) // clamp sane
m_frameStatsLag = frameLogLength - 1;
// update the log entry at the corresponding location
m_frameLog[m_frameStatsLag]->syncCounts = frameStats.SyncQPCTime.QuadPart;
m_frameLog[m_frameStatsLag]->presentID = frameStats.PresentCount;
}
// Tick method for use with photocell sensor
void Game::Tick()
{
HRESULT hr = 0;
// double frameTime; // local variable for comparison
double dFrequency = static_cast<double>(m_qpcFrequency.QuadPart); // counts per second of QPC
// Update with data from last frame
// get sync time of last frame from swapchain
auto sc = m_deviceResources->GetSwapChain();
DXGI_FRAME_STATISTICS frameStats;
sc->GetFrameStatistics(&frameStats);
m_frameLog[1]->syncCounts = frameStats.SyncQPCTime.QuadPart;
// this is from 2 frames ago since we havent rotated yet
// Compute a refresh rate for the actual monitor v-syncs
INT64 monCounts = getPerfCounts(); // get current time in QPC counts
double monDeltaT = (monCounts - m_lastMonCounts) / dFrequency; // see how long it's been
if (monDeltaT > 0.256) // if it's been over 1/4 second
{
uint monSyncs = frameStats.SyncRefreshCount; // get current QPC count of syncs/refreshes
uint monSyncDelta = monSyncs - static_cast<uint32_t>(m_lastMonSyncs); // how many syncs since last time
m_monitorSyncRate = (float)monSyncDelta / monDeltaT; // compute sync rate of panel
m_lastMonCounts = monCounts; // save state for next time
m_lastMonSyncs = monSyncs;
}
// also check the media stats that return an approved Present Duration
IDXGISwapChainMedia* scMedia;
DX::ThrowIfFailed(sc->QueryInterface(IID_PPV_ARGS(&scMedia)));
DXGI_FRAME_STATISTICS_MEDIA mediaStats = { 0 };
hr = scMedia->GetFrameStatisticsMedia(&mediaStats);
if (hr == S_OK && mediaStats.ApprovedPresentDuration != 0)
m_vTotalFixedApproved = true;
else
m_vTotalFixedApproved = false;
// set photon time to be a bit after sync time until we have hardware event
m_frameLog[0]->photonCounts = m_frameLog[0]->syncCounts + 100000; // assume 10ms of GtG, etc.
m_frameCounter++; // new frame id
if (!m_paused)
{
if (m_sensing)
{
m_lastLastFlash = m_lastFlash; // lagged from 2 frames ago
m_lastFlash = m_flash; // lagged from previous frame
m_flash = (m_frameCounter % 4) == 0; // only flash 1 of every 4 frames
#if 0
// if there should be a flash this frame, reconnect the sensor (should not be required every frame)
if (m_flash)
{
// make sure we are still connected (should never happen in real life)
if (!m_sensorConnected)
{
m_sensorConnected = m_sensor.ConnectSensor();
}
}
#endif
// advance printout columns to current frame
RotateFrameLog(); // make room to store this latest data
// m_frameLog[0]->frameID = m_frameCounter; // log the frame ID
// log time when app starts a frame
m_frameLog[0]->readCounts = getPerfCounts();
// Don't bother to sleep during sensing
// model app workload by sleeping that many ms
// mySleep(sleepDelay);
Update(); // actually do some CPU stuff
// log when drawing starts on the GPU
// m_frameLog[0]->drawCounts = getPerfCounts();
// Draw
Render(); // this is before we have all values for this frame
// if there should be a flash this frame, start measuring
uint64_t sensorCountsStart;
if (m_flash)
{
m_sensor.StartLatencyMeasurement(LatencyType_Immediate);
sensorCountsStart = getPerfCounts();
}
UNREFERENCED_PARAMETER(sensorCountsStart);
// log time when app calls Present()
m_frameLog[0]->presentCounts = getPerfCounts();
// Show the new frame
// UINT syncInterval = 0;
// UINT presentFlags;
if (m_mediaPresentDuration != 0
)
{
hr = m_deviceResources->Present(m_mediaVsyncCount, DXGI_PRESENT_USE_DURATION);
}
else
{
hr = m_deviceResources->Present(0, 0); // default is V-Sync enabled, not tearing
}
// if this was a frame that included a flash, then read the photocell's measurement
if (m_flash)
{
// time from start of latency measurement sensor in sec
m_sensorTime = m_sensor.ReadLatency(); // blocking call
// get own estimate of sensorTime based on QPC
auto sensorCountsEnd = getPerfCounts();
UNREFERENCED_PARAMETER(sensorCountsEnd);
// m_sensorTime = (sensorCountsEnd - sensorCountsStart) / dFrequency;
if ((m_sensorTime > 0.001) && (m_sensorTime < 0.100)) // if valid, run the stats on it
{
// total it up for computing the average and variance
m_totalSensorTime += m_sensorTime;
m_totalSensorTime2 += (double)m_sensorTime * m_sensorTime;
m_sensorCount++;
// scan for min
if (m_sensorTime < m_minSensorTime)
m_minSensorTime = m_sensorTime;
// scan for max
if (m_sensorTime > m_maxSensorTime)
m_maxSensorTime = m_sensorTime;
}
}
// else // we are not flashing so just wait for the flip queue to update with the black frame
// make sure each frame lasts long enough for the sensor to detect it.
Sleep(2);
m_lastFrameTime = m_frameTime;
m_frameTime = (m_frameLog[0]->readCounts - m_lastReadCounts) / dFrequency;
m_lastReadCounts = m_frameLog[0]->readCounts;
}
else // we are not using the sensor, just track in-PC timings
{
// m_flash = m_frameCounter & 1; // switch every other frame
// m_flash = (m_frameCounter >> 1) & 1; // switch every 2 frames
m_flash = (m_frameCounter >> 2) & 1; // switch every 4 frames
// advance to current frame
RotateFrameLog(); // make room to store this latest data
m_frameLog[0]->frameID = m_frameCounter; // log the frame ID
// Read input events()
// log time when the button was clicked -extract the click time stamp
// log time when photocell was hit -extract the photon time stamp
// log time when the camera image flashed -extract the camera result time stamp
// log time when app starts a frame
m_frameLog[0]->readCounts = getPerfCounts();
// simulate input device click that occurred before we read it.
int64_t inputCounts = static_cast<int64_t>(m_avgInputTime * dFrequency);
m_frameLog[0]->clickCounts = m_frameLog[0]->readCounts - inputCounts;
// TODO: FrameTime should not be a member var
// default to no app frame-doubling
m_mediaVsyncCount = 1;
// use PresentDuration mode in some tests
UINT closestSmallerDuration = 0, closestLargerDuration = 0;
if (m_vTotalFixedSupported && (
m_currentTest == TestPattern::FlickerConstant // 2
|| m_currentTest == TestPattern::DisplayLatency // 4
|| m_currentTest == TestPattern::FrameLock // 7
|| m_currentTest == TestPattern::MotionBlur)) // 8
{
m_mediaVsyncCount = 1;
// for fixed presentation time , find the number of frames to duplicate to get in the range
if (m_targetFrameTime != 0)
{
INT64 tempDuration = (INT64)(10000000.0 * m_targetFrameTime);
while (tempDuration > m_maxDuration)
{
m_mediaVsyncCount++;
tempDuration = (INT64)(10000000.0 * m_targetFrameTime / m_mediaVsyncCount);
}
}
m_mediaPresentDuration = (INT64)(10000000.0 * m_targetFrameTime / m_mediaVsyncCount);
if (m_mediaPresentDuration > 0)
{
// confirm that this rate is actually supported
hr = scMedia->CheckPresentDurationSupport(
static_cast<uint32_t>(m_mediaPresentDuration), &closestSmallerDuration, &closestLargerDuration);
// Check that one of the neighboring Durations matches our goal
if (hr == S_OK && (m_mediaPresentDuration == closestLargerDuration || m_mediaPresentDuration == closestSmallerDuration))
{
// then the rate is valid and we can set it
hr = scMedia->SetPresentDuration(static_cast<uint32_t>(m_mediaPresentDuration));
if (hr != S_OK)
{
m_mediaPresentDuration = 0;
}
}
else
{
// PresentDuration is not to be used
m_mediaPresentDuration = 0;
}
}
}
else
{
// PresentDuration is not to be used
m_mediaPresentDuration = 0;
}
hr = scMedia->GetFrameStatisticsMedia(&mediaStats);
if (hr == S_OK && m_mediaPresentDuration > 0)
{
// we can use the wait model so indicate on UI
m_frameLog[0]->sleepCounts = getPerfCounts();
}
else // use a sleep timer
{
m_vTotalFixedApproved = false;
// if we didnt get PresentDuration mode, maybe we got an MPO:
m_MPO = false;
if (m_vTotalFixedSupported && m_vTotalFixedApproved)
{
scMedia->SetPresentDuration(0);
}
if (mediaStats.CompositionMode == DXGI_FRAME_PRESENTATION_MODE_OVERLAY)
{
m_MPO = true;
}
double avgRunTime; // how long the app spends not sleeping
m_mediaPresentDuration = 0; // indicate to not use PresentDuration model
if (m_frameCount > 1)
avgRunTime = m_totalRunningTime / m_frameCount;
else
avgRunTime = 0.0013; // aka 1.3ms
// apply frame doubling if frame rate is less than EDID reported minimum
double targetFrameTime = m_targetFrameTime;
double maxFrameTime = 1.001 / m_minFrameRate; // as repotted by EDID
if (targetFrameTime > maxFrameTime)
{
targetFrameTime /= 2.0; // halve the period to double the frame rate
m_mediaVsyncCount = 2;
}
// if still to slow, then
if (targetFrameTime > maxFrameTime)
{
targetFrameTime /= 1.5; // triple the frame rate
m_mediaVsyncCount = 3;
}
// if still to slow, then
if (targetFrameTime > maxFrameTime)
{
targetFrameTime /= 1.333333333; // quadruple the frame rate
m_mediaVsyncCount = 4;
}
// don't worry too much about precision here as software loop is sloppy anyway.
// compute how much of frame time to sleep by subtracting time running CPU/GPU
m_sleepDelay = 1000.0 * (targetFrameTime - avgRunTime);
// Hopefully set correct duration for this frame by sleeping enough
m_frameLog[0]->sleepCounts = getPerfCounts();
mySleep(m_sleepDelay);
}
// log when app logic starts on the GPU
m_frameLog[0]->updateCounts = getPerfCounts();
Update(); // actually do some CPU workload stuff
// log when drawing starts on the GPU
m_frameLog[0]->drawCounts = getPerfCounts();
// Draw()
Render(); // update screen (before we have all values for this frame)
// log time when app calls Present()
m_frameLog[0]->presentCounts = getPerfCounts();
// Call Present() to show the new frame
if (m_mediaPresentDuration != 0
)
{
hr = m_deviceResources->Present(m_mediaVsyncCount, DXGI_PRESENT_USE_DURATION);
}
else
{
hr = m_deviceResources->Present(0, 0); // default is V-Sync enabled
}
// log time when vsync happens on display
// m_frameLog[0]->syncCounts = presentCounts; // clear this as we don't know until next frame
// log time when photons arrive at photocell
// m_frameLog[0]->photonCounts = presentCounts; // clear this as we don't know until next frame
// track frame time for frame rate
m_lastFrameTime = m_frameTime;
m_frameTime = (m_frameLog[0]->readCounts - m_lastReadCounts) / dFrequency;
m_lastReadCounts = m_frameLog[0]->readCounts;
// if valid data
if ((m_frameTime > 0.001) && (m_frameTime < 0.100)) // run the stats on it
{
m_frameCount++; // frames we average over
// accumulate time for computing the averages
m_totalFrameTime += m_frameTime;
m_totalFrameTime2 += m_frameTime * m_frameTime;
#if 0
// scan for min
if (m_frameTime < m_minLatency)
m_minLatency = m_frameTime;
// scan for max
if (m_frameTime > m_maxLatency)
m_maxLatency = m_frameTime;
#endif
// accumulate Running time for computing Average and Variance
double sleepTime = (m_frameLog[0]->updateCounts - m_frameLog[0]->sleepCounts) / dFrequency;
double runningTime = m_frameTime - sleepTime; // all the time last frame not sleeping
m_totalRunningTime += runningTime;
m_totalRunningTime2 += runningTime * runningTime;
// accumulate Render time for computing Average
double renderTime = (m_frameLog[0]->presentCounts - m_frameLog[0]->drawCounts) / dFrequency;
m_totalRenderTime += renderTime;
m_totalRenderTime2 += renderTime * renderTime;
// accumulate Present time for computing Average
double presentTime = (m_frameLog[2]->syncCounts - m_frameLog[2]->presentCounts) / dFrequency;
m_totalPresentTime += presentTime;
m_totalPresentTime2 += presentTime * presentTime;
}
else
{
float x = 1.f; // this line just for setting a breakpoint on
UNREFERENCED_PARAMETER(x);
}
}
}
else
{
Sleep(15); // update at ~60Hz even when paused.
// save for use next frame
}
// track data since app startup
m_totalTimeSinceStart += m_frameTime; // TODO totalTime should not be a double but a uint64 in microseconds
m_lastLogTime = m_logTime; // save last value
m_logTime += m_frameTime; // time since logging started
// run timer that delays average stats reset by 1/4 second after each (sub)test change:
INT64 nowCounts = getPerfCounts(); // get current time in QPC counts