OVRManager.cs 63.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 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 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.

Your use of this SDK or tool is subject to the Oculus SDK License Agreement, available at
https://developer.oculus.com/licenses/oculussdk/

Unless required by applicable law or agreed to in writing, the Utilities 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.
************************************************************************************/

#if USING_XR_MANAGEMENT && USING_XR_SDK_OCULUS
#define USING_XR_SDK
#endif

#if UNITY_2020_1_OR_NEWER
#define REQUIRES_XR_SDK
#endif

#if UNITY_ANDROID && !UNITY_EDITOR
#define OVR_ANDROID_MRC
#endif

#if !UNITY_2018_3_OR_NEWER
#error Oculus Utilities require Unity 2018.3 or higher.
#endif

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

using UnityEngine.Rendering;

#if USING_XR_SDK
using UnityEngine.XR;
using UnityEngine.Experimental.XR;
#endif

using Settings = UnityEngine.XR.XRSettings;
using Node = UnityEngine.XR.XRNode;

/// <summary>
/// Configuration data for Oculus virtual reality.
/// </summary>
public class OVRManager : MonoBehaviour, OVRMixedRealityCaptureConfiguration
{
	public enum XrApi
	{
		Unknown = OVRPlugin.XrApi.Unknown,
		CAPI = OVRPlugin.XrApi.CAPI,
		VRAPI = OVRPlugin.XrApi.VRAPI,
		OpenXR = OVRPlugin.XrApi.OpenXR,
	}

	public enum TrackingOrigin
	{
		EyeLevel = OVRPlugin.TrackingOrigin.EyeLevel,
		FloorLevel = OVRPlugin.TrackingOrigin.FloorLevel,
		Stage = OVRPlugin.TrackingOrigin.Stage,
	}

	public enum EyeTextureFormat
	{
		Default = OVRPlugin.EyeTextureFormat.Default,
		R16G16B16A16_FP = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP,
		R11G11B10_FP = OVRPlugin.EyeTextureFormat.R11G11B10_FP,
	}

	public enum FixedFoveatedRenderingLevel
	{
		Off = OVRPlugin.FixedFoveatedRenderingLevel.Off,
		Low = OVRPlugin.FixedFoveatedRenderingLevel.Low,
		Medium = OVRPlugin.FixedFoveatedRenderingLevel.Medium,
		High = OVRPlugin.FixedFoveatedRenderingLevel.High,
		HighTop = OVRPlugin.FixedFoveatedRenderingLevel.HighTop,
	}

	[Obsolete("Please use FixedFoveatedRenderingLevel instead")]
	public enum TiledMultiResLevel
	{
		Off = OVRPlugin.TiledMultiResLevel.Off,
		LMSLow = OVRPlugin.TiledMultiResLevel.LMSLow,
		LMSMedium = OVRPlugin.TiledMultiResLevel.LMSMedium,
		LMSHigh = OVRPlugin.TiledMultiResLevel.LMSHigh,
		LMSHighTop = OVRPlugin.TiledMultiResLevel.LMSHighTop,
	}

	public enum SystemHeadsetType
	{
		None = OVRPlugin.SystemHeadset.None,

		// Standalone headsets
		Oculus_Quest = OVRPlugin.SystemHeadset.Oculus_Quest,
		Oculus_Quest_2 = OVRPlugin.SystemHeadset.Oculus_Quest_2,
		Placeholder_10 = OVRPlugin.SystemHeadset.Placeholder_10,
		Placeholder_11 = OVRPlugin.SystemHeadset.Placeholder_11,
		Placeholder_12 = OVRPlugin.SystemHeadset.Placeholder_12,
		Placeholder_13 = OVRPlugin.SystemHeadset.Placeholder_13,
		Placeholder_14 = OVRPlugin.SystemHeadset.Placeholder_14,

		// PC headsets
		Rift_DK1 = OVRPlugin.SystemHeadset.Rift_DK1,
		Rift_DK2 = OVRPlugin.SystemHeadset.Rift_DK2,
		Rift_CV1 = OVRPlugin.SystemHeadset.Rift_CV1,
		Rift_CB = OVRPlugin.SystemHeadset.Rift_CB,
		Rift_S = OVRPlugin.SystemHeadset.Rift_S,
		Oculus_Link_Quest = OVRPlugin.SystemHeadset.Oculus_Link_Quest,
		Oculus_Link_Quest_2 = OVRPlugin.SystemHeadset.Oculus_Link_Quest_2,
		PC_Placeholder_4103 = OVRPlugin.SystemHeadset.PC_Placeholder_4103,
		PC_Placeholder_4104 = OVRPlugin.SystemHeadset.PC_Placeholder_4104,
		PC_Placeholder_4105 = OVRPlugin.SystemHeadset.PC_Placeholder_4105,
		PC_Placeholder_4106 = OVRPlugin.SystemHeadset.PC_Placeholder_4106,
		PC_Placeholder_4107 = OVRPlugin.SystemHeadset.PC_Placeholder_4107
	}

	public enum XRDevice
	{
		Unknown = 0,
		Oculus = 1,
		OpenVR = 2,
	}

	public enum ColorSpace
	{
		Unknown = OVRPlugin.ColorSpace.Unknown,
		Unmanaged = OVRPlugin.ColorSpace.Unmanaged,
		Rec_2020 = OVRPlugin.ColorSpace.Rec_2020,
		Rec_709 = OVRPlugin.ColorSpace.Rec_709,
		Rift_CV1 = OVRPlugin.ColorSpace.Rift_CV1,
		Rift_S = OVRPlugin.ColorSpace.Rift_S,
		Quest = OVRPlugin.ColorSpace.Quest,
		P3 = OVRPlugin.ColorSpace.P3,
		Adobe_RGB = OVRPlugin.ColorSpace.Adobe_RGB,
	}

	/// <summary>
	/// Gets the singleton instance.
	/// </summary>
	public static OVRManager instance { get; private set; }

	/// <summary>
	/// Gets a reference to the active display.
	/// </summary>
	public static OVRDisplay display { get; private set; }

	/// <summary>
	/// Gets a reference to the active sensor.
	/// </summary>
	public static OVRTracker tracker { get; private set; }

	/// <summary>
	/// Gets a reference to the active boundary system.
	/// </summary>
	public static OVRBoundary boundary { get; private set; }

	private static OVRProfile _profile;
	/// <summary>
	/// Gets the current profile, which contains information about the user's settings and body dimensions.
	/// </summary>
	public static OVRProfile profile
	{
		get {
			if (_profile == null)
				_profile = new OVRProfile();

			return _profile;
		}
	}

	private IEnumerable<Camera> disabledCameras;
	float prevTimeScale;

	/// <summary>
	/// Occurs when an HMD attached.
	/// </summary>
	public static event Action HMDAcquired;

	/// <summary>
	/// Occurs when an HMD detached.
	/// </summary>
	public static event Action HMDLost;

	/// <summary>
	/// Occurs when an HMD is put on the user's head.
	/// </summary>
	public static event Action HMDMounted;

	/// <summary>
	/// Occurs when an HMD is taken off the user's head.
	/// </summary>
	public static event Action HMDUnmounted;

	/// <summary>
	/// Occurs when VR Focus is acquired.
	/// </summary>
	public static event Action VrFocusAcquired;

	/// <summary>
	/// Occurs when VR Focus is lost.
	/// </summary>
	public static event Action VrFocusLost;

	/// <summary>
	/// Occurs when Input Focus is acquired.
	/// </summary>
	public static event Action InputFocusAcquired;

	/// <summary>
	/// Occurs when Input Focus is lost.
	/// </summary>
	public static event Action InputFocusLost;

	/// <summary>
	/// Occurs when the active Audio Out device has changed and a restart is needed.
	/// </summary>
	public static event Action AudioOutChanged;

	/// <summary>
	/// Occurs when the active Audio In device has changed and a restart is needed.
	/// </summary>
	public static event Action AudioInChanged;

	/// <summary>
	/// Occurs when the sensor gained tracking.
	/// </summary>
	public static event Action TrackingAcquired;

	/// <summary>
	/// Occurs when the sensor lost tracking.
	/// </summary>
	public static event Action TrackingLost;

	/// <summary>
	/// Occurs when the display refresh rate changes
	/// @params (float fromRefreshRate, float toRefreshRate)
	/// </summary>
	public static event Action<float, float> DisplayRefreshRateChanged;

	/// <summary>
	/// Occurs when Health & Safety Warning is dismissed.
	/// </summary>
	//Disable the warning about it being unused. It's deprecated.
#pragma warning disable 0067
	[Obsolete]
	public static event Action HSWDismissed;
#pragma warning restore

