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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
|
/************************************************************************************
Filename : OculusWorldDemo.cpp
Content : First-person view test application for Oculus Rift
Created : October 4, 2012
Authors : Michael Antonov, Andrew Reisse, Steve LaValle
Peter Hoff, Dan Goodman, Bryan Croteau
Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
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 "OVR.h"
#include "../CommonSrc/Platform/Platform_Default.h"
#include "../CommonSrc/Render/Render_Device.h"
#include "../CommonSrc/Render/Render_XmlSceneLoader.h"
#include "../CommonSrc/Render/Render_FontEmbed_DejaVu48.h"
#include "../CommonSrc/Platform/Gamepad.h"
#include <Kernel/OVR_SysFile.h>
#include <Kernel/OVR_Log.h>
#include <Kernel/OVR_Timer.h>
#include "Player.h"
// Filename to be loaded by default, searching specified paths.
#define WORLDDEMO_ASSET_FILE "Tuscany.xml"
#define WORLDDEMO_ASSET_PATH1 "Assets/Tuscany/"
#define WORLDDEMO_ASSET_PATH2 "../Assets/Tuscany/"
// This path allows the shortcut to work.
#define WORLDDEMO_ASSET_PATH3 "Samples/OculusWorldDemo/Assets/Tuscany/"
using namespace OVR;
using namespace OVR::Platform;
using namespace OVR::Render;
//-------------------------------------------------------------------------------------
// ***** OculusWorldDemo Description
// This app renders a simple flat-shaded room allowing the user to move along the
// floor and look around with an HMD, mouse and keyboard. The following keys work:
//
// 'W', 'S', 'A', 'D' and Arrow Keys - Move forward, back; strafe left/right.
// F1 - No stereo, no distortion.
// F2 - Stereo, no distortion.
// F3 - Stereo and distortion.
// F4 - Toggle MSAA.
// F9 - Cycle through fullscreen and windowed modes. Necessary for previewing content with Rift.
//
// Important Oculus-specific logic can be found at following locations:
//
// OculusWorldDemoApp::OnStartup - This function will initialize OVR::DeviceManager and HMD,
// creating SensorDevice and attaching it to SensorFusion.
// This needs to be done before obtaining sensor data.
//
// OculusWorldDemoApp::OnIdle - Here we poll SensorFusion for orientation, apply it
// to the scene and handle movement.
// Stereo rendering is also done here, by delegating to
// to Render function for each eye.
//
//-------------------------------------------------------------------------------------
// ***** OculusWorldDemo Application class
// An instance of this class is created on application startup (main/WinMain).
// It then works as follows:
// - Graphics and HMD setup is done OculusWorldDemoApp::OnStartup(). This function
// also creates the room model from Slab declarations.
// - Per-frame processing is done in OnIdle(). This function processes
// sensor and movement input and then renders the frame.
// - Additional input processing is done in OnMouse, OnKey.
class OculusWorldDemoApp : public Application, public MessageHandler
{
public:
OculusWorldDemoApp();
~OculusWorldDemoApp();
virtual int OnStartup(int argc, char** argv);
virtual void OnIdle();
virtual void OnMouseMove(int x, int y, int modifiers);
virtual void OnKey(OVR::KeyCode key, int chr, bool down, int modifiers);
virtual void OnResize(int width, int height);
virtual void OnMessage(const Message& msg);
void Render(const StereoEyeParams& stereo);
// Sets temporarily displayed message for adjustments
void SetAdjustMessage(const char* format, ...);
// Overrides current timeout, in seconds (not the future default value);
// intended to be called right after SetAdjustMessage.
void SetAdjustMessageTimeout(float timeout);
// Stereo setting adjustment functions.
// Called with deltaTime when relevant key is held.
void AdjustFov(float dt);
void AdjustAspect(float dt);
void AdjustIPD(float dt);
void AdjustEyeHeight(float dt);
void AdjustMotionPrediction(float dt);
void AdjustDistortion(float dt, int kIndex, const char* label);
void AdjustDistortionK0(float dt) { AdjustDistortion(dt, 0, "K0"); }
void AdjustDistortionK1(float dt) { AdjustDistortion(dt, 1, "K1"); }
void AdjustDistortionK2(float dt) { AdjustDistortion(dt, 2, "K2"); }
void AdjustDistortionK3(float dt) { AdjustDistortion(dt, 3, "K3"); }
void AdjustDistortion(float val, int kIndex);
void AdjustEsd(float val);
// Adds room model to scene.
void PopulateScene(const char* fileName);
void PopulatePreloadScene();
void ClearScene();
// Magnetometer calibration procedure
void UpdateManualMagCalibration();
protected:
RenderDevice* pRender;
RendererParams RenderParams;
int Width, Height;
int Screen;
int FirstScreenInCycle;
// *** Oculus HMD Variables
Ptr<DeviceManager> pManager;
Ptr<SensorDevice> pSensor;
Ptr<HMDDevice> pHMD;
Ptr<Profile> pUserProfile;
SensorFusion SFusion;
HMDInfo TheHMDInfo;
Ptr<LatencyTestDevice> pLatencyTester;
Util::LatencyTest LatencyUtil;
double LastUpdate;
int FPS;
int FrameCounter;
double NextFPSUpdate;
Array<Ptr<CollisionModel> > CollisionModels;
Array<Ptr<CollisionModel> > GroundCollisionModels;
// Loading process displays screenshot in first frame
// and then proceeds to load until finished.
enum LoadingStateType
{
LoadingState_Frame0,
LoadingState_DoLoad,
LoadingState_Finished
};
// Player
Player ThePlayer;
Matrix4f View;
Scene MainScene;
Scene LoadingScene;
Scene GridScene;
Scene YawMarkGreenScene;
Scene YawMarkRedScene;
Scene YawLinesScene;
LoadingStateType LoadingState;
Ptr<ShaderFill> LitSolid, LitTextures[4];
// Stereo view parameters.
StereoConfig SConfig;
PostProcessType PostProcess;
// LOD
String MainFilePath;
Array<String> LODFilePaths;
int ConsecutiveLowFPSFrames;
int CurrentLODFileIndex;
float DistortionK0;
float DistortionK1;
float DistortionK2;
float DistortionK3;
String AdjustMessage;
double AdjustMessageTimeout;
// Saved distortion state.
float SavedK0, SavedK1, SavedK2, SavedK3;
float SavedESD, SavedAspect, SavedEyeDistance;
// Allows toggling color around distortion.
Color DistortionClearColor;
// Stereo settings adjustment state.
typedef void (OculusWorldDemoApp::*AdjustFuncType)(float);
bool ShiftDown;
AdjustFuncType pAdjustFunc;
float AdjustDirection;
enum SceneRenderMode
{
Scene_World,
Scene_Grid,
Scene_Both,
Scene_YawView
};
SceneRenderMode SceneMode;
enum TextScreen
{
Text_None,
Text_Orientation,
Text_Config,
Text_Help,
Text_Count
};
TextScreen TextScreen;
struct DeviceStatusNotificationDesc
{
DeviceHandle Handle;
MessageType Action;
DeviceStatusNotificationDesc():Action(Message_None) {}
DeviceStatusNotificationDesc(MessageType mt, const DeviceHandle& dev)
: Handle(dev), Action(mt) {}
};
Array<DeviceStatusNotificationDesc> DeviceStatusNotificationsQueue;
Model* CreateModel(Vector3f pos, struct SlabModel* sm);
Model* CreateBoundingModel(CollisionModel &cm);
void PopulateLODFileNames();
void DropLOD();
void RaiseLOD();
void CycleDisplay();
void GamepadStateChanged(const GamepadState& pad);
};
//-------------------------------------------------------------------------------------
OculusWorldDemoApp::OculusWorldDemoApp()
: pRender(0),
LastUpdate(0),
LoadingState(LoadingState_Frame0),
// Initial location
SConfig(),
PostProcess(PostProcess_Distortion),
DistortionClearColor(0, 0, 0),
ShiftDown(false),
pAdjustFunc(0),
AdjustDirection(1.0f),
SceneMode(Scene_World),
TextScreen(Text_None)
{
Width = 1280;
Height = 800;
Screen = 0;
FirstScreenInCycle = 0;
FPS = 0;
FrameCounter = 0;
NextFPSUpdate = 0;
ConsecutiveLowFPSFrames = 0;
CurrentLODFileIndex = 0;
AdjustMessageTimeout = 0;
}
OculusWorldDemoApp::~OculusWorldDemoApp()
{
RemoveHandlerFromDevices();
if(DejaVu.fill)
{
DejaVu.fill->Release();
}
pLatencyTester.Clear();
pSensor.Clear();
pHMD.Clear();
CollisionModels.ClearAndRelease();
GroundCollisionModels.ClearAndRelease();
}
int OculusWorldDemoApp::OnStartup(int argc, char** argv)
{
// *** Oculus HMD & Sensor Initialization
// Create DeviceManager and first available HMDDevice from it.
// Sensor object is created from the HMD, to ensure that it is on the
// correct device.
pManager = *DeviceManager::Create();
// We'll handle it's messages in this case.
pManager->SetMessageHandler(this);
pHMD = *pManager->EnumerateDevices<HMDDevice>().CreateDevice();
if (pHMD)
{
pSensor = *pHMD->GetSensor();
// This will initialize HMDInfo with information about configured IPD,
// screen size and other variables needed for correct projection.
// We pass HMD DisplayDeviceName into the renderer to select the
// correct monitor in full-screen mode.
if(pHMD->GetDeviceInfo(&TheHMDInfo))
{
//RenderParams.MonitorName = hmd.DisplayDeviceName;
SConfig.SetHMDInfo(TheHMDInfo);
}
// Retrieve relevant profile settings.
pUserProfile = pHMD->GetProfile();
if (pUserProfile)
{
ThePlayer.UserEyeHeight = pUserProfile->GetEyeHeight();
ThePlayer.EyePos.y = ThePlayer.UserEyeHeight;
}
}
else
{
// If we didn't detect an HMD, try to create the sensor directly.
// This is useful for debugging sensor interaction; it is not needed in
// a shipping app.
pSensor = *pManager->EnumerateDevices<SensorDevice>().CreateDevice();
}
// Create the Latency Tester device and assign it to the LatencyTesterUtil object.
pLatencyTester = *pManager->EnumerateDevices<LatencyTestDevice>().CreateDevice();
if (pLatencyTester)
{
LatencyUtil.SetDevice(pLatencyTester);
}
// Make the user aware which devices are present.
if(pHMD == NULL && pSensor == NULL)
{
SetAdjustMessage("---------------------------------\nNO HMD DETECTED\nNO SENSOR DETECTED\n---------------------------------");
}
else if(pHMD == NULL)
{
SetAdjustMessage("----------------------------\nNO HMD DETECTED\n----------------------------");
}
else if(pSensor == NULL)
{
SetAdjustMessage("---------------------------------\nNO SENSOR DETECTED\n---------------------------------");
}
else
{
SetAdjustMessage("--------------------------------------------\n"
"Press F9 for Full-Screen on Rift\n"
"--------------------------------------------");
}
// First message should be extra-long.
SetAdjustMessageTimeout(10.0f);
if(TheHMDInfo.HResolution > 0)
{
Width = TheHMDInfo.HResolution;
Height = TheHMDInfo.VResolution;
}
if(!pPlatform->SetupWindow(Width, Height))
{
return 1;
}
String Title = "Oculus World Demo";
if(TheHMDInfo.ProductName[0])
{
Title += " : ";
Title += TheHMDInfo.ProductName;
}
pPlatform->SetWindowTitle(Title);
// Report relative mouse motion in OnMouseMove
pPlatform->SetMouseMode(Mouse_Relative);
if(pSensor)
{
// We need to attach sensor to SensorFusion object for it to receive
// body frame messages and update orientation. SFusion.GetOrientation()
// is used in OnIdle() to orient the view.
SFusion.AttachToSensor(pSensor);
SFusion.SetDelegateMessageHandler(this);
SFusion.SetPredictionEnabled(true);
}
// *** Initialize Rendering
const char* graphics = "d3d11";
// Select renderer based on command line arguments.
for(int i = 1; i < argc; i++)
{
if(!strcmp(argv[i], "-r") && i < argc - 1)
{
graphics = argv[i + 1];
}
else if(!strcmp(argv[i], "-fs"))
{
RenderParams.Fullscreen = true;
}
}
// Enable multi-sampling by default.
RenderParams.Multisample = 4;
pRender = pPlatform->SetupGraphics(OVR_DEFAULT_RENDER_DEVICE_SET,
graphics, RenderParams);
// *** Configure Stereo settings.
SConfig.SetFullViewport(Viewport(0, 0, Width, Height));
SConfig.SetStereoMode(Stereo_LeftRight_Multipass);
// Configure proper Distortion Fit.
// For 7" screen, fit to touch left side of the view, leaving a bit of
// invisible screen on the top (saves on rendering cost).
// For smaller screens (5.5"), fit to the top.
if (TheHMDInfo.HScreenSize > 0.0f)
{
if (TheHMDInfo.HScreenSize > 0.140f) // 7"
SConfig.SetDistortionFitPointVP(-1.0f, 0.0f);
else
SConfig.SetDistortionFitPointVP(0.0f, 1.0f);
}
pRender->SetSceneRenderScale(SConfig.GetDistortionScale());
//pRender->SetSceneRenderScale(1.0f);
SConfig.Set2DAreaFov(DegreeToRad(85.0f));
// *** Identify Scene File & Prepare for Loading
// This creates lights and models.
if (argc == 2)
{
MainFilePath = argv[1];
PopulateLODFileNames();
}
else
{
fprintf(stderr, "Usage: OculusWorldDemo [input XML]\n");
MainFilePath = WORLDDEMO_ASSET_FILE;
}
// Try to modify path for correctness in case specified file is not found.
if (!SysFile(MainFilePath).IsValid())
{
String prefixPath1(pPlatform->GetContentDirectory() + "/" + WORLDDEMO_ASSET_PATH1),
prefixPath2(WORLDDEMO_ASSET_PATH2),
prefixPath3(WORLDDEMO_ASSET_PATH3);
if (SysFile(prefixPath1 + MainFilePath).IsValid())
MainFilePath = prefixPath1 + MainFilePath;
else if (SysFile(prefixPath2 + MainFilePath).IsValid())
MainFilePath = prefixPath2 + MainFilePath;
else if (SysFile(prefixPath3 + MainFilePath).IsValid())
MainFilePath = prefixPath3 + MainFilePath;
}
PopulatePreloadScene();
LastUpdate = pPlatform->GetAppTime();
//pPlatform->PlayMusicFile(L"Loop.wav");
return 0;
}
void OculusWorldDemoApp::OnMessage(const Message& msg)
{
if (msg.Type == Message_DeviceAdded || msg.Type == Message_DeviceRemoved)
{
if (msg.pDevice == pManager)
{
const MessageDeviceStatus& statusMsg =
static_cast<const MessageDeviceStatus&>(msg);
{ // limit the scope of the lock
Lock::Locker lock(pManager->GetHandlerLock());
DeviceStatusNotificationsQueue.PushBack(
DeviceStatusNotificationDesc(statusMsg.Type, statusMsg.Handle));
}
switch (statusMsg.Type)
{
case OVR::Message_DeviceAdded:
LogText("DeviceManager reported device added.\n");
break;
case OVR::Message_DeviceRemoved:
LogText("DeviceManager reported device removed.\n");
break;
default: OVR_ASSERT(0); // unexpected type
}
}
}
}
void OculusWorldDemoApp::OnResize(int width, int height)
{
Width = width;
Height = height;
SConfig.SetFullViewport(Viewport(0, 0, Width, Height));
}
void OculusWorldDemoApp::OnMouseMove(int x, int y, int modifiers)
{
if(modifiers & Mod_MouseRelative)
{
// Get Delta
int dx = x, dy = y;
const float maxPitch = ((3.1415f / 2) * 0.98f);
// Apply to rotation. Subtract for right body frame rotation,
// since yaw rotation is positive CCW when looking down on XZ plane.
ThePlayer.EyeYaw -= (Sensitivity * dx) / 360.0f;
if(!pSensor)
{
ThePlayer.EyePitch -= (Sensitivity * dy) / 360.0f;
if(ThePlayer.EyePitch > maxPitch)
{
ThePlayer.EyePitch = maxPitch;
}
if(ThePlayer.EyePitch < -maxPitch)
{
ThePlayer.EyePitch = -maxPitch;
}
}
}
}
void OculusWorldDemoApp::OnKey(OVR::KeyCode key, int chr, bool down, int modifiers)
{
OVR_UNUSED(chr);
switch(key)
{
case Key_Q:
if (down && (modifiers & Mod_Control))
{
pPlatform->Exit(0);
}
break;
// Handle player movement keys.
// We just update movement state here, while the actual translation is done in OnIdle()
// based on time.
case Key_W:
ThePlayer.MoveForward = down ? (ThePlayer.MoveForward | 1) : (ThePlayer.MoveForward & ~1);
break;
case Key_S:
ThePlayer.MoveBack = down ? (ThePlayer.MoveBack | 1) : (ThePlayer.MoveBack & ~1);
break;
case Key_A:
ThePlayer.MoveLeft = down ? (ThePlayer.MoveLeft | 1) : (ThePlayer.MoveLeft & ~1);
break;
case Key_D:
ThePlayer.MoveRight = down ? (ThePlayer.MoveRight | 1) : (ThePlayer.MoveRight & ~1);
break;
case Key_Up:
ThePlayer.MoveForward = down ? (ThePlayer.MoveForward | 2) : (ThePlayer.MoveForward & ~2);
break;
case Key_Down:
ThePlayer.MoveBack = down ? (ThePlayer.MoveBack | 2) : (ThePlayer.MoveBack & ~2);
break;
case Key_Left:
ThePlayer.MoveLeft = down ? (ThePlayer.MoveLeft | 2) : (ThePlayer.MoveLeft & ~2);
break;
case Key_Right:
ThePlayer.MoveRight = down ? (ThePlayer.MoveRight | 2) : (ThePlayer.MoveRight & ~2);
break;
case Key_Minus:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustEyeHeight : 0;
AdjustDirection = -1;
break;
case Key_Equal:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustEyeHeight : 0;
AdjustDirection = 1;
break;
case Key_B:
if (down)
{
if(SConfig.GetDistortionScale() == 1.0f)
{
if(SConfig.GetHMDInfo().HScreenSize > 0.140f) // 7"
{
SConfig.SetDistortionFitPointVP(-1.0f, 0.0f);
}
else
{
SConfig.SetDistortionFitPointVP(0.0f, 1.0f);
}
}
else
{
// No fitting; scale == 1.0.
SConfig.SetDistortionFitPointVP(0, 0);
}
}
break;
// Support toggling background color for distortion so that we can see
// the effect on the periphery.
case Key_V:
if (down)
{
if(DistortionClearColor.B == 0)
{
DistortionClearColor = Color(0, 128, 255);
}
else
{
DistortionClearColor = Color(0, 0, 0);
}
pRender->SetDistortionClearColor(DistortionClearColor);
}
break;
case Key_F1:
SConfig.SetStereoMode(Stereo_None);
PostProcess = PostProcess_None;
SetAdjustMessage("StereoMode: None");
break;
case Key_F2:
SConfig.SetStereoMode(Stereo_LeftRight_Multipass);
PostProcess = PostProcess_None;
SetAdjustMessage("StereoMode: Stereo + No Distortion");
break;
case Key_F3:
SConfig.SetStereoMode(Stereo_LeftRight_Multipass);
PostProcess = PostProcess_Distortion;
SetAdjustMessage("StereoMode: Stereo + Distortion");
break;
case Key_R:
SFusion.Reset();
SetAdjustMessage("Sensor Fusion Reset");
break;
case Key_Space:
if (!down)
{
TextScreen = (enum TextScreen)((TextScreen + 1) % Text_Count);
}
break;
case Key_F4:
if (!down)
{
RenderParams = pRender->GetParams();
RenderParams.Multisample = RenderParams.Multisample > 1 ? 1 : 4;
pRender->SetParams(RenderParams);
if(RenderParams.Multisample > 1)
{
SetAdjustMessage("Multisampling On");
}
else
{
SetAdjustMessage("Multisampling Off");
}
}
break;
case Key_F9:
#ifndef OVR_OS_LINUX // On Linux F9 does the same as F11.
if (!down)
{
CycleDisplay();
}
break;
#endif
#ifdef OVR_OS_MAC
case Key_F10: // F11 is reserved on Mac
#else
case Key_F11:
#endif
if (!down)
{
RenderParams = pRender->GetParams();
RenderParams.Display = DisplayId(SConfig.GetHMDInfo().DisplayDeviceName,SConfig.GetHMDInfo().DisplayId);
pRender->SetParams(RenderParams);
pPlatform->SetMouseMode(Mouse_Normal);
pPlatform->SetFullscreen(RenderParams, pRender->IsFullscreen() ? Display_Window : Display_FakeFullscreen);
pPlatform->SetMouseMode(Mouse_Relative); // Avoid mode world rotation jump.
// If using an HMD, enable post-process (for distortion) and stereo.
if(RenderParams.IsDisplaySet() && pRender->IsFullscreen())
{
SConfig.SetStereoMode(Stereo_LeftRight_Multipass);
PostProcess = PostProcess_Distortion;
}
}
break;
case Key_Escape:
if(!down)
{
// switch to primary screen windowed mode
pPlatform->SetFullscreen(RenderParams, Display_Window);
RenderParams.Display = pPlatform->GetDisplay(0);
pRender->SetParams(RenderParams);
Screen = 0;
}
break;
// Stereo adjustments.
case Key_BracketLeft:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustFov : 0;
AdjustDirection = 1;
break;
case Key_BracketRight:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustFov : 0;
AdjustDirection = -1;
break;
case Key_Insert:
case Key_Num0:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustIPD : 0;
AdjustDirection = 1;
break;
case Key_Delete:
case Key_Num9:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustIPD : 0;
AdjustDirection = -1;
break;
case Key_PageUp:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustAspect : 0;
AdjustDirection = 1;
break;
case Key_PageDown:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustAspect : 0;
AdjustDirection = -1;
break;
// Distortion correction adjustments
case Key_H:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK0 : NULL;
AdjustDirection = -1;
break;
case Key_Y:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK0 : NULL;
AdjustDirection = 1;
break;
case Key_J:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK1 : NULL;
AdjustDirection = -1;
break;
case Key_U:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK1 : NULL;
AdjustDirection = 1;
break;
case Key_K:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK2 : NULL;
AdjustDirection = -1;
break;
case Key_I:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK2 : NULL;
AdjustDirection = 1;
break;
case Key_L:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK3 : NULL;
AdjustDirection = -1;
break;
case Key_O:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK3 : NULL;
AdjustDirection = 1;
break;
case Key_Tab:
if (down)
{
float t0 = SConfig.GetDistortionK(0),
t1 = SConfig.GetDistortionK(1),
t2 = SConfig.GetDistortionK(2),
t3 = SConfig.GetDistortionK(3);
float tESD = SConfig.GetEyeToScreenDistance(),
taspect = SConfig.GetAspectMultiplier(),
tipd = SConfig.GetIPD();
if(SavedK0 > 0.0f)
{
SConfig.SetDistortionK(0, SavedK0);
SConfig.SetDistortionK(1, SavedK1);
SConfig.SetDistortionK(2, SavedK2);
SConfig.SetDistortionK(3, SavedK3);
SConfig.SetEyeToScreenDistance(SavedESD);
SConfig.SetAspectMultiplier(SavedAspect);
SConfig.SetIPD(SavedEyeDistance);
if ( ShiftDown )
{
// Swap saved and current values. Good for doing direct comparisons.
SetAdjustMessage("Swapped current and saved. New settings:\n"
"ESD:\t120 %.3f\t350 Eye:\t490 %.3f\n"
"K0: \t120 %.4f\t350 K2: \t490 %.4f\n"
"K1: \t120 %.4f\t350 K3: \t490 %.4f\n",
SavedESD, SavedEyeDistance,
SavedK0, SavedK2,
SavedK1, SavedK3);
SavedK0 = t0;
SavedK1 = t1;
SavedK2 = t2;
SavedK3 = t3;
SavedESD = tESD;
SavedAspect = taspect;
SavedEyeDistance = tipd;
}
else
{
SetAdjustMessage("Restored:\n"
"ESD:\t120 %.3f\t350 Eye:\t490 %.3f\n"
"K0: \t120 %.4f\t350 K2: \t490 %.4f\n"
"K1: \t120 %.4f\t350 K3: \t490 %.4f\n",
SavedESD, SavedEyeDistance,
SavedK0, SavedK2,
SavedK1, SavedK3);
}
}
else
{
SetAdjustMessage("Setting Saved");
SavedK0 = t0;
SavedK1 = t1;
SavedK2 = t2;
SavedK3 = t3;
SavedESD = tESD;
SavedAspect = taspect;
SavedEyeDistance = tipd;
}
}
break;
case Key_G:
if (down)
{
if(SceneMode == Scene_World)
{
SceneMode = Scene_Grid;
SetAdjustMessage("Grid Only");
}
else if(SceneMode == Scene_Grid)
{
SceneMode = Scene_Both;
SetAdjustMessage("Grid Overlay");
}
else if(SceneMode == Scene_Both)
{
SceneMode = Scene_World;
SetAdjustMessage("Grid Off");
}
}
break;
// Holding down Shift key accelerates adjustment velocity.
case Key_Shift:
ShiftDown = down;
break;
// Reset the camera position in case we get stuck
case Key_T:
ThePlayer.EyePos = Vector3f(10.0f, ThePlayer.UserEyeHeight, 10.0f);
break;
case Key_F5:
if (!down)
{
UPInt numNodes = MainScene.Models.GetSize();
for(UPInt i = 0; i < numNodes; i++)
{
Ptr<OVR::Render::Model> nodePtr = MainScene.Models[i];
Render::Model* pNode = nodePtr.GetPtr();
if(pNode->IsCollisionModel)
{
pNode->Visible = !pNode->Visible;
}
}
}
break;
case Key_N:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustMotionPrediction : NULL;
AdjustDirection = -1;
break;
case Key_M:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustMotionPrediction : NULL;
AdjustDirection = 1;
break;
/*
case Key_N:
RaiseLOD();
break;
case Key_M:
DropLOD();
break;
*/
// Cycle through drift correction options
case Key_Z:
if (down)
{
if (SFusion.IsYawCorrectionEnabled())
{
SFusion.SetGravityEnabled(false);
SFusion.SetYawCorrectionEnabled(false);
}
else if (SFusion.IsGravityEnabled())
{
SFusion.SetYawCorrectionEnabled(true);
}
else
{
SFusion.SetGravityEnabled(true);
}
SetAdjustMessage("Tilt Correction %s\nYaw Correction %s",
SFusion.IsGravityEnabled() ? "On" : "Off",
SFusion.IsYawCorrectionEnabled() ? "On" : "Off");
}
break;
// Show view of yaw angles (for mag calibration/analysis)
case Key_F6:
if (down)
{
if (SceneMode != Scene_YawView)
{
SceneMode = Scene_YawView;
SetAdjustMessage("Magnetometer Yaw Angle Marks");
}
else
{
SceneMode = Scene_World;
SetAdjustMessage("Magnetometer Marks Off");
}
}
break;
case Key_C:
if (down)
{
// Toggle chromatic aberration correction on/off.
RenderDevice::PostProcessShader shader = pRender->GetPostProcessShader();
if (shader == RenderDevice::PostProcessShader_Distortion)
{
pRender->SetPostProcessShader(RenderDevice::PostProcessShader_DistortionAndChromAb);
SetAdjustMessage("Chromatic Aberration Correction On");
}
else if (shader == RenderDevice::PostProcessShader_DistortionAndChromAb)
{
pRender->SetPostProcessShader(RenderDevice::PostProcessShader_Distortion);
SetAdjustMessage("Chromatic Aberration Correction Off");
}
else
OVR_ASSERT(false);
}
break;
case Key_P:
if (down)
{
// Toggle motion prediction.
if (SFusion.IsPredictionEnabled())
{
SFusion.SetPredictionEnabled(false);
SetAdjustMessage("Motion Prediction Off");
}
else
{
SFusion.SetPredictionEnabled(true);
SetAdjustMessage("Motion Prediction On");
}
}
break;
default:
break;
}
}
void OculusWorldDemoApp::OnIdle()
{
double curtime = pPlatform->GetAppTime();
float dt = float(curtime - LastUpdate);
LastUpdate = curtime;
// Update gamepad.
GamepadState gamepadState;
if (GetPlatformCore()->GetGamepadManager()->GetGamepadState(0, &gamepadState))
{
GamepadStateChanged(gamepadState);
}
if (LoadingState == LoadingState_DoLoad)
{
PopulateScene(MainFilePath.ToCStr());
LoadingState = LoadingState_Finished;
return;
}
// Check if any new devices were connected.
{
bool queueIsEmpty = false;
while (!queueIsEmpty)
{
DeviceStatusNotificationDesc desc;
{
Lock::Locker lock(pManager->GetHandlerLock());
if (DeviceStatusNotificationsQueue.GetSize() == 0)
break;
desc = DeviceStatusNotificationsQueue.Front();
// We can't call Clear under the lock since this may introduce a dead lock:
// this thread is locked by HandlerLock and the Clear might cause
// call of Device->Release, which will use Manager->DeviceLock. The bkg
// thread is most likely locked by opposite way:
// Manager->DeviceLock ==> HandlerLock, therefore - a dead lock.
// So, just grab the first element, save a copy of it and remove
// the element (Device->Release won't be called since we made a copy).
DeviceStatusNotificationsQueue.RemoveAt(0);
queueIsEmpty = (DeviceStatusNotificationsQueue.GetSize() == 0);
}
bool wasAlreadyCreated = desc.Handle.IsCreated();
if (desc.Action == Message_DeviceAdded)
{
switch(desc.Handle.GetType())
{
case Device_Sensor:
if (desc.Handle.IsAvailable() && !desc.Handle.IsCreated())
{
if (!pSensor)
{
pSensor = *desc.Handle.CreateDeviceTyped<SensorDevice>();
if (pSensor)
{
SFusion.AttachToSensor(pSensor);
SetAdjustMessage("---------------------------\n"
"SENSOR connected\n"
"---------------------------");
}
else
{
SetAdjustMessage("----------------------------\n"
"SENSOR connect failed\n"
"Unplug and reconnect it.\n"
"----------------------------");
}
}
else if (!wasAlreadyCreated)
{
LogText("A new SENSOR has been detected, but it is not currently used.");
}
}
break;
case Device_LatencyTester:
if (desc.Handle.IsAvailable() && !desc.Handle.IsCreated())
{
if (!pLatencyTester)
{
pLatencyTester = *desc.Handle.CreateDeviceTyped<LatencyTestDevice>();
LatencyUtil.SetDevice(pLatencyTester);
if (!wasAlreadyCreated)
SetAdjustMessage("----------------------------------------\n"
"LATENCY TESTER connected\n"
"----------------------------------------");
}
}
break;
case Device_HMD:
{
OVR::HMDInfo info;
desc.Handle.GetDeviceInfo(&info);
// if strlen(info.DisplayDeviceName) == 0 then
// this HMD is 'fake' (created using sensor).
if (strlen(info.DisplayDeviceName) > 0 && (!pHMD || !info.IsSameDisplay(TheHMDInfo)))
{
SetAdjustMessage("------------------------\n"
"HMD connected\n"
"------------------------");
if (!pHMD || !desc.Handle.IsDevice(pHMD))
pHMD = *desc.Handle.CreateDeviceTyped<HMDDevice>();
// update stereo config with new HMDInfo
if (pHMD && pHMD->GetDeviceInfo(&TheHMDInfo))
{
//RenderParams.MonitorName = hmd.DisplayDeviceName;
SConfig.SetHMDInfo(TheHMDInfo);
}
LogText("HMD device added.\n");
}
break;
}
default:;
}
}
else if (desc.Action == Message_DeviceRemoved)
{
if (desc.Handle.IsDevice(pSensor))
{
LogText("Sensor reported device removed.\n");
SFusion.AttachToSensor(NULL);
pSensor.Clear();
SetAdjustMessage("-------------------------------\n"
"SENSOR disconnected.\n"
"-------------------------------");
}
else if (desc.Handle.IsDevice(pLatencyTester))
{
LogText("Latency Tester reported device removed.\n");
LatencyUtil.SetDevice(NULL);
pLatencyTester.Clear();
SetAdjustMessage("---------------------------------------------\n"
"LATENCY SENSOR disconnected.\n"
"---------------------------------------------");
}
else if (desc.Handle.IsDevice(pHMD))
{
if (pHMD && !pHMD->IsDisconnected())
{
SetAdjustMessage("---------------------------\n"
"HMD disconnected\n"
"---------------------------");
// Disconnect HMD. pSensor is used to restore 'fake' HMD device
// (can be NULL).
pHMD = pHMD->Disconnect(pSensor);
// This will initialize TheHMDInfo with information about configured IPD,
// screen size and other variables needed for correct projection.
// We pass HMD DisplayDeviceName into the renderer to select the
// correct monitor in full-screen mode.
if (pHMD && pHMD->GetDeviceInfo(&TheHMDInfo))
{
//RenderParams.MonitorName = hmd.DisplayDeviceName;
SConfig.SetHMDInfo(TheHMDInfo);
}
LogText("HMD device removed.\n");
}
}
}
else
OVR_ASSERT(0); // unexpected action
}
}
// If one of Stereo setting adjustment keys is pressed, adjust related state.
if (pAdjustFunc)
{
(this->*pAdjustFunc)(dt * AdjustDirection * (ShiftDown ? 5.0f : 1.0f));
}
// Process latency tester results.
const char* results = LatencyUtil.GetResultsString();
if (results != NULL)
{
LogText("LATENCY TESTER: %s\n", results);
}
// >>> THIS MUST BE PLACED AS CLOSE AS POSSIBLE TO WHERE THE HMD ORIENTATION IS READ <<<
LatencyUtil.ProcessInputs();
// Handle Sensor motion.
// We extract Yaw, Pitch, Roll instead of directly using the orientation
// to allow "additional" yaw manipulation with mouse/controller.
if(pSensor)
{
Quatf hmdOrient = SFusion.GetPredictedOrientation();
float yaw = 0.0f;
hmdOrient.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&yaw, &ThePlayer.EyePitch, &ThePlayer.EyeRoll);
ThePlayer.EyeYaw += (yaw - ThePlayer.LastSensorYaw);
ThePlayer.LastSensorYaw = yaw;
// NOTE: We can get a matrix from orientation as follows:
// Matrix4f hmdMat(hmdOrient);
// Test logic - assign quaternion result directly to view:
// Quatf hmdOrient = SFusion.GetOrientation();
// View = Matrix4f(hmdOrient.Inverted()) * Matrix4f::Translation(-EyePos);
}
if(curtime >= NextFPSUpdate)
{
NextFPSUpdate = curtime + 1.0;
FPS = FrameCounter;
FrameCounter = 0;
}
FrameCounter++;
if(FPS < 40)
{
ConsecutiveLowFPSFrames++;
}
else
{
ConsecutiveLowFPSFrames = 0;
}
if(ConsecutiveLowFPSFrames > 200)
{
DropLOD();
ConsecutiveLowFPSFrames = 0;
}
ThePlayer.EyeYaw -= ThePlayer.GamepadRotate.x * dt;
ThePlayer.HandleCollision(dt, &CollisionModels, &GroundCollisionModels, ShiftDown);
if(!pSensor)
{
ThePlayer.EyePitch -= ThePlayer.GamepadRotate.y * dt;
const float maxPitch = ((3.1415f / 2) * 0.98f);
if(ThePlayer.EyePitch > maxPitch)
{
ThePlayer.EyePitch = maxPitch;
}
if(ThePlayer.EyePitch < -maxPitch)
{
ThePlayer.EyePitch = -maxPitch;
}
}
// Rotate and position View Camera, using YawPitchRoll in BodyFrame coordinates.
//
Matrix4f rollPitchYaw = Matrix4f::RotationY(ThePlayer.EyeYaw) * Matrix4f::RotationX(ThePlayer.EyePitch) *
Matrix4f::RotationZ(ThePlayer.EyeRoll);
Vector3f up = rollPitchYaw.Transform(UpVector);
Vector3f forward = rollPitchYaw.Transform(ForwardVector);
// Minimal head modeling; should be moved as an option to SensorFusion.
float headBaseToEyeHeight = 0.15f; // Vertical height of eye from base of head
float headBaseToEyeProtrusion = 0.09f; // Distance forward of eye from base of head
Vector3f eyeCenterInHeadFrame(0.0f, headBaseToEyeHeight, -headBaseToEyeProtrusion);
Vector3f shiftedEyePos = ThePlayer.EyePos + rollPitchYaw.Transform(eyeCenterInHeadFrame);
shiftedEyePos.y -= eyeCenterInHeadFrame.y; // Bring the head back down to original height
View = Matrix4f::LookAtRH(shiftedEyePos, shiftedEyePos + forward, up);
// Transformation without head modeling.
// View = Matrix4f::LookAtRH(EyePos, EyePos + forward, up);
// This is an alternative to LookAtRH:
// Here we transpose the rotation matrix to get its inverse.
// View = (Matrix4f::RotationY(EyeYaw) * Matrix4f::RotationX(EyePitch) *
// Matrix4f::RotationZ(EyeRoll)).Transposed() *
// Matrix4f::Translation(-EyePos);
switch(SConfig.GetStereoMode())
{
case Stereo_None:
Render(SConfig.GetEyeRenderParams(StereoEye_Center));
break;
case Stereo_LeftRight_Multipass:
//case Stereo_LeftDouble_Multipass:
Render(SConfig.GetEyeRenderParams(StereoEye_Left));
Render(SConfig.GetEyeRenderParams(StereoEye_Right));
break;
}
pRender->Present();
// Force GPU to flush the scene, resulting in the lowest possible latency.
pRender->ForceFlushGPU();
}
static const char* HelpText =
"F1 \t100 NoStereo\n"
"F2 \t100 Stereo \t420 Z \t520 Drift Correction\n"
"F3 \t100 StereoHMD \t420 F6 \t520 Yaw Drift Info\n"
"F4 \t100 MSAA \t420 R \t520 Reset SensorFusion\n"
"F9 \t100 FullScreen \t420\n"
"F11 \t100 Fast FullScreen \t500 - + \t660 Adj EyeHeight\n"
"C \t100 Chromatic Ab \t500 [ ] \t660 Adj FOV\n"
"P \t100 Motion Pred \t500 Shift \t660 Adj Faster\n"
"N/M \t180 Adj Motion Pred\n"
"( / ) \t180 Adj EyeDistance"
;
enum DrawTextCenterType
{
DrawText_NoCenter= 0,
DrawText_VCenter = 0x1,
DrawText_HCenter = 0x2,
DrawText_Center = DrawText_VCenter | DrawText_HCenter
};
static void DrawTextBox(RenderDevice* prender, float x, float y,
float textSize, const char* text,
DrawTextCenterType centerType = DrawText_NoCenter)
{
float ssize[2] = {0.0f, 0.0f};
prender->MeasureText(&DejaVu, text, textSize, ssize);
// Treat 0 a VCenter.
if (centerType & DrawText_HCenter)
{
x = -ssize[0]/2;
}
if (centerType & DrawText_VCenter)
{
y = -ssize[1]/2;
}
prender->FillRect(x-0.02f, y-0.02f, x+ssize[0]+0.02f, y+ssize[1]+0.02f, Color(40,40,100,210));
prender->RenderText(&DejaVu, text, x, y, textSize, Color(255,255,0,210));
}
void OculusWorldDemoApp::Render(const StereoEyeParams& stereo)
{
pRender->BeginScene(PostProcess);
// *** 3D - Configures Viewport/Projection and Render
pRender->ApplyStereoParams(stereo);
pRender->Clear();
pRender->SetDepthMode(true, true);
if (SceneMode != Scene_Grid)
{
MainScene.Render(pRender, stereo.ViewAdjust * View);
}
if (SceneMode == Scene_YawView)
{
Matrix4f trackerOnlyOrient = Matrix4f::RotationY(ThePlayer.LastSensorYaw)
* Matrix4f::RotationX(ThePlayer.EyePitch)
* Matrix4f::RotationZ(ThePlayer.EyeRoll);
YawLinesScene.Render(pRender, stereo.ViewAdjust * trackerOnlyOrient.Inverted());
//YawMarkRedScene.Render(pRender, stereo.ViewAdjust);
}
// *** 2D Text & Grid - Configure Orthographic rendering.
// Render UI in 2D orthographic coordinate system that maps [-1,1] range
// to a readable FOV area centered at your eye and properly adjusted.
pRender->ApplyStereoParams2D(stereo);
pRender->SetDepthMode(false, false);
float unitPixel = SConfig.Get2DUnitPixel();
float textHeight= unitPixel * 22;
if ((SceneMode == Scene_Grid)||(SceneMode == Scene_Both))
{ // Draw grid two pixels thick.
GridScene.Render(pRender, Matrix4f());
GridScene.Render(pRender, Matrix4f::Translation(unitPixel,unitPixel,0));
}
// Display Loading screen-shot in frame 0.
if (LoadingState != LoadingState_Finished)
{
LoadingScene.Render(pRender, Matrix4f());
String loadMessage = String("Loading ") + MainFilePath;
DrawTextBox(pRender, 0.0f, 0.0f, textHeight, loadMessage.ToCStr(), DrawText_HCenter);
LoadingState = LoadingState_DoLoad;
}
if(!AdjustMessage.IsEmpty() && AdjustMessageTimeout > pPlatform->GetAppTime())
{
DrawTextBox(pRender,0.0f,0.4f, textHeight, AdjustMessage.ToCStr(), DrawText_HCenter);
}
switch(TextScreen)
{
case Text_Orientation:
{
char buf[256], gpustat[256];
OVR_sprintf(buf, sizeof(buf),
" Yaw:%4.0f Pitch:%4.0f Roll:%4.0f \n"
" FPS: %d Frame: %d \n Pos: %3.2f, %3.2f, %3.2f \n"
" EyeHeight: %3.2f",
RadToDegree(ThePlayer.EyeYaw), RadToDegree(ThePlayer.EyePitch), RadToDegree(ThePlayer.EyeRoll),
FPS, FrameCounter, ThePlayer.EyePos.x, ThePlayer.EyePos.y, ThePlayer.EyePos.z, ThePlayer.UserEyeHeight);
size_t texMemInMB = pRender->GetTotalTextureMemoryUsage() / 1058576;
if (texMemInMB)
{
OVR_sprintf(gpustat, sizeof(gpustat), "\n GPU Tex: %u MB", texMemInMB);
OVR_strcat(buf, sizeof(buf), gpustat);
}
DrawTextBox(pRender, 0.0f, -0.15f, textHeight, buf, DrawText_HCenter);
}
break;
case Text_Config:
{
char textBuff[2048];
OVR_sprintf(textBuff, sizeof(textBuff),
"Fov\t300 %9.4f\n"
"EyeDistance\t300 %9.4f\n"
"DistortionK0\t300 %9.4f\n"
"DistortionK1\t300 %9.4f\n"
"DistortionK2\t300 %9.4f\n"
"DistortionK3\t300 %9.4f\n"
"TexScale\t300 %9.4f",
SConfig.GetYFOVDegrees(),
SConfig.GetIPD(),
SConfig.GetDistortionK(0),
SConfig.GetDistortionK(1),
SConfig.GetDistortionK(2),
SConfig.GetDistortionK(3),
SConfig.GetDistortionScale());
DrawTextBox(pRender, 0.0f, 0.0f, textHeight, textBuff, DrawText_Center);
}
break;
case Text_Help:
DrawTextBox(pRender, 0.0f, -0.1f, textHeight, HelpText, DrawText_Center);
default:
break;
}
// Display colored quad if we're doing a latency test.
Color colorToDisplay;
if (LatencyUtil.DisplayScreenColor(colorToDisplay))
{
pRender->FillRect(-0.4f, -0.4f, 0.4f, 0.4f, colorToDisplay);
}
pRender->FinishScene();
}
// Sets temporarily displayed message for adjustments
void OculusWorldDemoApp::SetAdjustMessage(const char* format, ...)
{
Lock::Locker lock(pManager->GetHandlerLock());
char textBuff[2048];
va_list argList;
va_start(argList, format);
OVR_vsprintf(textBuff, sizeof(textBuff), format, argList);
va_end(argList);
// Message will time out in 4 seconds.
AdjustMessage = textBuff;
AdjustMessageTimeout = pPlatform->GetAppTime() + 4.0f;
}
void OculusWorldDemoApp::SetAdjustMessageTimeout(float timeout)
{
AdjustMessageTimeout = pPlatform->GetAppTime() + timeout;
}
// ***** View Control Adjustments
void OculusWorldDemoApp::AdjustFov(float dt)
{
float esd = SConfig.GetEyeToScreenDistance() + 0.01f * dt;
SConfig.SetEyeToScreenDistance(esd);
SetAdjustMessage("ESD:%6.3f FOV: %6.3f", esd, SConfig.GetYFOVDegrees());
}
void OculusWorldDemoApp::AdjustAspect(float dt)
{
float rawAspect = SConfig.GetAspect() / SConfig.GetAspectMultiplier();
float newAspect = SConfig.GetAspect() + 0.01f * dt;
SConfig.SetAspectMultiplier(newAspect / rawAspect);
SetAdjustMessage("Aspect: %6.3f", newAspect);
}
void OculusWorldDemoApp::AdjustDistortion(float dt, int kIndex, const char* label)
{
SConfig.SetDistortionK(kIndex, SConfig.GetDistortionK(kIndex) + 0.03f * dt);
SetAdjustMessage("%s: %6.4f", label, SConfig.GetDistortionK(kIndex));
}
void OculusWorldDemoApp::AdjustIPD(float dt)
{
SConfig.SetIPD(SConfig.GetIPD() + 0.025f * dt);
SetAdjustMessage("EyeDistance: %6.4f", SConfig.GetIPD());
}
void OculusWorldDemoApp::AdjustEyeHeight(float dt)
{
float dist = 0.5f * dt;
ThePlayer.UserEyeHeight += dist;
ThePlayer.EyePos.y += dist;
SetAdjustMessage("UserEyeHeight: %4.2f", ThePlayer.UserEyeHeight);
}
void OculusWorldDemoApp::AdjustMotionPrediction(float dt)
{
float motionPred = SFusion.GetPredictionDelta() + 0.01f * dt;
if (motionPred < 0.0f)
{
motionPred = 0.0f;
}
SFusion.SetPrediction(motionPred);
SetAdjustMessage("MotionPrediction: %6.3fs", motionPred);
}
void OculusWorldDemoApp::AdjustDistortion(float val, int kIndex)
{
SConfig.SetDistortionK(kIndex, val);
SetAdjustMessage("K%d: %6.4f", kIndex, SConfig.GetDistortionK(kIndex));
}
void OculusWorldDemoApp::AdjustEsd(float val)
{
SConfig.SetEyeToScreenDistance(val);
float esd = SConfig.GetEyeToScreenDistance();
SetAdjustMessage("ESD:%6.3f FOV: %6.3f", esd, SConfig.GetYFOVDegrees());
}
// Loads the scene data
void OculusWorldDemoApp::PopulateScene(const char *fileName)
{
XmlHandler xmlHandler;
if(!xmlHandler.ReadFile(fileName, pRender, &MainScene, &CollisionModels, &GroundCollisionModels))
{
SetAdjustMessage("---------------------------------\nFILE LOAD FAILED\n---------------------------------");
SetAdjustMessageTimeout(10.0f);
}
MainScene.SetAmbient(Vector4f(1.0f, 1.0f, 1.0f, 1.0f));
// Distortion debug grid (brought up by 'G' key).
Ptr<Model> gridModel = *Model::CreateGrid(Vector3f(0,0,0), Vector3f(1.0f/10, 0,0), Vector3f(0,1.0f/10,0),
10, 10, 5,
Color(0, 255, 0, 255), Color(255, 50, 50, 255) );
GridScene.World.Add(gridModel);
// Yaw angle marker and lines (brought up by ';' key).
float shifty = -0.5f;
Ptr<Model> yawMarkGreenModel = *Model::CreateBox(Color(0, 255, 0, 255), Vector3f(0.0f, shifty, -2.0f), Vector3f(0.05f, 0.05f, 0.05f));
YawMarkGreenScene.World.Add(yawMarkGreenModel);
Ptr<Model> yawMarkRedModel = *Model::CreateBox(Color(255, 0, 0, 255), Vector3f(0.0f, shifty, -2.0f), Vector3f(0.05f, 0.05f, 0.05f));
YawMarkRedScene.World.Add(yawMarkRedModel);
Ptr<Model> yawLinesModel = *new Model();
Color c = Color(255, 200, 200, 255);
float r = 1.5f;
yawLinesModel->AddTriangle(yawLinesModel->AddVertex(Vector3f(-0.1f, 0, -r), c),
yawLinesModel->AddVertex(Vector3f(0, 0, -r-0.2f), c),
yawLinesModel->AddVertex(Vector3f(0.1f, 0, -r), c));
yawLinesModel->AddTriangle(yawLinesModel->AddVertex(Vector3f(-r-0.1f, 0, -r), c),
yawLinesModel->AddVertex(Vector3f(-r, 0, -r-0.2f), c),
yawLinesModel->AddVertex(Vector3f(-r+0.1f, 0, -r), c));
yawLinesModel->AddTriangle(yawLinesModel->AddVertex(Vector3f(r-0.1f, 0, -r), c),
yawLinesModel->AddVertex(Vector3f(r, 0, -r-0.2f), c),
yawLinesModel->AddVertex(Vector3f(r+0.1f, 0, -r), c));
yawLinesModel->SetPosition(Vector3f(0.0f,-1.2f,0.0f));
YawLinesScene.World.Add(yawLinesModel);
}
void OculusWorldDemoApp::PopulatePreloadScene()
{
// Load-screen screen shot image
String fileName = MainFilePath;
fileName.StripExtension();
Ptr<File> imageFile = *new SysFile(fileName + "_LoadScreen.tga");
Ptr<Texture> imageTex;
if (imageFile->IsValid())
imageTex = *LoadTextureTga(pRender, imageFile);
// Image is rendered as a single quad.
if (imageTex)
{
imageTex->SetSampleMode(Sample_Anisotropic|Sample_Repeat);
Ptr<Model> m = *new Model(Prim_Triangles);
m->AddVertex(-0.5f, 0.5f, 0.0f, Color(255,255,255,255), 0.0f, 0.0f);
m->AddVertex( 0.5f, 0.5f, 0.0f, Color(255,255,255,255), 1.0f, 0.0f);
m->AddVertex( 0.5f, -0.5f, 0.0f, Color(255,255,255,255), 1.0f, 1.0f);
m->AddVertex(-0.5f, -0.5f, 0.0f, Color(255,255,255,255), 0.0f, 1.0f);
m->AddTriangle(2,1,0);
m->AddTriangle(0,3,2);
Ptr<ShaderFill> fill = *new ShaderFill(*pRender->CreateShaderSet());
fill->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Vertex, VShader_MVP));
fill->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Fragment, FShader_Texture));
fill->SetTexture(0, imageTex);
m->Fill = fill;
LoadingScene.World.Add(m);
}
}
void OculusWorldDemoApp::ClearScene()
{
MainScene.Clear();
GridScene.Clear();
YawMarkGreenScene.Clear();
YawMarkRedScene.Clear();
YawLinesScene.Clear();
}
void OculusWorldDemoApp::PopulateLODFileNames()
{
//OVR::String mainFilePath = MainFilePath;
LODFilePaths.PushBack(MainFilePath);
int LODIndex = 1;
SPInt pos = strcspn(MainFilePath.ToCStr(), ".");
SPInt len = strlen(MainFilePath.ToCStr());
SPInt diff = len - pos;
if (diff == 0)
return;
while(true)
{
char pathWithoutExt[250];
char buffer[250];
for(SPInt i = 0; i < pos; ++i)
{
pathWithoutExt[i] = MainFilePath[(int)i];
}
pathWithoutExt[pos] = '\0';
OVR_sprintf(buffer, sizeof(buffer), "%s%i.xml", pathWithoutExt, LODIndex);
FILE* fp = 0;
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
errno_t err = fopen_s(&fp, buffer, "rb");
if(!fp || err)
{
#else
fp = fopen(buffer, "rb");
if(!fp)
{
#endif
break;
}
fclose(fp);
OVR::String result = buffer;
LODFilePaths.PushBack(result);
LODIndex++;
}
}
void OculusWorldDemoApp::DropLOD()
{
if(CurrentLODFileIndex < (int)(LODFilePaths.GetSize() - 1))
{
ClearScene();
CurrentLODFileIndex++;
PopulateScene(LODFilePaths[CurrentLODFileIndex].ToCStr());
}
}
void OculusWorldDemoApp::RaiseLOD()
{
if(CurrentLODFileIndex > 0)
{
ClearScene();
CurrentLODFileIndex--;
PopulateScene(LODFilePaths[CurrentLODFileIndex].ToCStr());
}
}
//-----------------------------------------------------------------------------
void OculusWorldDemoApp::CycleDisplay()
{
int screenCount = pPlatform->GetDisplayCount();
// If Windowed, switch to the HMD screen first in Full-Screen Mode.
// If already Full-Screen, cycle to next screen until we reach FirstScreenInCycle.
if (pRender->IsFullscreen())
{
// Right now, we always need to restore window before going to next screen.
pPlatform->SetFullscreen(RenderParams, Display_Window);
Screen++;
if (Screen == screenCount)
Screen = 0;
RenderParams.Display = pPlatform->GetDisplay(Screen);
if (Screen != FirstScreenInCycle)
{
pRender->SetParams(RenderParams);
pPlatform->SetFullscreen(RenderParams, Display_Fullscreen);
}
}
else
{
// Try to find HMD Screen, making it the first screen in full-screen Cycle.
FirstScreenInCycle = 0;
if (pHMD)
{
DisplayId HMD (SConfig.GetHMDInfo().DisplayDeviceName, SConfig.GetHMDInfo().DisplayId);
for (int i = 0; i< screenCount; i++)
{
if (pPlatform->GetDisplay(i) == HMD)
{
FirstScreenInCycle = i;
break;
}
}
}
// Switch full-screen on the HMD.
Screen = FirstScreenInCycle;
RenderParams.Display = pPlatform->GetDisplay(Screen);
pRender->SetParams(RenderParams);
pPlatform->SetFullscreen(RenderParams, Display_Fullscreen);
}
}
void OculusWorldDemoApp::GamepadStateChanged(const GamepadState& pad)
{
ThePlayer.GamepadMove = Vector3f(pad.LX * pad.LX * (pad.LX > 0 ? 1 : -1),
0,
pad.LY * pad.LY * (pad.LY > 0 ? -1 : 1));
ThePlayer.GamepadRotate = Vector3f(2 * pad.RX, -2 * pad.RY, 0);
}
//-------------------------------------------------------------------------------------
OVR_PLATFORM_APP(OculusWorldDemoApp);
|