aboutsummaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/CAPI/CAPI_HMDState.cpp
blob: fd98225fa4306dd5efaa2f3655b8249629924d6f (plain)
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
/************************************************************************************

Filename    :   CAPI_HMDState.cpp
Content     :   State associated with a single HMD
Created     :   January 24, 2014
Authors     :   Michael Antonov

Copyright   :   Copyright 2014 Oculus VR, Inc. All Rights reserved.

Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License"); 
you may not use the Oculus VR Rift SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.1 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

************************************************************************************/

#include "CAPI_HMDState.h"
#include "CAPI_GlobalState.h"
#include "../OVR_Profile.h"

namespace OVR { namespace CAPI {

//-------------------------------------------------------------------------------------
// ***** HMDState


HMDState::HMDState(HMDDevice* device)
    : pHMD(device), HMDInfoW(device), HMDInfo(HMDInfoW.h),    
      EnabledHmdCaps(0), HmdCapsAppliedToSensor(0),
      SensorStarted(0), SensorCreated(0), SensorCaps(0),
      AddSensorCount(0), AddLatencyTestCount(0), AddLatencyTestDisplayCount(0),
      RenderState(getThis(), pHMD->GetProfile(), HMDInfoW.h),
      LastFrameTimeSeconds(0.0f), LastGetFrameTimeSeconds(0.0),
      LatencyTestActive(false),
      LatencyTest2Active(false)
{
    pLastError = 0;
    GlobalState::pInstance->AddHMD(this);
    
    // Should be in renderer?
    TimeManager.Init(RenderState.RenderInfo);

    EyeRenderActive[0] = false;
    EyeRenderActive[1] = false;

    LatencyTestDrawColor[0] = 0;
    LatencyTestDrawColor[1] = 0;
    LatencyTestDrawColor[2] = 0;

    OVR_CAPI_VISION_CODE( pPoseTracker = 0; )

    RenderingConfigured = false;
    BeginFrameCalled    = false;
    BeginFrameThreadId  = 0;
    BeginFrameTimingCalled = false;
}

HMDState::HMDState(ovrHmdType hmdType)
  : pHMD(0), HMDInfoW(hmdType), HMDInfo(HMDInfoW.h),
    EnabledHmdCaps(0),
    SensorStarted(0), SensorCreated(0), SensorCaps(0),
    AddSensorCount(0), AddLatencyTestCount(0), AddLatencyTestDisplayCount(0),
    RenderState(getThis(), 0, HMDInfoW.h), // No profile. 
    LastFrameTimeSeconds(0.0), LastGetFrameTimeSeconds(0.0)
{
    // TBD: We should probably be looking up the default profile for the given
    // device type + user.

    pLastError = 0;
    GlobalState::pInstance->AddHMD(this);

    // Should be in renderer?
    TimeManager.Init(RenderState.RenderInfo);

    EyeRenderActive[0] = false;
    EyeRenderActive[1] = false;

    OVR_CAPI_VISION_CODE( pPoseTracker = 0; )

    RenderingConfigured = false;
    BeginFrameCalled   = false;
    BeginFrameThreadId = 0;
    BeginFrameTimingCalled = false;
}


HMDState::~HMDState()
{
    OVR_ASSERT(GlobalState::pInstance);
   
    StopSensor();
    ConfigureRendering(0,0,0,0);

    OVR_CAPI_VISION_CODE( OVR_ASSERT(pPoseTracker == 0); )

    GlobalState::pInstance->RemoveHMD(this);
}



//-------------------------------------------------------------------------------------
// *** Sensor 

bool HMDState::StartSensor(unsigned supportedCaps, unsigned requiredCaps)
{
    Lock::Locker lockScope(&DevicesLock);

    bool crystalCoveOrBetter = (HMDInfo.HmdType == HmdType_CrystalCoveProto) ||
                               (HMDInfo.HmdType == HmdType_DK2);
    bool sensorCreatedJustNow = false;

    // TBD: In case of sensor not being immediately available, it would be good to check
    //      yaw config availability to match it with ovrHmdCap_YawCorrection requirement.
    // 

    if (!crystalCoveOrBetter)
    {
        if (requiredCaps & ovrSensorCap_Position)
        {
            pLastError = "ovrSensorCap_Position not supported on this HMD.";
            return false;            
        }
    }

    supportedCaps |= requiredCaps;

    if (pHMD && !pSensor)
    {
        // Zero AddSensorCount before creation, in case it fails (or succeeds but then
        // immediately gets disconnected) followed by another Add notification.        
        AddSensorCount      = 0;
        pSensor             = *pHMD->GetSensor();
        sensorCreatedJustNow= true;

        if (pSensor)
        {
            pSensor->SetReportRate(500);
            SFusion.AttachToSensor(pSensor);
            applyProfileToSensorFusion();
        }
        else
        {
            if (requiredCaps & ovrSensorCap_Orientation)
            {
                pLastError = "Failed to create sensor.";
                return false;
            }
        }
    }


    if ((requiredCaps & ovrSensorCap_YawCorrection) && !pSensor->IsMagCalibrated())
    {
        pLastError = "ovrHmdCap_YawCorrection not available.";
        if (sensorCreatedJustNow)
        {
            SFusion.AttachToSensor(0);
            SFusion.Reset();
            pSensor.Clear();
        }
        return false;
    }        

    SFusion.SetYawCorrectionEnabled((supportedCaps & ovrSensorCap_YawCorrection) != 0);

    if (pSensor && sensorCreatedJustNow)
    {
        LogText("Sensor created.\n");
        SensorCreated = true;
    }

    updateDK2FeaturesTiedToSensor(sensorCreatedJustNow);    
    

#ifdef OVR_CAPI_VISIONSUPPORT

    if (crystalCoveOrBetter && (supportedCaps & ovrSensorCap_Position))
    {
        if (!pPoseTracker)
        {
            pPoseTracker = new Vision::PoseTracker(SFusion);
            if (pPoseTracker)
            {
                pPoseTracker->AssociateHMD(pSensor);
                LogText("Sensor Pose tracker created.\n");
            }
        }

        // TBD: How do we verify that position tracking is actually available
        //      i.e. camera is plugged in?
    }
    else if (pPoseTracker)
    {
        // TBD: Internals not thread safe - must fix!!
        delete pPoseTracker;
        pPoseTracker = 0;
        LogText("Sensor Pose tracker destroyed.\n");
    }

#endif // OVR_CAPI_VISIONSUPPORT

    SensorCaps    = supportedCaps;
    SensorStarted = true;

    return true;
}


// Stops sensor sampling, shutting down internal resources.
void HMDState::StopSensor()
{
    Lock::Locker lockScope(&DevicesLock);

    if (SensorStarted)
    {
#ifdef OVR_CAPI_VISIONSUPPORT
        if (pPoseTracker)
        {
            // TBD: Internals not thread safe - must fix!!
            delete pPoseTracker;
            pPoseTracker = 0;
            LogText("Sensor Pose tracker destroyed.\n");
        }        
#endif // OVR_CAPI_VISION_CODE

        SFusion.AttachToSensor(0);
        SFusion.Reset();
        pSensor.Clear();
        HmdCapsAppliedToSensor = 0;
        AddSensorCount = 0;
        SensorCaps     = 0;
        SensorCreated  = false;
        SensorStarted  = false;

        LogText("StopSensor succeeded.\n");
    }
}

// Resets sensor orientation.
void HMDState::ResetSensor()
{
    SFusion.Reset();
}


// Returns prediction for time.
ovrSensorState HMDState::PredictedSensorState(double absTime)
{    
    SensorState ss;

    // We are trying to keep this path lockless unless we are notified of new device
    // creation while not having a sensor yet. It's ok to check SensorCreated volatile
    // flag here, since GetSensorStateAtTime() is internally lockless and safe.

    if (SensorCreated || checkCreateSensor())
    {   
        ss = SFusion.GetSensorStateAtTime(absTime);

        if (!(ss.StatusFlags & ovrStatus_OrientationTracked))
        {
            Lock::Locker lockScope(&DevicesLock);

#ifdef OVR_CAPI_VISIONSUPPORT
            if (pPoseTracker)
            {
                // TBD: Internals not thread safe - must fix!!
                delete pPoseTracker;
                pPoseTracker = 0;
                LogText("Sensor Pose tracker destroyed.\n");
            }        
#endif // OVR_CAPI_VISION_CODE
            // Not needed yet; SFusion.AttachToSensor(0);
            // This seems to reset orientation anyway...
            pSensor.Clear();
            SensorCreated = false;         
            HmdCapsAppliedToSensor = 0;
        }
    }
    else
    {
        // SensorState() defaults to 0s.
        // ss.Pose.Orientation       = Quatf();
        // ..

        // John:
        // We still want valid times so frames will get a delta-time
        // and allow operation with a joypad when the sensor isn't
        // connected.
        ss.Recorded.TimeInSeconds  = absTime;
        ss.Predicted.TimeInSeconds = absTime;
    }

    ss.StatusFlags |= ovrStatus_HmdConnected;
    return ss;
}


bool  HMDState::checkCreateSensor()
{
    if (!(SensorStarted && !SensorCreated && AddSensorCount))
        return false;

    Lock::Locker lockScope(&DevicesLock);

    // Re-check condition once in the lock, in case the state changed.
    if (SensorStarted && !SensorCreated && AddSensorCount)
    {        
        if (pHMD)
        {
            AddSensorCount = 0;
            pSensor        = *pHMD->GetSensor();
        }

        if (pSensor)
        {
            pSensor->SetReportRate(500);
            SFusion.AttachToSensor(pSensor);
            SFusion.SetYawCorrectionEnabled((SensorCaps & ovrSensorCap_YawCorrection) != 0);
            applyProfileToSensorFusion();

#ifdef OVR_CAPI_VISIONSUPPORT
            if (SensorCaps & ovrSensorCap_Position)
            {
                pPoseTracker = new Vision::PoseTracker(SFusion);
                if (pPoseTracker)
                {
                    pPoseTracker->AssociateHMD(pSensor);
                }
                LogText("Sensor Pose tracker created.\n");
            }
#endif // OVR_CAPI_VISION_CODE

            LogText("Sensor created.\n");

            SensorCreated = true;
            return true;
        }
    }

    return SensorCreated;
}

bool HMDState::GetSensorDesc(ovrSensorDesc* descOut)
{
    Lock::Locker lockScope(&DevicesLock);

    if (SensorCreated)
    {
        OVR_ASSERT(pSensor);
        OVR::SensorInfo si;
        pSensor->GetDeviceInfo(&si);
        descOut->VendorId  = si.VendorId;
        descOut->ProductId = si.ProductId;
        OVR_ASSERT(si.SerialNumber.GetSize() <= sizeof(descOut->SerialNumber));
        OVR_strcpy(descOut->SerialNumber, sizeof(descOut->SerialNumber), si.SerialNumber.ToCStr());
        return true;
    }
    return false;
}


void HMDState::applyProfileToSensorFusion()
{
    if (!pHMD)
        return;
    Profile* profile = pHMD->GetProfile();
    if (!profile)
    {
        OVR_ASSERT(false);
        return;
    }
    SFusion.SetUserHeadDimensions ( *profile, RenderState.RenderInfo );
}

void HMDState::updateLowPersistenceMode(bool lowPersistence) const
{
	OVR_ASSERT(pSensor);
	DisplayReport dr;
    
    if (pSensor.GetPtr())
    {
	    pSensor->GetDisplayReport(&dr);

	    dr.Persistence = (UInt16) (dr.TotalRows * (lowPersistence ? 0.18f : 1.0f));
	    dr.Brightness = lowPersistence ? 255 : 0;
    
	    pSensor->SetDisplayReport(dr);
    }
}

void HMDState::updateLatencyTestForHmd(bool latencyTesting)
{
    if (pSensor.GetPtr())
    {
        DisplayReport dr;
        pSensor->GetDisplayReport(&dr);

        dr.ReadPixel = latencyTesting;

        pSensor->SetDisplayReport(dr);
    }

    if (latencyTesting)
    {
        LatencyUtil2.SetSensorDevice(pSensor.GetPtr());
    }
    else
    {
        LatencyUtil2.SetSensorDevice(NULL);
    }
}


void HMDState::updateDK2FeaturesTiedToSensor(bool sensorCreatedJustNow)
{
    Lock::Locker lockScope(&DevicesLock);

    if (!SensorCreated || (HMDInfo.HmdType != HmdType_DK2))
        return;

    // Only send display reports if state changed or sensor initializing first time.
    if (sensorCreatedJustNow ||
         ((HmdCapsAppliedToSensor ^ EnabledHmdCaps) & ovrHmdCap_LowPersistence))
    {
        updateLowPersistenceMode((EnabledHmdCaps & ovrHmdCap_LowPersistence) ? true : false);         
    }

    if (sensorCreatedJustNow || ((HmdCapsAppliedToSensor ^ EnabledHmdCaps) & ovrHmdCap_LatencyTest))
    {
        updateLatencyTestForHmd((EnabledHmdCaps & ovrHmdCap_LatencyTest) != 0);
    }

    HmdCapsAppliedToSensor = EnabledHmdCaps & (ovrHmdCap_LowPersistence|ovrHmdCap_LatencyTest);
}



void HMDState::SetEnabledHmdCaps(unsigned hmdCaps)
{
    
    if (HMDInfo.HmdType == HmdType_DK2)
    {
        if ((EnabledHmdCaps ^ hmdCaps) & ovrHmdCap_DynamicPrediction)
        {
            // DynamicPrediction change
            TimeManager.ResetFrameTiming(TimeManager.GetFrameTiming().FrameIndex,
                                         (hmdCaps & ovrHmdCap_DynamicPrediction) ? true : false,
                                         RenderingConfigured);
        }
    }

    if ((EnabledHmdCaps ^ hmdCaps) & ovrHmdCap_NoVSync)
    {
        TimeManager.SetVsync((hmdCaps & ovrHmdCap_NoVSync) ? false : true);
    }


    EnabledHmdCaps             = hmdCaps & ovrHmdCap_Writable_Mask;
    RenderState.EnabledHmdCaps = EnabledHmdCaps;

    // Unfortunately, LowPersistance and other flags are tied to sensor.
    // This flag will apply the state of sensor is created; otherwise this will be delayed
    // till StartSensor.
    // Such behavior is less then ideal, but should be resolved with the service model.

    updateDK2FeaturesTiedToSensor(false);
}


//-------------------------------------------------------------------------------------
// ***** Property Access

// TBD: This all needs to be cleaned up and organized into namespaces.

float HMDState::getFloatValue(const char* propertyName, float defaultVal)
{
	if (OVR_strcmp(propertyName, "LensSeparation") == 0)
	{
		return HMDInfo.LensSeparationInMeters;
	}
    else if (OVR_strcmp(propertyName, "CenterPupilDepth") == 0)
    {        
        return SFusion.GetCenterPupilDepth();
    }
	else if (pHMD)
	{
		Profile* p = pHMD->GetProfile();
		if (p)
		{
			return p->GetFloatValue(propertyName, defaultVal);
		}
	}
	return defaultVal;
}

bool HMDState::setFloatValue(const char* propertyName, float value)
{
    if (OVR_strcmp(propertyName, "CenterPupilDepth") == 0)
    {
        SFusion.SetCenterPupilDepth(value);
        return true;
    }
    return false;
}


static unsigned CopyFloatArrayWithLimit(float dest[], unsigned destSize,
                                        float source[], unsigned sourceSize)
{
    unsigned count = Alg::Min(destSize, sourceSize);
    for (unsigned i = 0; i < count; i++)
        dest[i] = source[i];
    return count;
}


unsigned HMDState::getFloatArray(const char* propertyName, float values[], unsigned arraySize)
{
	if (arraySize)
	{
		if (OVR_strcmp(propertyName, "ScreenSize") == 0)
		{
            float data[2] = { HMDInfo.ScreenSizeInMeters.w, HMDInfo.ScreenSizeInMeters.h };

            return CopyFloatArrayWithLimit(values, arraySize, data, 2);
		}
        else if (OVR_strcmp(propertyName, "DistortionClearColor") == 0)
        {
            return CopyFloatArrayWithLimit(values, arraySize, RenderState.ClearColor, 4);
        }
        else if (OVR_strcmp(propertyName, "DK2Latency") == 0)
        {
            if (HMDInfo.HmdType != HmdType_DK2)
                return 0;

            float data[3];            
            TimeManager.GetLatencyTimings(data);
            
            return CopyFloatArrayWithLimit(values, arraySize, data, 3);
        }

        /*
        else if (OVR_strcmp(propertyName, "CenterPupilDepth") == 0)
        {
            if (arraySize >= 1)
            {
                values[0] = SFusion.GetCenterPupilDepth();
                return 1;
            }
            return 0;
        } */
		else if (pHMD)
		{        
			Profile* p = pHMD->GetProfile();

			// TBD: Not quite right. Should update profile interface, so that
			//      we can return 0 in all conditions if property doesn't exist.
			if (p)
			{
				unsigned count = p->GetFloatValues(propertyName, values, arraySize);
				return count;
			}
		}
	}

	return 0;
}

bool HMDState::setFloatArray(const char* propertyName, float values[], unsigned arraySize)
{
    if (!arraySize)
        return false;
    
    if (OVR_strcmp(propertyName, "DistortionClearColor") == 0)
    {
        CopyFloatArrayWithLimit(RenderState.ClearColor, 4, values, arraySize);
        return true;
    }
    return false;
}


const char* HMDState::getString(const char* propertyName, const char* defaultVal)
{
	if (pHMD)
	{
		// For now, just access the profile.
		Profile* p = pHMD->GetProfile();

		LastGetStringValue[0] = 0;
		if (p && p->GetValue(propertyName, LastGetStringValue, sizeof(LastGetStringValue)))
		{
			return LastGetStringValue;
		}
	}

	return defaultVal;
}

//-------------------------------------------------------------------------------------
// *** Latency Test

bool HMDState::ProcessLatencyTest(unsigned char rgbColorOut[3])
{
    bool result = false;

    // Check create.
    if (pLatencyTester)
    {
        if (pLatencyTester->IsConnected())
        {
            Color colorToDisplay;

            LatencyUtil.ProcessInputs();
            result = LatencyUtil.DisplayScreenColor(colorToDisplay);
            rgbColorOut[0] = colorToDisplay.R;
            rgbColorOut[1] = colorToDisplay.G;
            rgbColorOut[2] = colorToDisplay.B;
        }
        else
        {
            // Disconnect.
            LatencyUtil.SetDevice(NULL);
            pLatencyTester = 0;
            LogText("LATENCY SENSOR disconnected.\n");
        }
    }
    else if (AddLatencyTestCount > 0)
    {
        // This might have some unlikely race condition issue which could cause us to miss a device...
        AddLatencyTestCount = 0;

        pLatencyTester = *GlobalState::pInstance->GetManager()->
                            EnumerateDevices<LatencyTestDevice>().CreateDevice();
        if (pLatencyTester)
        {
            LatencyUtil.SetDevice(pLatencyTester);
            LogText("LATENCY TESTER connected\n");
        }        
    }
    
    return result;
}

void HMDState::ProcessLatencyTest2(unsigned char rgbColorOut[3], double startTime)
{
    // Check create.
    if (!(EnabledHmdCaps & ovrHmdCap_LatencyTest))
        return;

    if (pLatencyTesterDisplay && !LatencyUtil2.HasDisplayDevice())
    {
        if (!pLatencyTesterDisplay->IsConnected())
        {
            LatencyUtil2.SetDisplayDevice(NULL);
        }
    }
    else if (AddLatencyTestDisplayCount > 0)
    {
        // This might have some unlikely race condition issue
        // which could cause us to miss a device...
        AddLatencyTestDisplayCount = 0;

        pLatencyTesterDisplay = *GlobalState::pInstance->GetManager()->
                                 EnumerateDevices<LatencyTestDevice>().CreateDevice();
        if (pLatencyTesterDisplay)
        {
            LatencyUtil2.SetDisplayDevice(pLatencyTesterDisplay);
        }
    }

    if (LatencyUtil2.HasDevice() && pSensor && pSensor->IsConnected())
    {
        LatencyUtil2.BeginTest(startTime);

        Color colorToDisplay;
        LatencyTest2Active = LatencyUtil2.DisplayScreenColor(colorToDisplay);
        rgbColorOut[0] = colorToDisplay.R;
        rgbColorOut[1] = colorToDisplay.G;
        rgbColorOut[2] = colorToDisplay.B;
    }
    else
    {
        LatencyTest2Active = false;
    }
}

//-------------------------------------------------------------------------------------
// *** Rendering

bool HMDState::ConfigureRendering(ovrEyeRenderDesc eyeRenderDescOut[2],
                                  const ovrFovPort eyeFovIn[2],
                                  const ovrRenderAPIConfig* apiConfig,                                  
                                  unsigned distortionCaps)
{
    ThreadChecker::Scope checkScope(&RenderAPIThreadChecker, "ovrHmd_ConfigureRendering");

    // null -> shut down.
    if (!apiConfig)
    {
        if (pRenderer)
            pRenderer.Clear();        
        RenderingConfigured = false; 
        return true;
    }

    if (pRenderer &&
        (apiConfig->Header.API != pRenderer->GetRenderAPI()))
    {
        // Shutdown old renderer.
        if (pRenderer)
            pRenderer.Clear();
    }


    // Step 1: do basic setup configuration
    RenderState.setupRenderDesc(eyeRenderDescOut, eyeFovIn);
    RenderState.EnabledHmdCaps = EnabledHmdCaps;     // This is a copy... Any cleaner way?
    RenderState.DistortionCaps = distortionCaps;

    TimeManager.ResetFrameTiming(0,
                                 (EnabledHmdCaps & ovrHmdCap_DynamicPrediction) ? true : false,
                                 true);

    LastFrameTimeSeconds = 0.0f;

    // Set RenderingConfigured early to avoid ASSERTs in renderer initialization.
    RenderingConfigured = true;

    if (!pRenderer)
    {
        pRenderer = *DistortionRenderer::APICreateRegistry
                        [apiConfig->Header.API](this, TimeManager, RenderState);
    }

    if (!pRenderer ||
        !pRenderer->Initialize(apiConfig, distortionCaps))
    {
        RenderingConfigured = false;
        return false;
    }    

    return true;
}



ovrPosef HMDState::BeginEyeRender(ovrEyeType eye)
{
    // Debug checks.
    checkBeginFrameScope("ovrHmd_BeginEyeRender");
    ThreadChecker::Scope checkScope(&RenderAPIThreadChecker, "ovrHmd_BeginEyeRender");

    // Unknown eyeId provided in ovrHmd_BeginEyeRender
    OVR_ASSERT_LOG(eye == ovrEye_Left || eye == ovrEye_Right,
                   ("ovrHmd_BeginEyeRender eyeId out of range."));     
    OVR_ASSERT_LOG(EyeRenderActive[eye] == false,
                   ("Multiple calls to ovrHmd_BeginEyeRender for the same eye."));

    EyeRenderActive[eye] = true;
    
    // Only process latency tester for drawing the left eye (assumes left eye is drawn first)
    if (pRenderer && eye == 0)
    {
        LatencyTestActive = ProcessLatencyTest(LatencyTestDrawColor);
    }

    return ovrHmd_GetEyePose(this, eye);
}


void HMDState::EndEyeRender(ovrEyeType eye, ovrPosef renderPose, ovrTexture* eyeTexture)
{
    // Debug checks.
    checkBeginFrameScope("ovrHmd_EndEyeRender");
    ThreadChecker::Scope checkScope(&RenderAPIThreadChecker, "ovrHmd_EndEyeRender");

    if (!EyeRenderActive[eye])
    {
        OVR_ASSERT_LOG(false,
                       ("ovrHmd_EndEyeRender called without ovrHmd_BeginEyeRender."));
        return;
    }

    RenderState.EyeRenderPoses[eye] = renderPose;

    if (pRenderer)
        pRenderer->SubmitEye(eye, eyeTexture);

    EyeRenderActive[eye] = false;
}

}} // namespace OVR::CAPI