	private static bool _isHmdPresentCached = false;
	private static bool _isHmdPresent = false;
	private static bool _wasHmdPresent = false;
	/// <summary>
	/// If true, a head-mounted display is connected and present.
	/// </summary>
	public static bool isHmdPresent
	{
		get {
			if (!_isHmdPresentCached)
			{
				_isHmdPresentCached = true;
				_isHmdPresent = OVRNodeStateProperties.IsHmdPresent();
			}

			return _isHmdPresent;
		}

		private set {
			_isHmdPresentCached = true;
			_isHmdPresent = value;
		}
	}

	/// <summary>
	/// Gets the audio output device identifier.
	/// </summary>
	/// <description>
	/// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
	/// </description>
	public static string audioOutId
	{
		get { return OVRPlugin.audioOutId; }
	}

	/// <summary>
	/// Gets the audio input device identifier.
	/// </summary>
	/// <description>
	/// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
	/// </description>
	public static string audioInId
	{
		get { return OVRPlugin.audioInId; }
	}

	private static bool _hasVrFocusCached = false;
	private static bool _hasVrFocus = false;
	private static bool _hadVrFocus = false;
	/// <summary>
	/// If true, the app has VR Focus.
	/// </summary>
	public static bool hasVrFocus
	{
		get {
			if (!_hasVrFocusCached)
			{
				_hasVrFocusCached = true;
				_hasVrFocus = OVRPlugin.hasVrFocus;
			}

			return _hasVrFocus;
		}

		private set {
			_hasVrFocusCached = true;
			_hasVrFocus = value;
		}
	}

	private static bool _hadInputFocus = true;
	/// <summary>
	/// If true, the app has Input Focus.
	/// </summary>
	public static bool hasInputFocus
	{
		get
		{
			return OVRPlugin.hasInputFocus;
		}
	}

	/// <summary>
	/// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth.
	/// </summary>
	public bool chromatic
	{
		get {
			if (!isHmdPresent)
				return false;

			return OVRPlugin.chromatic;
		}

		set {
			if (!isHmdPresent)
				return;

			OVRPlugin.chromatic = value;
		}
	}

	[Header("Performance/Quality")]
	/// <summary>
	/// If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.
	/// </summary>
	[Tooltip("If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.")]
	public bool useRecommendedMSAALevel = true;

	/// <summary>
	/// If true, both eyes will see the same image, rendered from the center eye pose, saving performance.
	/// </summary>
	[SerializeField]
	[Tooltip("If true, both eyes will see the same image, rendered from the center eye pose, saving performance.")]
	private bool _monoscopic = false;

	public bool monoscopic
	{
		get
		{
			if (!isHmdPresent)
				return _monoscopic;

			return OVRPlugin.monoscopic;
		}

		set
		{
			if (!isHmdPresent)
				return;

			OVRPlugin.monoscopic = value;
			_monoscopic = value;
		}
	}

	/// <summary>
	/// If true, dynamic resolution will be enabled
	/// </summary>
	[Tooltip("If true, dynamic resolution will be enabled On PC")]
	public bool enableAdaptiveResolution = false;

	[SerializeField, HideInInspector]
	private OVRManager.ColorSpace _colorGamut = OVRManager.ColorSpace.Rift_CV1;

	/// <summary>
	/// The target color gamut the HMD will perform a color space transformation to
	/// </summary>
	public OVRManager.ColorSpace colorGamut
	{
		get
		{
			return _colorGamut;
		}
		set
		{
			_colorGamut = value;
			OVRPlugin.SetClientColorDesc((OVRPlugin.ColorSpace)_colorGamut);
		}
	}

	/// <summary>
	/// The native color gamut of the target HMD
	/// </summary>
	public OVRManager.ColorSpace nativeColorGamut
	{
		get
		{
			return (OVRManager.ColorSpace)OVRPlugin.GetHmdColorDesc();
		}
	}

	/// <summary>
	/// Adaptive Resolution is based on Unity engine's renderViewportScale/eyeTextureResolutionScale feature
	/// But renderViewportScale was broken in an array of Unity engines, this function help to filter out those broken engines
	/// </summary>
	public static bool IsAdaptiveResSupportedByEngine()
	{
		return true;
	}

	/// <summary>
	/// Min RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = true );
	/// </summary>
	[RangeAttribute(0.5f, 2.0f)]
	[Tooltip("Min RenderScale the app can reach under adaptive resolution mode")]
	public float minRenderScale = 0.7f;

	/// <summary>
	/// Max RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = true );
	/// </summary>
	[RangeAttribute(0.5f, 2.0f)]
	[Tooltip("Max RenderScale the app can reach under adaptive resolution mode")]
	public float maxRenderScale = 1.0f;

	/// <summary>
	/// Set the relative offset rotation of head poses
	/// </summary>
	[SerializeField]
	[Tooltip("Set the relative offset rotation of head poses")]
	private Vector3 _headPoseRelativeOffsetRotation;
	public Vector3 headPoseRelativeOffsetRotation
	{
		get
		{
			return _headPoseRelativeOffsetRotation;
		}
		set
		{
			OVRPlugin.Quatf rotation;
			OVRPlugin.Vector3f translation;
			if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation))
			{
				Quaternion finalRotation = Quaternion.Euler(value);
				rotation = finalRotation.ToQuatf();
				OVRPlugin.SetHeadPoseModifier(ref rotation, ref translation);
			}
			_headPoseRelativeOffsetRotation = value;
		}
	}

	/// <summary>
	/// Set the relative offset translation of head poses
	/// </summary>
	[SerializeField]
	[Tooltip("Set the relative offset translation of head poses")]
	private Vector3 _headPoseRelativeOffsetTranslation;
	public Vector3 headPoseRelativeOffsetTranslation
	{
		get
		{
			return _headPoseRelativeOffsetTranslation;
		}
		set
		{
			OVRPlugin.Quatf rotation;
			OVRPlugin.Vector3f translation;
			if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation))
			{
				if (translation.FromFlippedZVector3f() != value)
				{
					translation = value.ToFlippedZVector3f();
					OVRPlugin.SetHeadPoseModifier(ref rotation, ref translation);
				}
			}
			_headPoseRelativeOffsetTranslation = value;
		}
	}

	/// <summary>
	/// The TCP listening port of Oculus Profiler Service, which will be activated in Debug/Developerment builds
	/// When the app is running on editor or device, open "Tools/Oculus/Oculus Profiler Panel" to view the realtime system metrics
	/// </summary>
	public int profilerTcpPort = OVRSystemPerfMetrics.TcpListeningPort;

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_ANDROID
	/// <summary>
	/// If true, the MixedRealityCapture properties will be displayed
	/// </summary>
	[HideInInspector]
	public bool expandMixedRealityCapturePropertySheet = false;


	/// <summary>
	/// If true, Mixed Reality mode will be enabled
	/// </summary>
	[HideInInspector, Tooltip("If true, Mixed Reality mode will be enabled. It would be always set to false when the game is launching without editor")]
	public bool enableMixedReality = false;

	public enum CompositionMethod
	{
		External,
		Direct
	}

	/// <summary>
	/// Composition method
	/// </summary>
	[HideInInspector]
	public CompositionMethod compositionMethod = CompositionMethod.External;

	/// <summary>
	/// Extra hidden layers
	/// </summary>
	[HideInInspector, Tooltip("Extra hidden layers")]
	public LayerMask extraHiddenLayers;

	/// <summary>
	/// Extra visible layers
	/// </summary>
	[HideInInspector, Tooltip("Extra visible layers")]
	public LayerMask extraVisibleLayers;

	/// <summary>
	/// If premultipled alpha blending is used for the eye fov layer.
	/// Useful for changing how the eye fov layer blends with underlays.
	/// </summary>
	[HideInInspector]
	public static bool eyeFovPremultipliedAlphaModeEnabled
	{
		get
		{
			return OVRPlugin.eyeFovPremultipliedAlphaModeEnabled;
		}
		set
		{
			OVRPlugin.eyeFovPremultipliedAlphaModeEnabled = value;
		}
	}

	/// <summary>
	/// Whether MRC should dynamically update the culling mask using the Main Camera's culling mask, extraHiddenLayers, and extraVisibleLayers
	/// </summary>
	[HideInInspector, Tooltip("Dynamic Culling Mask")]
	public bool dynamicCullingMask = true;

	/// <summary>
	/// The backdrop color will be used when rendering the foreground frames (on Rift). It only applies to External Composition.
	/// </summary>
	[HideInInspector, Tooltip("Backdrop color for Rift (External Compositon)")]
	public Color externalCompositionBackdropColorRift = Color.green;

	/// <summary>
	/// The backdrop color will be used when rendering the foreground frames (on Quest). It only applies to External Composition.
	/// </summary>
	[HideInInspector, Tooltip("Backdrop color for Quest (External Compositon)")]
	public Color externalCompositionBackdropColorQuest = Color.clear;

	/// <summary>
	/// If true, Mixed Reality mode will use direct composition from the first web camera
	/// </summary>

	public enum CameraDevice
	{
		WebCamera0,
		WebCamera1,
		ZEDCamera
	}

	/// <summary>
	/// The camera device for direct composition
	/// </summary>
	[HideInInspector, Tooltip("The camera device for direct composition")]
	public CameraDevice capturingCameraDevice = CameraDevice.WebCamera0;

	/// <summary>
	/// Flip the camera frame horizontally
	/// </summary>
	[HideInInspector, Tooltip("Flip the camera frame horizontally")]
	public bool flipCameraFrameHorizontally = false;

	/// <summary>
	/// Flip the camera frame vertically
	/// </summary>
	[HideInInspector, Tooltip("Flip the camera frame vertically")]
	public bool flipCameraFrameVertically = false;

	/// <summary>
	/// Delay the touch controller pose by a short duration (0 to 0.5 second) to match the physical camera latency
	/// </summary>
	[HideInInspector, Tooltip("Delay the touch controller pose by a short duration (0 to 0.5 second) to match the physical camera latency")]
	public float handPoseStateLatency = 0.0f;

	/// <summary>
	/// Delay the foreground / background image in the sandwich composition to match the physical camera latency. The maximum duration is sandwichCompositionBufferedFrames / {Game FPS}
	/// </summary>
	[HideInInspector, Tooltip("Delay the foreground / background image in the sandwich composition to match the physical camera latency. The maximum duration is sandwichCompositionBufferedFrames / {Game FPS}")]
	public float sandwichCompositionRenderLatency = 0.0f;

	/// <summary>
	/// The number of frames are buffered in the SandWich composition. The more buffered frames, the more memory it would consume.
	/// </summary>
	[HideInInspector, Tooltip("The number of frames are buffered in the SandWich composition. The more buffered frames, the more memory it would consume.")]
	public int sandwichCompositionBufferedFrames = 8;


	/// <summary>
	/// Chroma Key Color
	/// </summary>
	[HideInInspector, Tooltip("Chroma Key Color")]
	public Color chromaKeyColor = Color.green;

	/// <summary>
	/// Chroma Key Similarity
	/// </summary>
	[HideInInspector, Tooltip("Chroma Key Similarity")]
	public float chromaKeySimilarity = 0.60f;

	/// <summary>
	/// Chroma Key Smooth Range
	/// </summary>
	[HideInInspector, Tooltip("Chroma Key Smooth Range")]
	public float chromaKeySmoothRange = 0.03f;

	/// <summary>
	///  Chroma Key Spill Range
	/// </summary>
	[HideInInspector, Tooltip("Chroma Key Spill Range")]
	public float chromaKeySpillRange = 0.06f;

	/// <summary>
	/// Use dynamic lighting (Depth sensor required)
	/// </summary>
	[HideInInspector, Tooltip("Use dynamic lighting (Depth sensor required)")]
	public bool useDynamicLighting = false;

	public enum DepthQuality
	{
		Low,
		Medium,
		High
	}
	/// <summary>
	/// The quality level of depth image. The lighting could be more smooth and accurate with high quality depth, but it would also be more costly in performance.
	/// </summary>
	[HideInInspector, Tooltip("The quality level of depth image. The lighting could be more smooth and accurate with high quality depth, but it would also be more costly in performance.")]
	public DepthQuality depthQuality = DepthQuality.Medium;

	/// <summary>
	/// Smooth factor in dynamic lighting. Larger is smoother
	/// </summary>
	[HideInInspector, Tooltip("Smooth factor in dynamic lighting. Larger is smoother")]
	public float dynamicLightingSmoothFactor = 8.0f;

	/// <summary>
	/// The maximum depth variation across the edges. Make it smaller to smooth the lighting on the edges.
	/// </summary>
	[HideInInspector, Tooltip("The maximum depth variation across the edges. Make it smaller to smooth the lighting on the edges.")]
	public float dynamicLightingDepthVariationClampingValue = 0.001f;

	public enum VirtualGreenScreenType
	{
		Off,
		OuterBoundary,
		PlayArea
	}

	/// <summary>
	/// Set the current type of the virtual green screen
	/// </summary>
	[HideInInspector, Tooltip("Type of virutal green screen ")]
	public VirtualGreenScreenType virtualGreenScreenType = VirtualGreenScreenType.Off;

	/// <summary>
	/// Top Y of virtual screen
	/// </summary>
	[HideInInspector, Tooltip("Top Y of virtual green screen")]
	public float virtualGreenScreenTopY = 10.0f;

	/// <summary>
	/// Bottom Y of virtual screen
	/// </summary>
	[HideInInspector, Tooltip("Bottom Y of virtual green screen")]
	public float virtualGreenScreenBottomY = -10.0f;

	/// <summary>
	/// When using a depth camera (e.g. ZED), whether to use the depth in virtual green screen culling.
	/// </summary>
	[HideInInspector, Tooltip("When using a depth camera (e.g. ZED), whether to use the depth in virtual green screen culling.")]
	public bool virtualGreenScreenApplyDepthCulling = false;

	/// <summary>
	/// The tolerance value (in meter) when using the virtual green screen with a depth camera. Make it bigger if the foreground objects got culled incorrectly.
	/// </summary>
	[HideInInspector, Tooltip("The tolerance value (in meter) when using the virtual green screen with a depth camera. Make it bigger if the foreground objects got culled incorrectly.")]
	public float virtualGreenScreenDepthTolerance = 0.2f;


	public enum MrcActivationMode
	{
		Automatic,
		Disabled
	}

	/// <summary>
	/// (Quest-only) control if the mixed reality capture mode can be activated automatically through remote network connection.
	/// </summary>
	[HideInInspector, Tooltip("(Quest-only) control if the mixed reality capture mode can be activated automatically through remote network connection.")]
	public MrcActivationMode mrcActivationMode;

	public enum MrcCameraType
	{
		Normal,
		Foreground,
		Background
	}

	public delegate GameObject InstantiateMrcCameraDelegate(GameObject mainCameraGameObject, MrcCameraType cameraType);

	/// <summary>
	/// Allows overriding the internal mrc camera creation
	/// </summary>
	public InstantiateMrcCameraDelegate instantiateMixedRealityCameraGameObject = null;
	
	// OVRMixedRealityCaptureConfiguration Interface implementation
	bool OVRMixedRealityCaptureConfiguration.enableMixedReality { get { return enableMixedReality; } set { enableMixedReality = value; } }
	LayerMask OVRMixedRealityCaptureConfiguration.extraHiddenLayers { get { return extraHiddenLayers; } set { extraHiddenLayers = value; } }
	LayerMask OVRMixedRealityCaptureConfiguration.extraVisibleLayers { get { return extraVisibleLayers; } set { extraVisibleLayers = value; } }
	bool OVRMixedRealityCaptureConfiguration.dynamicCullingMask { get { return dynamicCullingMask; } set { dynamicCullingMask = value; } }
	CompositionMethod OVRMixedRealityCaptureConfiguration.compositionMethod { get { return compositionMethod; } set { compositionMethod = value; } }
	Color OVRMixedRealityCaptureConfiguration.externalCompositionBackdropColorRift { get { return externalCompositionBackdropColorRift; } set { externalCompositionBackdropColorRift = value; } }
	Color OVRMixedRealityCaptureConfiguration.externalCompositionBackdropColorQuest { get { return externalCompositionBackdropColorQuest; } set { externalCompositionBackdropColorQuest = value; } }
	CameraDevice OVRMixedRealityCaptureConfiguration.capturingCameraDevice { get { return capturingCameraDevice; } set { capturingCameraDevice = value; } }
	bool OVRMixedRealityCaptureConfiguration.flipCameraFrameHorizontally { get { return flipCameraFrameHorizontally; } set { flipCameraFrameHorizontally = value; } }
	bool OVRMixedRealityCaptureConfiguration.flipCameraFrameVertically { get { return flipCameraFrameVertically; } set { flipCameraFrameVertically = value; } }
	float OVRMixedRealityCaptureConfiguration.handPoseStateLatency { get { return handPoseStateLatency; } set { handPoseStateLatency = value; } }
	float OVRMixedRealityCaptureConfiguration.sandwichCompositionRenderLatency { get { return sandwichCompositionRenderLatency; } set { sandwichCompositionRenderLatency = value; } }
	int OVRMixedRealityCaptureConfiguration.sandwichCompositionBufferedFrames { get { return sandwichCompositionBufferedFrames; } set { sandwichCompositionBufferedFrames = value; } }
	Color OVRMixedRealityCaptureConfiguration.chromaKeyColor { get { return chromaKeyColor; } set { chromaKeyColor = value; } }
	float OVRMixedRealityCaptureConfiguration.chromaKeySimilarity { get { return chromaKeySimilarity; } set { chromaKeySimilarity = value; } }
	float OVRMixedRealityCaptureConfiguration.chromaKeySmoothRange { get { return chromaKeySmoothRange; } set { chromaKeySmoothRange = value; } }
	float OVRMixedRealityCaptureConfiguration.chromaKeySpillRange { get { return chromaKeySpillRange; } set { chromaKeySpillRange = value; } }
	bool OVRMixedRealityCaptureConfiguration.useDynamicLighting { get { return useDynamicLighting; } set { useDynamicLighting = value; } }
	DepthQuality OVRMixedRealityCaptureConfiguration.depthQuality { get { return depthQuality; } set { depthQuality = value; } }
	float OVRMixedRealityCaptureConfiguration.dynamicLightingSmoothFactor { get { return dynamicLightingSmoothFactor; } set { dynamicLightingSmoothFactor = value; } }
	float OVRMixedRealityCaptureConfiguration.dynamicLightingDepthVariationClampingValue { get { return dynamicLightingDepthVariationClampingValue; } set { dynamicLightingDepthVariationClampingValue = value; } }
	VirtualGreenScreenType OVRMixedRealityCaptureConfiguration.virtualGreenScreenType { get { return virtualGreenScreenType; } set { virtualGreenScreenType = value; } }
	float OVRMixedRealityCaptureConfiguration.virtualGreenScreenTopY { get { return virtualGreenScreenTopY; } set { virtualGreenScreenTopY = value; } }
	float OVRMixedRealityCaptureConfiguration.virtualGreenScreenBottomY { get { return virtualGreenScreenBottomY; } set { virtualGreenScreenBottomY = value; } }
	bool OVRMixedRealityCaptureConfiguration.virtualGreenScreenApplyDepthCulling { get { return virtualGreenScreenApplyDepthCulling; } set { virtualGreenScreenApplyDepthCulling = value; } }
	float OVRMixedRealityCaptureConfiguration.virtualGreenScreenDepthTolerance { get { return virtualGreenScreenDepthTolerance; } set { virtualGreenScreenDepthTolerance = value; } }
	MrcActivationMode OVRMixedRealityCaptureConfiguration.mrcActivationMode { get { return mrcActivationMode; } set { mrcActivationMode = value; } }
	InstantiateMrcCameraDelegate OVRMixedRealityCaptureConfiguration.instantiateMixedRealityCameraGameObject { get { return instantiateMixedRealityCameraGameObject; } set { instantiateMixedRealityCameraGameObject = value; } }

#endif


	/// <summary>
	/// The native XR API being used
	/// </summary>
	public XrApi xrApi
	{
		get
		{
			return (XrApi)OVRPlugin.nativeXrApi;
		}
	}

	/// <summary>
	/// The value of current XrInstance when using OpenXR
	/// </summary>
	public UInt64 xrInstance
	{
		get
		{
			return OVRPlugin.GetNativeOpenXRInstance();
		}
	}

	/// <summary>
	/// The value of current XrSession when using OpenXR
	/// </summary>
	public UInt64 xrSession
	{
		get
		{
			return OVRPlugin.GetNativeOpenXRSession();
		}
	}

	/// <summary>
	/// The number of expected display frames per rendered frame.
	/// </summary>
	public int vsyncCount
	{
		get {
			if (!isHmdPresent)
				return 1;

			return OVRPlugin.vsyncCount;
		}

		set {
			if (!isHmdPresent)
				return;

			OVRPlugin.vsyncCount = value;
		}
	}

	public static string OCULUS_UNITY_NAME_STR = "Oculus";
	public static string OPENVR_UNITY_NAME_STR = "OpenVR";

	public static XRDevice loadedXRDevice;

	/// <summary>
	/// Gets the current battery level.
	/// </summary>
	/// <returns><c>battery level in the range [0.0,1.0]</c>
	/// <param name="batteryLevel">Battery level.</param>
	public static float batteryLevel
	{
		get {
			if (!isHmdPresent)
				return 1f;

			return OVRPlugin.batteryLevel;
		}
	}

	/// <summary>
	/// Gets the current battery temperature.
	/// </summary>
	/// <returns><c>battery temperature in Celsius</c>
	/// <param name="batteryTemperature">Battery temperature.</param>
	public static float batteryTemperature
	{
		get {
			if (!isHmdPresent)
				return 0f;

			return OVRPlugin.batteryTemperature;
		}
	}

	/// <summary>
	/// Gets the current battery status.
	/// </summary>
	/// <returns><c>battery status</c>
	/// <param name="batteryStatus">Battery status.</param>
	public static int batteryStatus
	{
		get {
			if (!isHmdPresent)
				return -1;

			return (int)OVRPlugin.batteryStatus;
		}
	}

	/// <summary>
	/// Gets the current volume level.
	/// </summary>
	/// <returns><c>volume level in the range [0,1].</c>
	public static float volumeLevel
	{
		get {
			if (!isHmdPresent)
				return 0f;

			return OVRPlugin.systemVolume;
		}
	}

	/// <summary>
	/// Gets or sets the current CPU performance level (0-2). Lower performance levels save more power.
	/// </summary>
	public static int cpuLevel
	{
		get {
			if (!isHmdPresent)
				return 2;

			return OVRPlugin.cpuLevel;
		}

		set {
			if (!isHmdPresent)
				return;

			OVRPlugin.cpuLevel = value;
		}
	}

	/// <summary>
	/// Gets or sets the current GPU performance level (0-2). Lower performance levels save more power.
	/// </summary>
	public static int gpuLevel
	{
		get {
			if (!isHmdPresent)
				return 2;

			return OVRPlugin.gpuLevel;
		}

		set {
			if (!isHmdPresent)
				return;

			OVRPlugin.gpuLevel = value;
		}
	}

	/// <summary>
	/// If true, the CPU and GPU are currently throttled to save power and/or reduce the temperature.
	/// </summary>
	public static bool isPowerSavingActive
	{
		get {
			if (!isHmdPresent)
				return false;

			return OVRPlugin.powerSaving;
		}
	}

	/// <summary>
	/// Gets or sets the eye texture format.
	/// </summary>
	public static EyeTextureFormat eyeTextureFormat
	{
		get
		{
			return (OVRManager.EyeTextureFormat)OVRPlugin.GetDesiredEyeTextureFormat();
		}

		set
		{
			OVRPlugin.SetDesiredEyeTextureFormat((OVRPlugin.EyeTextureFormat)value);
		}
	}

	/// <summary>
	/// Gets if tiled-based multi-resolution technique is supported
	/// This feature is only supported on QCOMM-based Android devices
	/// </summary>
	public static bool fixedFoveatedRenderingSupported
	{
		get
		{
			return OVRPlugin.fixedFoveatedRenderingSupported;
		}
	}

	/// <summary>
	/// Gets or sets the tiled-based multi-resolution level
	/// This feature is only supported on QCOMM-based Android devices
	/// </summary>
	public static FixedFoveatedRenderingLevel fixedFoveatedRenderingLevel
	{
		get
		{
			if (!OVRPlugin.fixedFoveatedRenderingSupported)
			{
				Debug.LogWarning("Fixed Foveated Rendering feature is not supported");
			}
			return (FixedFoveatedRenderingLevel)OVRPlugin.fixedFoveatedRenderingLevel;
		}
		set
		{
			if (!OVRPlugin.fixedFoveatedRenderingSupported)
			{
				Debug.LogWarning("Fixed Foveated Rendering feature is not supported");
			}
			OVRPlugin.fixedFoveatedRenderingLevel = (OVRPlugin.FixedFoveatedRenderingLevel)value;
		}
	}

	/// <summary>
	/// Let the system decide the best foveation level adaptively (Off .. fixedFoveatedRenderingLevel)
	/// This feature is only supported on QCOMM-based Android devices
	/// </summary>
	public static bool useDynamicFixedFoveatedRendering
	{
		get
		{
			if (!OVRPlugin.fixedFoveatedRenderingSupported)
			{
				Debug.LogWarning("Fixed Foveated Rendering feature is not supported");
			}
			return OVRPlugin.useDynamicFixedFoveatedRendering;
		}
		set
		{
			if (!OVRPlugin.fixedFoveatedRenderingSupported)
			{
				Debug.LogWarning("Fixed Foveated Rendering feature is not supported");
			}
			OVRPlugin.useDynamicFixedFoveatedRendering = value;
		}
	}

	[Obsolete("Please use fixedFoveatedRenderingSupported instead", false)]
	public static bool tiledMultiResSupported
	{
		get
		{
			return OVRPlugin.tiledMultiResSupported;
		}
	}

	[Obsolete("Please use fixedFoveatedRenderingLevel instead", false)]
	public static TiledMultiResLevel tiledMultiResLevel
	{
		get
		{
			if (!OVRPlugin.tiledMultiResSupported)
			{
				Debug.LogWarning("Tiled-based Multi-resolution feature is not supported");
			}
			return (TiledMultiResLevel)OVRPlugin.tiledMultiResLevel;
		}
		set
		{
			if (!OVRPlugin.tiledMultiResSupported)
			{
				Debug.LogWarning("Tiled-based Multi-resolution feature is not supported");
			}
			OVRPlugin.tiledMultiResLevel = (OVRPlugin.TiledMultiResLevel)value;
		}
	}

	/// <summary>
	/// Gets if the GPU Utility is supported
	/// This feature is only supported on QCOMM-based Android devices
	/// </summary>
	public static bool gpuUtilSupported
	{
		get
		{
			return OVRPlugin.gpuUtilSupported;
		}
	}

	/// <summary>
	/// Gets the GPU Utilised Level (0.0 - 1.0)
	/// This feature is only supported on QCOMM-based Android devices
	/// </summary>
	public static float gpuUtilLevel
	{
		get
		{
			if (!OVRPlugin.gpuUtilSupported)
			{
				Debug.LogWarning("GPU Util is not supported");
			}
			return OVRPlugin.gpuUtilLevel;
		}
	}

	/// <summary>
	/// Get the system headset type
	/// </summary>
	public static SystemHeadsetType systemHeadsetType
	{
		get
		{
			return (SystemHeadsetType)OVRPlugin.GetSystemHeadsetType();
		}
	}

	/// <summary>
	/// Sets the Color Scale and Offset which is commonly used for effects like fade-to-black.
	/// In our compositor, once a given frame is rendered, warped, and ready to be displayed, we then multiply
	/// each pixel by colorScale and add it to colorOffset, whereby newPixel = oldPixel * colorScale + colorOffset.
	/// Note that for mobile devices (Quest, etc.), colorOffset is only supported with OpenXR, so colorScale is all that can
	/// be used. A colorScale of (1, 1, 1, 1) and colorOffset of (0, 0, 0, 0) will lead to an identity multiplication
	/// and have no effect.
	/// </summary>
	public static void SetColorScaleAndOffset(Vector4 colorScale, Vector4 colorOffset, bool applyToAllLayers)
	{
		OVRPlugin.SetColorScaleAndOffset(colorScale, colorOffset, applyToAllLayers);
	}

	/// <summary>
	/// Specifies OpenVR pose local to tracking space
	/// </summary>
	public static void SetOpenVRLocalPose(Vector3 leftPos, Vector3 rightPos, Quaternion leftRot, Quaternion rightRot)
	{
		if (loadedXRDevice == XRDevice.OpenVR)
			OVRInput.SetOpenVRLocalPose(leftPos, rightPos, leftRot, rightRot);
	}

	//Series of offsets that line up the virtual controllers to the phsyical world.
	private static Vector3 OpenVRTouchRotationOffsetEulerLeft = new Vector3(40.0f, 0.0f, 0.0f);
	private static Vector3 OpenVRTouchRotationOffsetEulerRight = new Vector3(40.0f, 0.0f, 0.0f);
	private static Vector3 OpenVRTouchPositionOffsetLeft = new Vector3(0.0075f, -0.005f, -0.0525f);
	private static Vector3 OpenVRTouchPositionOffsetRight = new Vector3(-0.0075f, -0.005f, -0.0525f);

	/// <summary>
	/// Specifies the pose offset required to make an OpenVR controller's reported pose match the virtual pose.
	/// Currently we only specify this offset for Oculus Touch on OpenVR.
	/// </summary>
	public static OVRPose GetOpenVRControllerOffset(Node hand)
	{
		OVRPose poseOffset = OVRPose.identity;
		if ((hand == Node.LeftHand || hand == Node.RightHand) && loadedXRDevice == XRDevice.OpenVR)
		{
			int index = (hand == Node.LeftHand) ? 0 : 1;
			if (OVRInput.openVRControllerDetails[index].controllerType == OVRInput.OpenVRController.OculusTouch)
			{
				Vector3 offsetOrientation = (hand == Node.LeftHand) ? OpenVRTouchRotationOffsetEulerLeft : OpenVRTouchRotationOffsetEulerRight;
				poseOffset.orientation = Quaternion.Euler(offsetOrientation.x, offsetOrientation.y, offsetOrientation.z);
				poseOffset.position = (hand == Node.LeftHand) ? OpenVRTouchPositionOffsetLeft : OpenVRTouchPositionOffsetRight;
			}
		}
		return poseOffset;
	}


	[Header("Tracking")]
	[SerializeField]
	[Tooltip("Defines the current tracking origin type.")]
	private OVRManager.TrackingOrigin _trackingOriginType = OVRManager.TrackingOrigin.EyeLevel;
	/// <summary>
	/// Defines the current tracking origin type.
	/// </summary>
	public OVRManager.TrackingOrigin trackingOriginType
	{
		get {
			if (!isHmdPresent)
				return _trackingOriginType;

			return (OVRManager.TrackingOrigin)OVRPlugin.GetTrackingOriginType();
		}

		set {
			if (!isHmdPresent)
				return;

			if (OVRPlugin.SetTrackingOriginType((OVRPlugin.TrackingOrigin)value))
			{
				// Keep the field exposed in the Unity Editor synchronized with any changes.
				_trackingOriginType = value;
			}
		}
	}

	/// <summary>
	/// If true, head tracking will affect the position of each OVRCameraRig's cameras.
	/// </summary>
	[Tooltip("If true, head tracking will affect the position of each OVRCameraRig's cameras.")]
	public bool usePositionTracking = true;

	/// <summary>
	/// If true, head tracking will affect the rotation of each OVRCameraRig's cameras.
	/// </summary>
	[HideInInspector]
	public bool useRotationTracking = true;

	/// <summary>
	/// If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.
	/// </summary>
	[Tooltip("If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.")]
	public bool useIPDInPositionTracking = true;

	/// <summary>
	/// If true, each scene load will cause the head pose to reset. This function only works on Rift.
	/// </summary>
	[Tooltip("If true, each scene load will cause the head pose to reset. This function only works on Rift.")]
	public bool resetTrackerOnLoad = false;

	/// <summary>
	/// If true, the Reset View in the universal menu will cause the pose to be reset. This should generally be
	/// enabled for applications with a stationary position in the virtual world and will allow the View Reset
	/// command to place the person back to a predefined location (such as a cockpit seat).
	/// Set this to false if you have a locomotion system because resetting the view would effectively teleport
	/// the player to potentially invalid locations.
	/// </summary>
	[Tooltip("If true, the Reset View in the universal menu will cause the pose to be reset. This should generally be enabled for applications with a stationary position in the virtual world and will allow the View Reset command to place the person back to a predefined location (such as a cockpit seat). Set this to false if you have a locomotion system because resetting the view would effectively teleport the player to potentially invalid locations.")]
    public bool AllowRecenter = true;

	/// <summary>
	/// If true, a lower-latency update will occur right before rendering. If false, the only controller pose update will occur at the start of simulation for a given frame.
	/// Selecting this option lowers rendered latency for controllers and is often a net positive; however, it also creates a slight disconnect between rendered and simulated controller poses.
	/// Visit online Oculus documentation to learn more.
	/// </summary>
	[Tooltip("If true, rendered controller latency is reduced by several ms, as the left/right controllers will have their positions updated right before rendering.")]
	public bool LateControllerUpdate = true;

	/// <summary>
	/// True if the current platform supports virtual reality.
	/// </summary>
	public bool isSupportedPlatform { get; private set; }

	private static bool _isUserPresentCached = false;
	private static bool _isUserPresent = false;
	private static bool _wasUserPresent = false;
	/// <summary>
	/// True if the user is currently wearing the display.
	/// </summary>
	public bool isUserPresent
	{
		get {
			if (!_isUserPresentCached)
			{
				_isUserPresentCached = true;
				_isUserPresent = OVRPlugin.userPresent;
			}

			return _isUserPresent;
		}

		private set {
			_isUserPresentCached = true;
			_isUserPresent = value;
		}
	}

	private static bool prevAudioOutIdIsCached = false;
	private static bool prevAudioInIdIsCached = false;
	private static string prevAudioOutId = string.Empty;
	private static string prevAudioInId = string.Empty;
	private static bool wasPositionTracked = false;

	private static OVRPlugin.EventDataBuffer eventDataBuffer = new OVRPlugin.EventDataBuffer();

	public static System.Version utilitiesVersion
	{
		get { return OVRPlugin.wrapperVersion; }
	}

	public static System.Version pluginVersion
	{
		get { return OVRPlugin.version; }
	}

	public static System.Version sdkVersion
	{
		get { return OVRPlugin.nativeSDKVersion; }
	}

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_ANDROID
	private static bool MixedRealityEnabledFromCmd()
	{
		var args = System.Environment.GetCommandLineArgs();
		for (int i = 0; i < args.Length; i++)
		{
			if (args[i].ToLower() == "-mixedreality")
				return true;
		}
		return false;
	}

	private static bool UseDirectCompositionFromCmd()
	{
		var args = System.Environment.GetCommandLineArgs();
		for (int i = 0; i < args.Length; i++)
		{
			if (args[i].ToLower() == "-directcomposition")
				return true;
		}
		return false;
	}

	private static bool UseExternalCompositionFromCmd()
	{
		var args = System.Environment.GetCommandLineArgs();
		for (int i = 0; i < args.Length; i++)
		{
			if (args[i].ToLower() == "-externalcomposition")
				return true;
		}
		return false;
	}

	private static bool CreateMixedRealityCaptureConfigurationFileFromCmd()
	{
		var args = System.Environment.GetCommandLineArgs();
		for (int i = 0; i < args.Length; i++)
		{
			if (args[i].ToLower() == "-create_mrc_config")
				return true;
		}
		return false;
	}

	private static bool LoadMixedRealityCaptureConfigurationFileFromCmd()
	{
		var args = System.Environment.GetCommandLineArgs();
		for (int i = 0; i < args.Length; i++)
		{
			if (args[i].ToLower() == "-load_mrc_config")
				return true;
		}
		return false;
	}
#endif

	public static bool IsUnityAlphaOrBetaVersion()
	{
		string ver = Application.unityVersion;
		int pos = ver.Length - 1;

		while (pos >= 0 && ver[pos] >= '0' && ver[pos] <= '9')
		{
			--pos;
		}

		if (pos >= 0 && (ver[pos] == 'a' || ver[pos] == 'b'))
			return true;

		return false;
	}

	public static string UnityAlphaOrBetaVersionWarningMessage = "WARNING: It's not recommended to use Unity alpha/beta release in Oculus development. Use a stable release if you encounter any issue.";

#region Unity Messages

	public static bool OVRManagerinitialized = false;
	private void InitOVRManager()
	{
		// Only allow one instance at runtime.
		if (instance != null)
		{
			enabled = false;
			DestroyImmediate(this);
			return;
		}

		instance = this;

		// uncomment the following line to disable the callstack printed to log
		//Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);  // TEMPORARY

		Debug.Log("Unity v" + Application.unityVersion + ", " +
				"Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " +
				"OVRPlugin v" + OVRPlugin.version + ", " +
				"SDK v" + OVRPlugin.nativeSDKVersion + ".");

		Debug.LogFormat("SystemHeadset {0}, API {1}", systemHeadsetType.ToString(), xrApi.ToString());

		if (xrApi == XrApi.OpenXR)
		{
			Debug.LogFormat("OpenXR instance 0x{0:X} session 0x{1:X}", xrInstance, xrSession);
		}

#if !UNITY_EDITOR
		if (IsUnityAlphaOrBetaVersion())
		{
			Debug.LogWarning(UnityAlphaOrBetaVersionWarningMessage);
		}
#endif

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
		var supportedTypes =
			UnityEngine.Rendering.GraphicsDeviceType.Direct3D11.ToString() + ", " +
			UnityEngine.Rendering.GraphicsDeviceType.Direct3D12.ToString();

		if (!supportedTypes.Contains(SystemInfo.graphicsDeviceType.ToString()))
			Debug.LogWarning("VR rendering requires one of the following device types: (" + supportedTypes + "). Your graphics device: " + SystemInfo.graphicsDeviceType.ToString());
#endif

		// Detect whether this platform is a supported platform
		RuntimePlatform currPlatform = Application.platform;
		if (currPlatform == RuntimePlatform.Android ||
			// currPlatform == RuntimePlatform.LinuxPlayer ||
			currPlatform == RuntimePlatform.OSXEditor ||
			currPlatform == RuntimePlatform.OSXPlayer ||
			currPlatform == RuntimePlatform.WindowsEditor ||
			currPlatform == RuntimePlatform.WindowsPlayer)
		{
			isSupportedPlatform = true;
		}
		else
		{
			isSupportedPlatform = false;
		}
		if (!isSupportedPlatform)
		{
			Debug.LogWarning("This platform is unsupported");
			return;
		}

#if UNITY_ANDROID && !UNITY_EDITOR
		// Turn off chromatic aberration by default to save texture bandwidth.
		chromatic = false;
#endif

#if (UNITY_STANDALONE_WIN || UNITY_ANDROID) && !UNITY_EDITOR
		enableMixedReality = false;		// we should never start the standalone game in MxR mode, unless the command-line parameter is provided
#endif

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
		if (!staticMixedRealityCaptureInitialized)
		{
			bool loadMrcConfig = LoadMixedRealityCaptureConfigurationFileFromCmd();
			bool createMrcConfig = CreateMixedRealityCaptureConfigurationFileFromCmd();

			if (loadMrcConfig || createMrcConfig)
			{
				OVRMixedRealityCaptureSettings mrcSettings = ScriptableObject.CreateInstance<OVRMixedRealityCaptureSettings>();
				mrcSettings.ReadFrom(this);
				if (loadMrcConfig)
				{
					mrcSettings.CombineWithConfigurationFile();
					mrcSettings.ApplyTo(this);
				}
				if (createMrcConfig)
				{
					mrcSettings.WriteToConfigurationFile();
				}
				ScriptableObject.Destroy(mrcSettings);
			}

			if (MixedRealityEnabledFromCmd())
			{
				enableMixedReality = true;
			}

			if (enableMixedReality)
			{
				Debug.Log("OVR: Mixed Reality mode enabled");
				if (UseDirectCompositionFromCmd())
				{
					compositionMethod = CompositionMethod.Direct;
				}
				if (UseExternalCompositionFromCmd())
				{
					compositionMethod = CompositionMethod.External;
				}
				Debug.Log("OVR: CompositionMethod : " + compositionMethod);
			}
		}
#endif

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
		StaticInitializeMixedRealityCapture(this);
#endif

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
		if (enableAdaptiveResolution && !OVRManager.IsAdaptiveResSupportedByEngine())
		{
			enableAdaptiveResolution = false;
			UnityEngine.Debug.LogError("Your current Unity Engine " + Application.unityVersion + " might have issues to support adaptive resolution, please disable it under OVRManager");
		}
#endif

		Initialize();

		Debug.LogFormat("Current display frequency {0}, available frequencies [{1}]",
			display.displayFrequency, string.Join(", ", display.displayFrequenciesAvailable.Select(f => f.ToString()).ToArray()));

		if (resetTrackerOnLoad)
			display.RecenterPose();

		if (Debug.isDebugBuild)
		{
			// Activate system metrics collection in Debug/Developerment build
			if (GetComponent<OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer>() == null)
			{
				gameObject.AddComponent<OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer>();
			}
			OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer perfTcpServer = GetComponent<OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer>();
			perfTcpServer.listeningPort = profilerTcpPort;
			if (!perfTcpServer.enabled)
			{
				perfTcpServer.enabled = true;
			}
#if !UNITY_EDITOR
			OVRPlugin.SetDeveloperMode(OVRPlugin.Bool.True);
#endif
		}

		// Refresh the client color space
		OVRManager.ColorSpace clientColorSpace = colorGamut;
		colorGamut = clientColorSpace;

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
		// Force OcculusionMesh on all the time, you can change the value to false if you really need it be off for some reasons,
		// be aware there are performance drops if you don't use occlusionMesh.
		OVRPlugin.occlusionMesh = true;
#endif

		OVRManagerinitialized = true;

	}

	private void Awake()
	{
#if !USING_XR_SDK
		//For legacy, we should initialize OVRManager in all cases.
		//For now, in XR SDK, only initialize if OVRPlugin is initialized.
		InitOVRManager();
#else
		if (OVRPlugin.initialized)
			InitOVRManager();
#endif
	}

#if UNITY_EDITOR
	private static bool _scriptsReloaded;

	[UnityEditor.Callbacks.DidReloadScripts]
	static void ScriptsReloaded()
	{
		_scriptsReloaded = true;
	}
#endif

	void SetCurrentXRDevice()
	{
#if USING_XR_SDK
		XRDisplaySubsystem currentDisplaySubsystem = GetCurrentDisplaySubsystem();
		XRDisplaySubsystemDescriptor currentDisplaySubsystemDescriptor = GetCurrentDisplaySubsystemDescriptor();
#endif
		if (OVRPlugin.initialized)
		{
			loadedXRDevice = XRDevice.Oculus;
		}
#if USING_XR_SDK
		else if (currentDisplaySubsystem != null && currentDisplaySubsystemDescriptor != null && currentDisplaySubsystem.running)
#else
		else if (Settings.enabled)
#endif
		{
#if USING_XR_SDK
			string loadedXRDeviceName = currentDisplaySubsystemDescriptor.id;
#else
			string loadedXRDeviceName = Settings.loadedDeviceName;
#endif
			if (loadedXRDeviceName == OPENVR_UNITY_NAME_STR)
				loadedXRDevice = XRDevice.OpenVR;
			else
				loadedXRDevice = XRDevice.Unknown;
		}
		else
		{
			loadedXRDevice = XRDevice.Unknown;
		}
	}

#if USING_XR_SDK
	static List<XRDisplaySubsystem> s_displaySubsystems;
	public static XRDisplaySubsystem GetCurrentDisplaySubsystem()
	{
		if (s_displaySubsystems == null)
			s_displaySubsystems = new List<XRDisplaySubsystem>();
		SubsystemManager.GetInstances(s_displaySubsystems);
		if (s_displaySubsystems.Count > 0)
			return s_displaySubsystems[0];
		return null;
	}

	static List<XRDisplaySubsystemDescriptor> s_displaySubsystemDescriptors;
	public static XRDisplaySubsystemDescriptor GetCurrentDisplaySubsystemDescriptor()
	{
		if (s_displaySubsystemDescriptors == null)
			s_displaySubsystemDescriptors = new List<XRDisplaySubsystemDescriptor>();
		SubsystemManager.GetSubsystemDescriptors(s_displaySubsystemDescriptors);
		if (s_displaySubsystemDescriptors.Count > 0)
			return s_displaySubsystemDescriptors[0];
		return null;
	}

	static List<XRInputSubsystem> s_inputSubsystems;
	public static XRInputSubsystem GetCurrentInputSubsystem()
	{
		if (s_inputSubsystems == null)
			s_inputSubsystems = new List<XRInputSubsystem>();
		SubsystemManager.GetInstances(s_inputSubsystems);
		if (s_inputSubsystems.Count > 0)
			return s_inputSubsystems[0];
		return null;
	}
#endif

	void Initialize()
	{
		if (display == null)
			display = new OVRDisplay();
		if (tracker == null)
			tracker = new OVRTracker();
		if (boundary == null)
			boundary = new OVRBoundary();

		SetCurrentXRDevice();
	}

	private void Update()
	{
		//Only if we're using the XR SDK do we have to check if OVRManager isn't yet initialized, and init it.
		//If we're on legacy, we know initialization occurred properly in Awake()
#if USING_XR_SDK
		if (!OVRManagerinitialized)
		{
			XRDisplaySubsystem currentDisplaySubsystem = GetCurrentDisplaySubsystem();
			XRDisplaySubsystemDescriptor currentDisplaySubsystemDescriptor = GetCurrentDisplaySubsystemDescriptor();
			if (currentDisplaySubsystem == null || currentDisplaySubsystemDescriptor == null || !OVRPlugin.initialized)
				return;
			//If we're using the XR SDK and the display subsystem is present, and OVRPlugin is initialized, we can init OVRManager
			InitOVRManager();
		}
#endif

#if UNITY_EDITOR
		if (_scriptsReloaded)
		{
			_scriptsReloaded = false;
			instance = this;
			Initialize();
		}
#endif

		SetCurrentXRDevice();

		if (OVRPlugin.shouldQuit)
		{
			Debug.Log("[OVRManager] OVRPlugin.shouldQuit detected");
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
			StaticShutdownMixedRealityCapture(instance);
#endif
			Application.Quit();
		}

		if (AllowRecenter && OVRPlugin.shouldRecenter)
		{
			OVRManager.display.RecenterPose();
		}

		if (trackingOriginType != _trackingOriginType)
			trackingOriginType = _trackingOriginType;

		tracker.isEnabled = usePositionTracking;

		OVRPlugin.rotation = useRotationTracking;

		OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking;

		// Dispatch HMD events.

		isHmdPresent = OVRNodeStateProperties.IsHmdPresent();

		if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel)
		{
			Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing +
			", but the recommended MSAA level is " + display.recommendedMSAALevel +
			". Switching to the recommended level.");

			QualitySettings.antiAliasing = display.recommendedMSAALevel;
		}

		if (monoscopic != _monoscopic)
		{
			monoscopic = _monoscopic;
		}

		if (headPoseRelativeOffsetRotation != _headPoseRelativeOffsetRotation)
		{
			headPoseRelativeOffsetRotation = _headPoseRelativeOffsetRotation;
		}

		if (headPoseRelativeOffsetTranslation != _headPoseRelativeOffsetTranslation)
		{
			headPoseRelativeOffsetTranslation = _headPoseRelativeOffsetTranslation;
		}

		if (_wasHmdPresent && !isHmdPresent)
		{
			try
			{
				Debug.Log("[OVRManager] HMDLost event");
				if (HMDLost != null)
					HMDLost();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		if (!_wasHmdPresent && isHmdPresent)
		{
			try
			{
				Debug.Log("[OVRManager] HMDAcquired event");
				if (HMDAcquired != null)
					HMDAcquired();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		_wasHmdPresent = isHmdPresent;

		// Dispatch HMD mounted events.

		isUserPresent = OVRPlugin.userPresent;

		if (_wasUserPresent && !isUserPresent)
		{
			try
			{
				Debug.Log("[OVRManager] HMDUnmounted event");
				if (HMDUnmounted != null)
					HMDUnmounted();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		if (!_wasUserPresent && isUserPresent)
		{
			try
			{
				Debug.Log("[OVRManager] HMDMounted event");
				if (HMDMounted != null)
					HMDMounted();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		_wasUserPresent = isUserPresent;

		// Dispatch VR Focus events.

		hasVrFocus = OVRPlugin.hasVrFocus;

		if (_hadVrFocus && !hasVrFocus)
		{
			try
			{
				Debug.Log("[OVRManager] VrFocusLost event");
				if (VrFocusLost != null)
					VrFocusLost();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		if (!_hadVrFocus && hasVrFocus)
		{
			try
			{
				Debug.Log("[OVRManager] VrFocusAcquired event");
				if (VrFocusAcquired != null)
					VrFocusAcquired();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		_hadVrFocus = hasVrFocus;

		// Dispatch VR Input events.

		bool hasInputFocus = OVRPlugin.hasInputFocus;

		if (_hadInputFocus && !hasInputFocus)
		{
			try
			{
				Debug.Log("[OVRManager] InputFocusLost event");
				if (InputFocusLost != null)
					InputFocusLost();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		if (!_hadInputFocus && hasInputFocus)
		{
			try
			{
				Debug.Log("[OVRManager] InputFocusAcquired event");
				if (InputFocusAcquired != null)
					InputFocusAcquired();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		_hadInputFocus = hasInputFocus;

		// Changing effective rendering resolution dynamically according performance
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN)

		if (enableAdaptiveResolution)
		{
			if (Settings.eyeTextureResolutionScale < maxRenderScale)
			{
				// Allocate renderScale to max to avoid re-allocation
				Settings.eyeTextureResolutionScale = maxRenderScale;
			}
			else
			{
				// Adjusting maxRenderScale in case app started with a larger renderScale value
				maxRenderScale = Mathf.Max(maxRenderScale, Settings.eyeTextureResolutionScale);
			}
			minRenderScale = Mathf.Min(minRenderScale, maxRenderScale);
			float minViewportScale = minRenderScale / Settings.eyeTextureResolutionScale;
			float recommendedViewportScale = Mathf.Clamp(Mathf.Sqrt(OVRPlugin.GetAdaptiveGPUPerformanceScale()) * Settings.eyeTextureResolutionScale * Settings.renderViewportScale, 0.5f, 2.0f);
			recommendedViewportScale /= Settings.eyeTextureResolutionScale;
			recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f);
			Settings.renderViewportScale = recommendedViewportScale;
		}
#endif

		// Dispatch Audio Device events.

		string audioOutId = OVRPlugin.audioOutId;
		if (!prevAudioOutIdIsCached)
		{
			prevAudioOutId = audioOutId;
			prevAudioOutIdIsCached = true;
		}
		else if (audioOutId != prevAudioOutId)
		{
			try
			{
				Debug.Log("[OVRManager] AudioOutChanged event");
				if (AudioOutChanged != null)
					AudioOutChanged();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}

			prevAudioOutId = audioOutId;
		}

		string audioInId = OVRPlugin.audioInId;
		if (!prevAudioInIdIsCached)
		{
			prevAudioInId = audioInId;
			prevAudioInIdIsCached = true;
		}
		else if (audioInId != prevAudioInId)
		{
			try
			{
				Debug.Log("[OVRManager] AudioInChanged event");
				if (AudioInChanged != null)
					AudioInChanged();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}

			prevAudioInId = audioInId;
		}

		// Dispatch tracking events.

		if (wasPositionTracked && !tracker.isPositionTracked)
		{
			try
			{
				Debug.Log("[OVRManager] TrackingLost event");
				if (TrackingLost != null)
					TrackingLost();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		if (!wasPositionTracked && tracker.isPositionTracked)
		{
			try
			{
				Debug.Log("[OVRManager] TrackingAcquired event");
				if (TrackingAcquired != null)
					TrackingAcquired();
			}
			catch (Exception e)
			{
				Debug.LogError("Caught Exception: " + e);
			}
		}

		wasPositionTracked = tracker.isPositionTracked;

		display.Update();
		OVRInput.Update();

		UpdateHMDEvents();

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
		StaticUpdateMixedRealityCapture(this, gameObject, trackingOriginType);
#endif
	}

	private void UpdateHMDEvents()
	{
		while(OVRPlugin.PollEvent(ref eventDataBuffer))
		{
			switch(eventDataBuffer.EventType)
			{
				case OVRPlugin.EventType.DisplayRefreshRateChanged:
					if(DisplayRefreshRateChanged != null)
					{
						float FromRefreshRate = BitConverter.ToSingle(eventDataBuffer.EventData, 0);
						float ToRefreshRate = BitConverter.ToSingle(eventDataBuffer.EventData, 4);
						DisplayRefreshRateChanged(FromRefreshRate, ToRefreshRate);
					}
					break;
				default:
					break;
			}
		}
	}

	private static bool multipleMainCameraWarningPresented = false;
	private static WeakReference<Camera> lastFoundMainCamera = null;
	private static Camera FindMainCamera() {

		Camera lastCamera;
		if (lastFoundMainCamera != null && 
		    lastFoundMainCamera.TryGetTarget(out lastCamera) && 
		    lastCamera != null && 
		    lastCamera.CompareTag("MainCamera"))
		{
			return lastCamera;
		}

		Camera result = null;

		GameObject[] objects = GameObject.FindGameObjectsWithTag("MainCamera");
		List<Camera> cameras = new List<Camera>(4);
		foreach (GameObject obj in objects)
		{
			Camera camera = obj.GetComponent<Camera>();
			if (camera != null && camera.enabled)
			{
				OVRCameraRig cameraRig = camera.GetComponentInParent<OVRCameraRig>();
				if (cameraRig != null && cameraRig.trackingSpace != null)
				{
					cameras.Add(camera);
				}
			}
		}
		if (cameras.Count == 0)
		{
			result = Camera.main; // pick one of the cameras which tagged as "MainCamera"
		}
		else if (cameras.Count == 1)
		{
			result = cameras[0];
		}
		else
		{
			if (!multipleMainCameraWarningPresented)
			{
				Debug.LogWarning("Multiple MainCamera found. Assume the real MainCamera is the camera with the least depth");
				multipleMainCameraWarningPresented = true;
			}
			// return the camera with least depth
			cameras.Sort((Camera c0, Camera c1) => { return c0.depth < c1.depth ? -1 : (c0.depth > c1.depth ? 1 : 0); });
			result = cameras[0];
		}

		if (result != null)
		{
			Debug.LogFormat("[OVRManager] mainCamera found for MRC: ", result.gameObject.name);
		}
		else
		{
			Debug.Log("[OVRManager] unable to find a vaild camera");
		}
		lastFoundMainCamera = new WeakReference<Camera>(result);
		return result;
	}

	private void OnDisable()
	{
		OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer perfTcpServer = GetComponent<OVRSystemPerfMetrics.OVRSystemPerfMetricsTcpServer>();
		if (perfTcpServer != null)
		{
			perfTcpServer.enabled = false;
		}
	}

	private void LateUpdate()
	{
		OVRHaptics.Process();
	}

	private void FixedUpdate()
	{
		OVRInput.FixedUpdate();
	}

	private void OnDestroy()
	{
		Debug.Log("[OVRManager] OnDestroy");
		OVRManagerinitialized = false;
	}

	private void OnApplicationPause(bool pause)
	{
		if (pause)
		{
			Debug.Log("[OVRManager] OnApplicationPause(true)");
		}
		else
		{
			Debug.Log("[OVRManager] OnApplicationPause(false)");
		}
	}

	private void OnApplicationFocus(bool focus)
	{
		if (focus)
		{
			Debug.Log("[OVRManager] OnApplicationFocus(true)");
		}
		else
		{
			Debug.Log("[OVRManager] OnApplicationFocus(false)");
		}
	}

	private void OnApplicationQuit()
	{
		Debug.Log("[OVRManager] OnApplicationQuit");
	}

#endregion // Unity Messages

	/// <summary>
	/// Leaves the application/game and returns to the launcher/dashboard
	/// </summary>
	public void ReturnToLauncher()
	{
		// show the platform UI quit prompt
		OVRManager.PlatformUIConfirmQuit();
	}

	public static void PlatformUIConfirmQuit()
	{
		if (!isHmdPresent)
			return;

		OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit);
	}

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC

	public static bool staticMixedRealityCaptureInitialized = false;
	public static bool staticPrevEnableMixedRealityCapture = false;
	public static OVRMixedRealityCaptureSettings staticMrcSettings = null;
	private static bool suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false;

	public static void StaticInitializeMixedRealityCapture(OVRMixedRealityCaptureConfiguration configuration)
	{
		if (!staticMixedRealityCaptureInitialized)
		{
			staticMrcSettings = ScriptableObject.CreateInstance<OVRMixedRealityCaptureSettings>();
			staticMrcSettings.ReadFrom(configuration);

#if OVR_ANDROID_MRC
			bool mediaInitialized = OVRPlugin.Media.Initialize();
			Debug.Log(mediaInitialized ? "OVRPlugin.Media initialized" : "OVRPlugin.Media not initialized");
			if (mediaInitialized)
			{
				var audioConfig = AudioSettings.GetConfiguration();
				if(audioConfig.sampleRate > 0)
				{
					OVRPlugin.Media.SetMrcAudioSampleRate(audioConfig.sampleRate);
					Debug.LogFormat("[MRC] SetMrcAudioSampleRate({0})", audioConfig.sampleRate);
				}

				OVRPlugin.Media.SetMrcInputVideoBufferType(OVRPlugin.Media.InputVideoBufferType.TextureHandle);
				Debug.LogFormat("[MRC] Active InputVideoBufferType:{0}", OVRPlugin.Media.GetMrcInputVideoBufferType());
				if (configuration.mrcActivationMode == MrcActivationMode.Automatic)
				{
					OVRPlugin.Media.SetMrcActivationMode(OVRPlugin.Media.MrcActivationMode.Automatic);
					Debug.LogFormat("[MRC] ActivateMode: Automatic");
				}
				else if (configuration.mrcActivationMode == MrcActivationMode.Disabled)
				{
					OVRPlugin.Media.SetMrcActivationMode(OVRPlugin.Media.MrcActivationMode.Disabled);
					Debug.LogFormat("[MRC] ActivateMode: Disabled");
				}
				if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Vulkan)
				{
					OVRPlugin.Media.SetAvailableQueueIndexVulkan(1);
					OVRPlugin.Media.SetMrcFrameImageFlipped(true);
				}
			}
#endif
			staticPrevEnableMixedRealityCapture = false;

			staticMixedRealityCaptureInitialized = true;
		}
		else
		{
			staticMrcSettings.ApplyTo(configuration);
		}
	}

	public static void StaticUpdateMixedRealityCapture(OVRMixedRealityCaptureConfiguration configuration, GameObject gameObject, TrackingOrigin trackingOrigin)
	{
		if (!staticMixedRealityCaptureInitialized)
		{
			return;
		}

#if OVR_ANDROID_MRC
		configuration.enableMixedReality = OVRPlugin.Media.GetInitialized() && OVRPlugin.Media.IsMrcActivated();
		configuration.compositionMethod = CompositionMethod.External;		// force external composition on Android MRC

		if (OVRPlugin.Media.GetInitialized())
		{
			OVRPlugin.Media.Update();
		}
#endif

		if (configuration.enableMixedReality && !staticPrevEnableMixedRealityCapture)
		{
			OVRPlugin.SendEvent("mixed_reality_capture", "activated");
			Debug.Log("MixedRealityCapture: activate");
		}

		if (!configuration.enableMixedReality && staticPrevEnableMixedRealityCapture)
		{
			Debug.Log("MixedRealityCapture: deactivate");
		}

		if (configuration.enableMixedReality || staticPrevEnableMixedRealityCapture)
		{
			Camera mainCamera = FindMainCamera();
			if (mainCamera != null)
			{
				suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false;

				if (configuration.enableMixedReality)
				{
					OVRMixedReality.Update(gameObject, mainCamera, configuration, trackingOrigin);
				}

				if (staticPrevEnableMixedRealityCapture && !configuration.enableMixedReality)
				{
					OVRMixedReality.Cleanup();
				}

				staticPrevEnableMixedRealityCapture = configuration.enableMixedReality;
			}
			else
			{
				if (!suppressDisableMixedRealityBecauseOfNoMainCameraWarning)
				{
					Debug.LogWarning("Main Camera is not set, Mixed Reality disabled");
					suppressDisableMixedRealityBecauseOfNoMainCameraWarning = true;
				}
			}
		}

		staticMrcSettings.ReadFrom(configuration);
	}

	public static void StaticShutdownMixedRealityCapture(OVRMixedRealityCaptureConfiguration configuration)
	{
		if (staticMixedRealityCaptureInitialized)
		{
			ScriptableObject.Destroy(staticMrcSettings);
			staticMrcSettings = null;

			OVRMixedReality.Cleanup();

#if OVR_ANDROID_MRC
			if (OVRPlugin.Media.GetInitialized())
			{
				OVRPlugin.Media.Shutdown();
			}
#endif
			staticMixedRealityCaptureInitialized = false;
		}
	}

#endif


}