GSXRManager.cs 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.Events;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Runtime.InteropServices;
  8. using AOT;
  9. using SC.XR.Unity;
  10. public class GSXRManager : MonoBehaviour
  11. {
  12. public static GSXRManager Instance;
  13. //{
  14. // get
  15. // {
  16. // if (instance == null) instance = FindObjectOfType<GSXRManager>();
  17. // if (instance == null) Debug.LogError("GSXRManager object component not found");
  18. // return instance;
  19. // }
  20. //}
  21. //private static GSXRManager instance;
  22. static public int EyeLayerMax = 8;
  23. static public int OverlayLayerMax = 8;
  24. static public int RenderLayersMax = 16;
  25. public static Action SlamInitializedCallBack;
  26. //public static Action SlamOnPauseCallback;
  27. //public static Action SlamOnResumeCallback;
  28. [SerializeField]
  29. private SpecificationType m_SpecificationType = SpecificationType.GSXR;
  30. public SpecificationType SpecificationType {
  31. get { return m_SpecificationType; }
  32. private set { m_SpecificationType = value; }
  33. }
  34. public enum slamEventType
  35. {
  36. kEventNone = 0,
  37. kEventSdkServiceStarting = 1,
  38. kEventSdkServiceStarted = 2,
  39. kEventSdkServiceStopped = 3,
  40. kEventControllerConnecting = 4,
  41. kEventControllerConnected = 5,
  42. kEventControllerDisconnected = 6,
  43. kEventThermal = 7,
  44. kEventVrModeStarted = 8,
  45. kEventVrModeStopping = 9,
  46. kEventVrModeStopped = 10,
  47. kEventSensorError = 11,
  48. kEventMagnometerUncalibrated = 12,
  49. kEventBoundarySystemCollision = 13,
  50. kEvent6dofRelocation = 14,
  51. kEvent6dofWarningFeatureCount = 15,
  52. kEvent6dofWarningLowLight = 16,
  53. kEvent6dofWarningBrightLight = 17,
  54. kEvent6dofWarningCameraCalibration = 18
  55. }
  56. public enum controllerBondState
  57. {
  58. No_Bond = 0,
  59. Left_Bond = 1,
  60. Right_Bond = 2,
  61. Left_UnBond = 3,
  62. Right_UnBond = 4,
  63. OverTime_Bond = 5,
  64. Unknown = 6
  65. }
  66. [Serializable]
  67. public class SlamSettings
  68. {
  69. public enum eAntiAliasing
  70. {
  71. k1 = 1,
  72. k2 = 2,
  73. k4 = 4,
  74. };
  75. public enum eDepth
  76. {
  77. k16 = 16,
  78. k24 = 24
  79. };
  80. public enum eChromaticAberrationCorrection
  81. {
  82. kDisable = 0,
  83. kEnable = 1
  84. };
  85. public enum eVSyncCount
  86. {
  87. k0 = 0,
  88. k1 = 1,
  89. k2 = 2,
  90. };
  91. public enum eMasterTextureLimit
  92. {
  93. k0 = 0, // full size
  94. k1 = 1, // half size
  95. k2 = 2, // quarter size
  96. k3 = 3, // ...
  97. k4 = 4 // ...
  98. };
  99. public enum ePerfLevel
  100. {
  101. Minimum = 1,
  102. Medium = 2,
  103. Maximum = 3
  104. };
  105. public enum eFrustumType
  106. {
  107. Camera = 0,
  108. Device = 1,
  109. }
  110. public enum eEyeBufferType
  111. {
  112. //Mono = 0,
  113. StereoSeperate = 1,
  114. //StereoSingle = 2,
  115. //Array = 3,
  116. }
  117. [Tooltip("If head tracking lost, fade the display")]
  118. public bool poseStatusFade = true;
  119. [Tooltip("Use eye tracking (if available)")]
  120. public bool trackEyes = true;
  121. [Tooltip("Use position tracking (if available)")]
  122. public bool trackPosition = true;
  123. [Tooltip("Track position conversion from meters")]
  124. public float trackPositionScale = 1;
  125. [Tooltip("Height of the eyes from base of head")]
  126. public float headHeight = 0.0750f;
  127. [Tooltip("Depth of the eyes from center of head")]
  128. public float headDepth = 0.0805f;
  129. [Tooltip("Distance between the eyes")]
  130. public float interPupilDistance = 0.064f;
  131. //[Tooltip("Distance of line-of-sight convergence (0 disabled)")]
  132. //public float stereoConvergence = 0;
  133. //[Tooltip("Pitch angle to the horizon in degrees")]
  134. //public float horizonElevation = 0;
  135. [Tooltip("Eye field of view render target reprojection margin (% of fov) [0..]")]
  136. public float eyeFovMargin = 0.0f;
  137. [Tooltip("Eye render target scale factor")]
  138. public float eyeResolutionScaleFactor = 1.0f;
  139. [Tooltip("Eye render target depth buffer")]
  140. public eDepth eyeDepth = eDepth.k24;
  141. [Tooltip("Eye render target MSAA value")]
  142. public eAntiAliasing eyeAntiAliasing = eAntiAliasing.k2;
  143. [Tooltip("Overlay render target scale factor")]
  144. public float overlayResolutionScaleFactor = 1.0f;
  145. [Tooltip("Overlay render target depth buffer")]
  146. public eDepth overlayDepth = eDepth.k16;
  147. [Tooltip("Overlay render target MSAA value")]
  148. public eAntiAliasing overlayAntiAliasing = eAntiAliasing.k1;
  149. [Tooltip("Limit refresh rate")]
  150. public eVSyncCount vSyncCount = eVSyncCount.k1;
  151. [Tooltip("Chromatic Aberration Correction")]
  152. public eChromaticAberrationCorrection chromaticAberationCorrection = eChromaticAberrationCorrection.kEnable;
  153. [Tooltip("QualitySettings TextureQuality FullRes, HalfRes, etc.")]
  154. public eMasterTextureLimit masterTextureLimit = eMasterTextureLimit.k0;
  155. [Tooltip("CPU performance level")]
  156. public ePerfLevel cpuPerfLevel = ePerfLevel.Medium;
  157. [Tooltip("GPU performance level")]
  158. public ePerfLevel gpuPerfLevel = ePerfLevel.Medium;
  159. [Tooltip("Foveated render gain [1..], 0/feature disabled")]
  160. public Vector2 foveationGain = new Vector2(0.0f, 0.0f);
  161. [Tooltip("Foveated render hires area [0..]")]
  162. public float foveationArea = 0.0f;
  163. [Tooltip("Foveated render min pixel density [1/16..1]")]
  164. public float foveationMinimum = 0.25f;
  165. [Tooltip("Use perspective of unity camera or device frustum data")]
  166. public eFrustumType frustumType = eFrustumType.Camera;
  167. [Tooltip("Display buffer type (default stereo seperate)")]
  168. public eEyeBufferType displayType = eEyeBufferType.StereoSeperate;
  169. }
  170. [SerializeField]
  171. public SlamSettings settings;
  172. [Serializable]
  173. public class SlamStatus
  174. {
  175. [Tooltip("SnapdragonVR SDK Initialized")]
  176. public bool initialized = false;
  177. [Tooltip("SnapdragonVR SDK Running")]
  178. public bool running = false;
  179. [Tooltip("SnapdragonVR SDK Pose Status: 0/None, 1/Rotation, 2/Position, 3/RotationAndPosition")]
  180. public int pose = 0;
  181. }
  182. [SerializeField]
  183. public SlamStatus status;
  184. public enum eFadeState { FadeIn, FadeOut }
  185. [NonSerialized]
  186. public eFadeState fadeState = eFadeState.FadeIn;
  187. [NonSerialized]
  188. public float fadeDuration = 0.5f;
  189. [Header("Camera Rig")]
  190. public Transform head;
  191. public Transform gaze;
  192. public Camera monoCamera;
  193. public Camera leftCamera;
  194. public Camera rightCamera;
  195. public Camera leftOverlay;
  196. public Camera rightOverlay;
  197. public Camera monoOverlay;
  198. public GSXROverlay fadeOverlay;
  199. public GSXROverlay reticleOverlay;
  200. private bool IsUseOpticsCalibration = true;
  201. private bool IsUseCommonEvent = false;
  202. public Vector2 FocalPoint { get; set; } // Foveated Rendering Focal Point
  203. public int FrameCount { get { return frameCount; } }
  204. private int frameCount = 0;
  205. private static WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame();
  206. public GSXRPlugin plugin = null;
  207. private float sensorWarmupDuration = 0.25f;
  208. private List<GSXREye> eyes = new List<GSXREye>(EyeLayerMax);
  209. private List<GSXROverlay> overlays = new List<GSXROverlay>(OverlayLayerMax);
  210. private bool disableInput = false;
  211. private Coroutine onResume = null;
  212. private Coroutine submitFrame = null;
  213. private Matrix4x4 headDeltaInitLocalToWorld = Matrix4x4.identity;
  214. public Material DepthM;
  215. public bool IsCreateDepthRT = false;
  216. private bool IsDontDestroyOnLoad = true;
  217. /// <summary>
  218. /// Slam event listener.
  219. /// </summary>
  220. public interface SlamEventListener {
  221. /// <summary>
  222. /// Raises the slam event event.
  223. /// </summary>
  224. /// <param name="ev">Ev.</param>
  225. void OnSlamEvent (SlamEvent ev);
  226. };
  227. public enum slamThermalLevel
  228. {
  229. kSafe,
  230. kLevel1,
  231. kLevel2,
  232. kLevel3,
  233. kCritical,
  234. kNumThermalLevels
  235. };
  236. public enum slamThermalZone
  237. {
  238. kCpu,
  239. kGpu,
  240. kSkin,
  241. kNumThermalZones
  242. };
  243. public struct slamEventData_Thermal
  244. {
  245. public slamThermalZone zone; //!< Thermal zone
  246. public slamThermalLevel level; //!< Indication of the current zone thermal level
  247. };
  248. [StructLayout(LayoutKind.Explicit)]
  249. public struct slamEventData
  250. {
  251. [FieldOffset(0)]
  252. public slamEventData_Thermal thermal;
  253. //[FieldOffset(0)]
  254. //public slamEventData_New newData;
  255. }
  256. public struct SlamEvent
  257. {
  258. public slamEventType eventType; //!< Type of event
  259. public uint deviceId; //!< An identifier for the device that generated the event (0 == HMD)
  260. public float eventTimeStamp; //!< Time stamp for the event in seconds since the last BeginVr call
  261. public slamEventData eventData; //!< Event specific data payload
  262. };
  263. // david start
  264. public struct SCSingleLayerData
  265. {
  266. public UInt32 layerId;
  267. public UInt32 parentLayerId;
  268. public UInt32 layerTextureId;
  269. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
  270. public float[] modelMatrixData;
  271. public UInt32 editFlag;
  272. public int z;
  273. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 12)]
  274. public float[] vertexPosition;
  275. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 8)]
  276. public float[] vertexUV;
  277. public float alpha;
  278. public byte bOpaque;
  279. public UInt32 taskId;
  280. };
  281. public struct SCAllLayers
  282. {
  283. public UInt32 layerNum;
  284. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
  285. public float[] viewMatrixData;
  286. public IntPtr layerData;
  287. };
  288. // david end
  289. private List<SlamEventListener> eventListeners = new List<SlamEventListener>();
  290. public bool Initialized
  291. {
  292. get { return status.initialized; }
  293. }
  294. public bool IsRunning
  295. {
  296. get { return status.running; }
  297. }
  298. public bool DisableInput
  299. {
  300. get { return disableInput; }
  301. set { disableInput = value; }
  302. }
  303. void Awake() {
  304. if (Instance) {
  305. DestroyImmediate(gameObject);
  306. return;
  307. }
  308. Instance = this;
  309. if (!ValidateReferencedComponents ())
  310. {
  311. enabled = false;
  312. return;
  313. }
  314. RegisterListeners();
  315. Input.backButtonLeavesApp = true;
  316. Screen.sleepTimeout = SleepTimeout.NeverSleep;
  317. Application.targetFrameRate = -1;
  318. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "IsCreateDepthRT")) {
  319. IsCreateDepthRT = API_Module_SDKConfiguration.GetBool("Module_Slam", "IsCreateDepthRT", 0);
  320. DebugMy.Log("IsCreateDepthRT:" + IsCreateDepthRT, this, true);
  321. }
  322. }
  323. void OnGUI() {
  324. }
  325. bool ValidateReferencedComponents()
  326. {
  327. plugin = GSXRPlugin.Instance;
  328. if(plugin == null)
  329. {
  330. Debug.LogError("slam Plugin failed to load. Disabling...");
  331. return false;
  332. }
  333. if(head == null)
  334. {
  335. Debug.LogError("Required head gameobject not found! Disabling...");
  336. return false;
  337. }
  338. if(monoCamera == null && (leftCamera == null || rightCamera == null))
  339. {
  340. Debug.LogError("Required eye components are missing! Disabling...");
  341. return false;
  342. }
  343. return true;
  344. }
  345. #if UNITY_2018
  346. void OnEnable()
  347. {
  348. if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset)
  349. {
  350. UnityEngine.Experimental.Rendering.RenderPipeline.beginCameraRendering += OnPreRenderEvent;
  351. }
  352. }
  353. void OnDisable()
  354. {
  355. if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset)
  356. {
  357. UnityEngine.Experimental.Rendering.RenderPipeline.beginCameraRendering -= OnPreRenderEvent;
  358. }
  359. }
  360. private void OnPreRenderEvent(Camera camera)
  361. {
  362. camera.SendMessage("OnPreRenderEvent", SendMessageOptions.DontRequireReceiver);
  363. }
  364. #endif
  365. IEnumerator Start ()
  366. {
  367. yield return StartCoroutine(Initialize());
  368. status.initialized = plugin.IsInitialized();
  369. SetOverlayFade(eFadeState.FadeIn);
  370. yield return StartCoroutine(plugin.BeginVr((int)settings.cpuPerfLevel, (int)settings.gpuPerfLevel));
  371. /// for some platform plugin.BeginVr return so fast,so need check plugin.IsRunning() and Wait
  372. int waitFrameCount = 200;
  373. while ( !plugin.IsRunning() && waitFrameCount >=0) {
  374. yield return null;
  375. waitFrameCount--;
  376. }
  377. ///
  378. if (!plugin.IsRunning())
  379. {
  380. Debug.LogError("Slam failed!");
  381. Application.Quit();
  382. yield return null; // Wait one frame
  383. }
  384. float recenterTimeout = 1f;
  385. while (!plugin.RecenterTracking() && recenterTimeout > 0f)
  386. {
  387. yield return null; // Wait one frame
  388. recenterTimeout -= Time.deltaTime;
  389. }
  390. yield return new WaitForSecondsRealtime(sensorWarmupDuration);
  391. submitFrame = StartCoroutine(SubmitFrame());
  392. status.running = true;
  393. SlamInitializedCallBack?.Invoke(); //Slam initialization complete callback
  394. plugin.GSXR_Set_GlassDisconnectedCallBack(GlassDisconnetedCallBack); //Register glasses disconnection callback
  395. Debug.Log("Slam initialized!");
  396. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "IsUseCommonEvent")) {
  397. IsUseCommonEvent = API_Module_SDKConfiguration.GetBool("Module_Slam", "IsUseCommonEvent", 1);
  398. DebugMy.Log("IsUseCommonEvent:" + IsUseCommonEvent, this, true);
  399. }
  400. if (IsUseCommonEvent) {
  401. gameObject.AddComponent<Module_CommonEvent>();
  402. }
  403. DebugMy.Log("SDK SpecificationType:" + API_GSXR_Slam.SlamManager.SpecificationType + ":" + plugin.GSXR_Get_Version(), this, true);
  404. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "IsUseOpticsCalibration")) {
  405. IsUseOpticsCalibration = API_Module_SDKConfiguration.GetBool("Module_Slam", "IsUseOpticsCalibration", 1);
  406. DebugMy.Log("IsUseOpticsCalibration:" + IsUseOpticsCalibration, this, true);
  407. }
  408. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "trackPositionScale")) {
  409. settings.trackPositionScale = API_Module_SDKConfiguration.GetFloat("Module_Slam", "trackPositionScale", 1);
  410. DebugMy.Log("settings.trackPositionScale:" + settings.trackPositionScale, this, true);
  411. }
  412. Vector3 localLeftShoulder=Vector3.zero;
  413. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "LeftShoulderX") && API_Module_SDKConfiguration.HasKey("Module_Slam", "LeftShoulderY") && API_Module_SDKConfiguration.HasKey("Module_Slam", "LeftShoulderZ")) {
  414. localLeftShoulder = new Vector3(API_Module_SDKConfiguration.GetFloat("Module_Slam", "LeftShoulderX", 0.0f), API_Module_SDKConfiguration.GetFloat("Module_Slam", "LeftShoulderY", 0.0f), API_Module_SDKConfiguration.GetFloat("Module_Slam", "LeftShoulderZ", 0.0f));
  415. }
  416. if (API_Module_SDKConfiguration.HasKey("Module_SDKSystem", "IsDontDestroyOnLoad"))
  417. {
  418. IsDontDestroyOnLoad = API_Module_SDKConfiguration.GetBool("Module_SDKSystem", "IsDontDestroyOnLoad", 1);
  419. }
  420. shoulder = new Shoulder(head, localLeftShoulder == Vector3.zero ? new Vector3(-0.15f,-0.08f,-0.1f): localLeftShoulder);
  421. }
  422. [MonoPInvokeCallback(typeof(Action))]
  423. private static void GlassDisconnetedCallBack() {
  424. Debug.Log("GlassDisconnetedCallBack");
  425. Application.Quit();
  426. }
  427. IEnumerator Initialize()
  428. {
  429. // Plugin must be initialized OnStart in order to properly
  430. // get a valid surface
  431. // GameObject mainCameraGo = GameObject.FindWithTag("MainCamera");
  432. // if (mainCameraGo)
  433. // {
  434. // mainCameraGo.SetActive(false);
  435. //
  436. // Debug.Log("Camera with MainCamera tag found.");
  437. // if (!disableInput)
  438. // {
  439. // Debug.Log("Will use translation and orientation from the MainCamera.");
  440. // transform.position = mainCameraGo.transform.position;
  441. // transform.rotation = mainCameraGo.transform.rotation;
  442. // }
  443. //
  444. // Debug.Log("Disabling Camera with MainCamera tag");
  445. // }
  446. GL.Clear(false, true, Color.black);
  447. yield return StartCoroutine(plugin.Initialize());
  448. InitializeCameras();
  449. InitializeEyes();
  450. InitializeOverlays();
  451. int trackingMode = (int)GSXRPlugin.TrackingMode.kTrackingOrientation;
  452. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "IsSlamUse3Dof")) {
  453. if (API_Module_SDKConfiguration.GetBool("Module_Slam", "IsSlamUse3Dof", 0)) {
  454. DebugMy.Log("Slam Use3Dof", this, true);
  455. settings.trackPosition = false;
  456. }
  457. }
  458. if (settings.trackPosition)
  459. trackingMode |= (int)GSXRPlugin.TrackingMode.kTrackingPosition;
  460. if (settings.trackEyes)
  461. trackingMode |= (int)GSXRPlugin.TrackingMode.kTrackingEye;
  462. plugin.SetTrackingMode(trackingMode);
  463. plugin.SetVSyncCount((int)settings.vSyncCount);
  464. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  465. }
  466. Matrix4x4 invertZ = new Matrix4x4(
  467. new Vector4(1, 0, 0, 0),
  468. new Vector4(0, 1, 0, 0),
  469. new Vector4(0, 0, -1, 0),
  470. new Vector4(0, 0, 0, 1));
  471. private void InitializeCameras()
  472. {
  473. float stereoConvergence = plugin.deviceInfo.targetFrustumConvergence; //settings.stereoConvergence
  474. float horizonElevation = plugin.deviceInfo.targetFrustumPitch; //settings.horizonElevation
  475. float convergenceAngle = 0f;
  476. if (stereoConvergence > Mathf.Epsilon) convergenceAngle = Mathf.Rad2Deg * Mathf.Atan2(0.5f * settings.interPupilDistance, stereoConvergence);
  477. else if (stereoConvergence < -Mathf.Epsilon) convergenceAngle = -Mathf.Rad2Deg * Mathf.Atan2(0.5f * settings.interPupilDistance, -stereoConvergence);
  478. // left
  479. Vector3 eyePos;
  480. eyePos.x = -0.5f * settings.interPupilDistance;
  481. eyePos.y = (!settings.trackPosition ? settings.headHeight : 0);
  482. eyePos.z = (!settings.trackPosition ? settings.headDepth : 0);
  483. eyePos += head.transform.localPosition;
  484. Quaternion eyeRot;
  485. eyeRot = Quaternion.Euler(horizonElevation, convergenceAngle, 0);
  486. if (leftCamera != null)
  487. {
  488. leftCamera.transform.localPosition = eyePos;
  489. leftCamera.transform.localRotation = eyeRot;
  490. }
  491. if (leftOverlay != null)
  492. {
  493. leftOverlay.transform.localPosition = eyePos;
  494. leftOverlay.transform.localRotation = eyeRot;
  495. }
  496. // right
  497. eyePos.x *= -1;
  498. eyeRot = Quaternion.Euler(horizonElevation, -convergenceAngle, 0);
  499. if (rightCamera != null)
  500. {
  501. rightCamera.transform.localPosition = eyePos;
  502. rightCamera.transform.localRotation = eyeRot;
  503. }
  504. if (rightOverlay != null)
  505. {
  506. rightOverlay.transform.localPosition = eyePos;
  507. rightOverlay.transform.localRotation = eyeRot;
  508. }
  509. // mono
  510. eyePos.x = 0.0f;
  511. eyeRot = Quaternion.Euler(horizonElevation, 0, 0);
  512. if (monoCamera != null)
  513. {
  514. monoCamera.transform.localPosition = eyePos;
  515. monoCamera.transform.localRotation = eyeRot;
  516. }
  517. if (monoOverlay != null)
  518. {
  519. monoOverlay.transform.localPosition = eyePos;
  520. monoOverlay.transform.localRotation = eyeRot;
  521. }
  522. }
  523. private void AddEyes(Camera cam, GSXREye.eSide side)
  524. {
  525. bool enableCamera = false;
  526. var eyesFound = cam.gameObject.GetComponents<GSXREye>();
  527. for (int i = 0; i < eyesFound.Length; i++)
  528. {
  529. eyesFound[i].Side = side;
  530. if (eyesFound[i].imageType == GSXREye.eType.RenderTexture) enableCamera = true;
  531. }
  532. eyes.AddRange(eyesFound);
  533. if (eyesFound.Length == 0)
  534. {
  535. var eye = cam.gameObject.AddComponent<GSXREye>();
  536. eye.Side = side;
  537. eyes.Add(eye);
  538. enableCamera = true;
  539. }
  540. #if UNITY_5_4 || UNITY_5_5
  541. cam.hdr = false;
  542. #else // UNITY_5_6 plus
  543. cam.allowHDR = false;
  544. cam.allowMSAA = false;
  545. #endif
  546. //cam.enabled = enableCamera;
  547. }
  548. private void InitializeEyes()
  549. {
  550. eyes.Clear();
  551. if (monoCamera != null && monoCamera.gameObject.activeSelf)
  552. {
  553. AddEyes(monoCamera, GSXREye.eSide.Both);
  554. }
  555. if (leftCamera != null && leftCamera.gameObject.activeSelf)
  556. {
  557. AddEyes(leftCamera, GSXREye.eSide.Left);
  558. }
  559. if (rightCamera != null && rightCamera.gameObject.activeSelf)
  560. {
  561. AddEyes(rightCamera, GSXREye.eSide.Right);
  562. }
  563. for (int i = 0; i < GSXREye.Instances.Count; i++)
  564. {
  565. var eye = GSXREye.Instances[i];
  566. if (!eyes.Contains(eye))
  567. {
  568. eyes.Add(eye); // Add eyes found outside of slam camera hierarchy
  569. }
  570. }
  571. GSXRPlugin.DeviceInfo info = plugin.deviceInfo;
  572. foreach(GSXREye eye in eyes)
  573. {
  574. if (eye == null) continue;
  575. eye.FovMargin = settings.eyeFovMargin;
  576. eye.Format = RenderTextureFormat.Default;
  577. eye.Resolution = new Vector2(info.targetEyeWidthPixels, info.targetEyeHeightPixels);
  578. eye.ResolutionScaleFactor = settings.eyeResolutionScaleFactor;
  579. eye.Depth = (int)settings.eyeDepth;
  580. eye.AntiAliasing = (int)settings.eyeAntiAliasing; // hdr not supported with antialiasing
  581. eye.FrustumType = (int)settings.frustumType;
  582. eye.OnPreRenderListener = OnPreRenderListener;
  583. eye.OnPostRenderListener = OnPostRenderListener;
  584. eye.Initialize();
  585. }
  586. }
  587. private void AddOverlays(Camera cam, GSXROverlay.eSide side)
  588. {
  589. bool enableCamera = false;
  590. var overlaysFound = cam.gameObject.GetComponents<GSXROverlay>();
  591. for (int i = 0; i < overlaysFound.Length; i++)
  592. {
  593. overlaysFound[i].Side = side;
  594. if (overlaysFound[i].imageType == GSXROverlay.eType.RenderTexture) enableCamera = true;
  595. }
  596. overlays.AddRange(overlaysFound);
  597. if (overlaysFound.Length == 0)
  598. {
  599. var overlay = cam.gameObject.AddComponent<GSXROverlay>();
  600. overlay.Side = side;
  601. overlays.Add(overlay);
  602. enableCamera = true;
  603. }
  604. #if UNITY_5_4 || UNITY_5_5
  605. cam.hdr = false;
  606. #else // UNITY_5_6 plus
  607. cam.allowHDR = false;
  608. cam.allowMSAA = false;
  609. #endif
  610. cam.enabled = enableCamera;
  611. }
  612. private void InitializeOverlays()
  613. {
  614. overlays.Clear();
  615. if (leftOverlay != null && leftOverlay.gameObject.activeSelf)
  616. {
  617. AddOverlays(leftOverlay, GSXROverlay.eSide.Left);
  618. }
  619. if (rightOverlay != null && rightOverlay.gameObject.activeSelf)
  620. {
  621. AddOverlays(rightOverlay, GSXROverlay.eSide.Right);
  622. }
  623. if (monoOverlay != null && monoOverlay.gameObject.activeSelf)
  624. {
  625. AddOverlays(monoOverlay, GSXROverlay.eSide.Both);
  626. }
  627. for (int i = 0; i < GSXROverlay.Instances.Count; i++)
  628. {
  629. var overlay = GSXROverlay.Instances[i];
  630. if (!overlays.Contains(overlay))
  631. {
  632. overlays.Add(overlay); // Add overlays found outside of slam camera hierarchy
  633. }
  634. }
  635. GSXRPlugin.DeviceInfo info = plugin.deviceInfo;
  636. foreach (GSXROverlay overlay in overlays)
  637. {
  638. if (overlay == null) continue;
  639. overlay.Format = RenderTextureFormat.Default;
  640. overlay.Resolution = new Vector2(info.targetEyeWidthPixels, info.targetEyeHeightPixels);
  641. overlay.ResolutionScaleFactor = settings.overlayResolutionScaleFactor;
  642. overlay.Depth = (int)settings.overlayDepth;
  643. overlay.AntiAliasing = (int)settings.overlayAntiAliasing; // hdr not supported with antialiasing
  644. overlay.FrustumType = (int)settings.frustumType;
  645. overlay.OnPreRenderListener = OnPreRenderListener;
  646. overlay.OnPostRenderListener = OnPostRenderListener;
  647. overlay.Initialize();
  648. }
  649. }
  650. public void SetOverlayFade(eFadeState fadeValue)
  651. {
  652. fadeState = fadeValue;
  653. var startAlpha = fadeState == eFadeState.FadeIn ? 1f : 0f;
  654. UpdateOverlayFade(startAlpha);
  655. }
  656. public bool IsOverlayFading()
  657. {
  658. return !Mathf.Approximately((float)fadeState, fadeAlpha);
  659. }
  660. private float fadeAlpha = 0f;
  661. private void UpdateOverlayFade(float targetAlpha, float rate = 0)
  662. {
  663. if (fadeOverlay == null) return;
  664. fadeAlpha = rate > 0 ? Mathf.MoveTowards(fadeAlpha, targetAlpha, rate) : targetAlpha;
  665. var fadeTexture = fadeOverlay.imageTexture as Texture2D;
  666. if (fadeTexture != null)
  667. {
  668. var fadeColors = fadeTexture.GetPixels();
  669. for (int i = 0; i < fadeColors.Length; ++i)
  670. {
  671. fadeColors[i].a = fadeAlpha;
  672. }
  673. fadeTexture.SetPixels(fadeColors);
  674. fadeTexture.Apply(false);
  675. }
  676. var isActive = fadeAlpha > 0.0f;
  677. if (fadeOverlay.enabled != isActive)
  678. {
  679. fadeOverlay.enabled = isActive;
  680. }
  681. }
  682. IEnumerator SubmitFrame ()
  683. {
  684. Vector3 frustumSize = Vector3.zero;
  685. frustumSize.x = 0.5f * (plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left);
  686. frustumSize.y = 0.5f * (plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom);
  687. frustumSize.z = plugin.deviceInfo.targetFrustumLeft.near;
  688. //Debug.LogFormat("SubmitFrame: Frustum Size ({0:F2}, {1:F2}, {2:F2})", frustumSize.x, frustumSize.y, frustumSize.z);
  689. while (true)
  690. {
  691. yield return waitForEndOfFrame;//固定帧测试
  692. if ((plugin.GetTrackingMode() & (int)GSXRPlugin.TrackingMode.kTrackingEye) != 0) // Request eye pose
  693. {
  694. status.pose |= plugin.GSXR_Get_EyePose(ref eyePose);
  695. }
  696. var eyePoint = Vector3.zero;
  697. if ((status.pose & (int)GSXRPlugin.TrackingMode.kTrackingEye) != 0) // Valid eye pose
  698. {
  699. //Debug.LogFormat("Left Eye Position: {0}, Direction: {1}", eyePose.leftPosition.ToString(), eyePose.leftDirection.ToString());
  700. //Debug.LogFormat("Right Eye Position: {0}, Direction: {1}", eyePose.rightPosition.ToString(), eyePose.rightDirection.ToString());
  701. //Debug.LogFormat("Combined Eye Position: {0}, Direction: {1}", eyePose.combinedPosition.ToString(), eyePose.combinedDirection.ToString());
  702. var combinedDirection = Vector3.zero;
  703. if ((eyePose.leftStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.leftDirection;
  704. if ((eyePose.rightStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.rightDirection;
  705. //if ((eyePose.combinedStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.combinedDirection;
  706. if (combinedDirection.sqrMagnitude > 0f)
  707. {
  708. combinedDirection.Normalize();
  709. //Debug.LogFormat("Eye Direction: ({0:F2}, {1:F2}, {2:F2})", combinedDirection.x, combinedDirection.y, combinedDirection.z);
  710. float denominator = Vector3.Dot(combinedDirection, Vector3.forward);
  711. if (denominator > float.Epsilon)
  712. {
  713. // eye direction intersection with frustum near plane (left)
  714. eyePoint = combinedDirection * frustumSize.z / denominator;
  715. eyePoint.x /= frustumSize.x; // [-1..1]
  716. eyePoint.y /= frustumSize.y; // [-1..1]
  717. //Debug.LogFormat("Eye Point: ({0:F2}, {1:F2})", eyePoint.x, eyePoint.y);
  718. }
  719. }
  720. }
  721. var currentGain = GSXROverrideSettings.FoveateGain == Vector2.zero ?
  722. settings.foveationGain : GSXROverrideSettings.FoveateGain;
  723. var currentArea = GSXROverrideSettings.FoveateArea == 0f ?
  724. settings.foveationArea : GSXROverrideSettings.FoveateArea;
  725. var currentMinimum = GSXROverrideSettings.FoveateMinimum == 0f ?
  726. settings.foveationMinimum : GSXROverrideSettings.FoveateMinimum;
  727. for (int i = 0; i < eyes.Count; i++)
  728. {
  729. var eye = eyes[i];
  730. if (eye.TextureId > 0 && eye.ImageType == GSXREye.eType.RenderTexture)
  731. {
  732. plugin.SetFoveationParameters(eye.TextureId, eye.PreviousId, eyePoint.x, eyePoint.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  733. plugin.ApplyFoveation();
  734. }
  735. }
  736. var horizontalFieldOfView = 0f;
  737. if (settings.eyeFovMargin > 0f)
  738. {
  739. horizontalFieldOfView = (monoCamera.enabled ? monoCamera.fieldOfView / monoCamera.aspect : leftCamera.fieldOfView / leftCamera.aspect) * Mathf.Deg2Rad;
  740. }
  741. plugin.SubmitFrame(frameCount, horizontalFieldOfView, (int)settings.displayType);
  742. frameCount++;
  743. }
  744. }
  745. public bool RecenterTracking()
  746. {
  747. if (!Initialized)
  748. return false;
  749. return plugin.RecenterTracking();
  750. }
  751. void OnPreRenderListener (int sideMask, int textureId, int previousId)
  752. {
  753. if (!IsRunning)
  754. return;
  755. var currentGain = GSXROverrideSettings.FoveateGain == Vector2.zero ?
  756. settings.foveationGain : GSXROverrideSettings.FoveateGain;
  757. var currentArea = GSXROverrideSettings.FoveateArea == 0f ?
  758. settings.foveationArea : GSXROverrideSettings.FoveateArea;
  759. var currentMinimum = GSXROverrideSettings.FoveateMinimum == 0f ?
  760. settings.foveationMinimum : GSXROverrideSettings.FoveateMinimum;
  761. plugin.SetFoveationParameters(textureId, previousId, FocalPoint.x, FocalPoint.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  762. plugin.BeginEye(sideMask, frameDelta);
  763. }
  764. void OnPostRenderListener (int sideMask, int layerMask)
  765. {
  766. if (!IsRunning)
  767. return;
  768. plugin.EndEye (sideMask, layerMask);
  769. }
  770. public void SetPause(bool pause)
  771. {
  772. if (!Initialized)
  773. return;
  774. if (pause)
  775. {
  776. OnPause();
  777. }
  778. else
  779. {
  780. onResume = StartCoroutine(OnResume());
  781. }
  782. }
  783. void OnPause()
  784. {
  785. //Debug.Log("GSXRManager.OnPause()");
  786. status.running = false;
  787. if (onResume != null) {
  788. StopCoroutine(onResume);
  789. onResume = null;
  790. }
  791. if (submitFrame != null) { StopCoroutine(submitFrame); submitFrame = null; }
  792. if (plugin.IsRunning()) plugin.EndVr();
  793. }
  794. IEnumerator OnResume()
  795. {
  796. //Debug.Log("GSXRManager.OnResume()");
  797. SetOverlayFade(eFadeState.FadeIn);
  798. yield return StartCoroutine(plugin.BeginVr((int)settings.cpuPerfLevel, (int)settings.gpuPerfLevel));
  799. float recenterTimeout = 1f;
  800. while (!plugin.RecenterTracking() && recenterTimeout > 0f)
  801. {
  802. yield return null; // Wait one frame
  803. recenterTimeout -= Time.deltaTime;
  804. }
  805. yield return new WaitForSecondsRealtime(sensorWarmupDuration);
  806. submitFrame = StartCoroutine (SubmitFrame ());
  807. status.running = plugin.IsRunning();
  808. onResume = null;
  809. onApplicationPauseDele?.Invoke(false);
  810. }
  811. [NonSerialized]
  812. public GSXRPlugin.HeadPose headPose;
  813. [NonSerialized]
  814. public GSXRPlugin.EyePose eyePose;
  815. [NonSerialized]
  816. public Vector3 eyeDirection = Vector3.forward;
  817. [NonSerialized]
  818. public Vector2 eyeFocus = Vector2.zero;
  819. [NonSerialized]
  820. public float eyeSmoother = 0.2f;
  821. [NonSerialized]
  822. public float[] frameDelta = new float[9];
  823. public Vector3 modifyPosition = Vector3.zero;
  824. public Quaternion modifyOrientation = Quaternion.identity;
  825. bool outBload = false;
  826. float[] outTransformArray = new float[32];
  827. Matrix4x4 leftcalib = Matrix4x4.identity;
  828. Matrix4x4 rightCalib = Matrix4x4.identity;
  829. bool isRotNan=false;
  830. bool isPosNan=false;
  831. void LateUpdate()
  832. {
  833. if (!IsRunning)
  834. {
  835. return;
  836. }
  837. int trackingMode = plugin.GetTrackingMode();
  838. var prevOrientation = headPose.orientation;
  839. status.pose = plugin.GetHeadPose(ref headPose, frameCount);
  840. if (float.IsNaN(headPose.position.x) || float.IsNaN(headPose.position.y) || float.IsNaN(headPose.position.z))
  841. {
  842. DebugMy.Log("Position is " + headPose.position + " Error!!!!!!!!!!!!!!!!!!!!!!!!!!!", this, true);
  843. if (!isPosNan)
  844. {
  845. isPosNan = true;
  846. headPose.position = Vector3.zero;
  847. API_Module_DetectorSystem_Notice.SetNotice("The device position is NAN", "Please Reboot recovery", NoticeType.Warning, 0.8f, AlignmentType.Center, FollowType.False);
  848. API_Module_DetectorSystem_Notice.Show(1.5f);
  849. }
  850. }
  851. else
  852. {
  853. if (isPosNan)
  854. {
  855. isPosNan = false;
  856. DebugMy.Log("Position is " + headPose.position + " Success", this, true);
  857. }
  858. }
  859. if (float.IsNaN(headPose.orientation.x) || float.IsNaN(headPose.orientation.y) || float.IsNaN(headPose.orientation.z) || float.IsNaN(headPose.orientation.w))
  860. {
  861. DebugMy.Log("rotation is " + headPose.orientation + " Error!!!!!!!!!!!!!!!!!!!!!!!!!!!", this, true);
  862. if (!isRotNan)
  863. {
  864. isRotNan = true;
  865. headPose.orientation = Quaternion.identity;
  866. API_Module_DetectorSystem_Notice.SetNotice("The device rotation is NAN", "Please Reboot recovery", NoticeType.Warning, 0.8f, AlignmentType.Center, FollowType.False);
  867. API_Module_DetectorSystem_Notice.Show(1.5f);
  868. }
  869. }
  870. else
  871. {
  872. if (isRotNan)
  873. {
  874. isRotNan = false;
  875. DebugMy.Log("rotation is " + headPose.orientation + "Success", this, true);
  876. }
  877. }
  878. if ((trackingMode & (int)GSXRPlugin.TrackingMode.kTrackingEye) != 0)
  879. {
  880. status.pose |= plugin.GSXR_Get_EyePose(ref eyePose, frameCount);
  881. }
  882. if (!disableInput)
  883. {
  884. if ((status.pose & (int)GSXRPlugin.TrackingMode.kTrackingOrientation) != 0)
  885. {
  886. head.transform.localRotation = headPose.orientation;
  887. // delta orientation screen space x, y offset for foveated rendering
  888. var deltaOrientation = Quaternion.Inverse(prevOrientation) * headPose.orientation;
  889. var lookDirection = deltaOrientation * Vector3.forward;
  890. //Debug.LogFormat("Look Direction: {0}", lookDirection.ToString());
  891. lookDirection *= plugin.deviceInfo.targetFrustumLeft.near / lookDirection.z;
  892. float xTotal = 0.5f * (plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left);
  893. float xAdjust = (xTotal != 0.0f) ? lookDirection.x / xTotal : 0.0f;
  894. float yTotal = 0.5f * (plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom);
  895. float yAdjust = (yTotal != 0.0f) ? lookDirection.y / yTotal : 0.0f;
  896. //xAdjust *= 0.5f * plugin.deviceInfo.targetEyeWidthPixels;
  897. //yAdjust *= 0.5f * plugin.deviceInfo.targetEyeHeightPixels;
  898. // rotation around z [cos(z), sin(z), 0], [-sin(z), cos(z), 0], [0, 0, 1]
  899. Vector3 deltaEulers = deltaOrientation.eulerAngles;
  900. float cosZ = Mathf.Cos(deltaEulers.z * Mathf.Deg2Rad);
  901. float sinZ = Mathf.Sin(deltaEulers.z * Mathf.Deg2Rad);
  902. // Output rotation and translation
  903. frameDelta[0] = cosZ;
  904. frameDelta[1] = sinZ;
  905. frameDelta[2] = 0.0f;
  906. frameDelta[3] = -sinZ;
  907. frameDelta[4] = cosZ;
  908. frameDelta[5] = 0.0f;
  909. frameDelta[6] = xAdjust;
  910. frameDelta[7] = yAdjust;
  911. frameDelta[8] = 1.0f;
  912. }
  913. if (settings.trackPosition && (status.pose & (int)GSXRPlugin.TrackingMode.kTrackingPosition) != 0)
  914. {
  915. head.transform.localPosition = headPose.position * settings.trackPositionScale;
  916. }
  917. if ((status.pose & (int)GSXRPlugin.TrackingMode.kTrackingEye) != 0)
  918. {
  919. //Debug.LogFormat("Left Eye Position: {0}, Direction: {1}", eyePose.leftPosition.ToString(), eyePose.leftDirection.ToString());
  920. //Debug.LogFormat("Right Eye Position: {0}, Direction: {1}", eyePose.rightPosition.ToString(), eyePose.rightDirection.ToString());
  921. //Debug.LogFormat("Combined Eye Position: {0}, Direction: {1}", eyePose.combinedPosition.ToString(), eyePose.combinedDirection.ToString());
  922. var combinedDirection = Vector3.zero;
  923. if ((eyePose.leftStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.leftDirection;
  924. if ((eyePose.rightStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.rightDirection;
  925. //if ((eyePose.combinedStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.combinedDirection;
  926. if (combinedDirection.sqrMagnitude > 0f)
  927. {
  928. combinedDirection.Normalize();
  929. //Debug.LogFormat("Eye Direction: ({0:F2}, {1:F2}, {2:F2})", combinedDirection.x, combinedDirection.y, combinedDirection.z);
  930. eyeDirection = eyeSmoother > 0.001f ? Vector3.Lerp(eyeDirection, combinedDirection, eyeSmoother) : combinedDirection;
  931. //var combinedPosition = Vector3.zero;
  932. //if ((eyePose.leftStatus & (int)GSXRPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.leftPosition;
  933. //if ((eyePose.rightStatus & (int)GSXRPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.rightPosition;
  934. ////if ((eyePose.combinedStatus & (int)GSXRPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.combinedPosition;
  935. gaze.localPosition = monoCamera.transform.localPosition;
  936. gaze.localRotation = Quaternion.LookRotation(eyeDirection, Vector3.up);
  937. float denominator = Vector3.Dot(eyeDirection, Vector3.forward);
  938. if (denominator > float.Epsilon)
  939. {
  940. // eye direction intersection with frustum near plane (left)
  941. var eyePoint = eyeDirection * plugin.deviceInfo.targetFrustumLeft.near / denominator;
  942. // size of the frustum near plane (left)
  943. var nearSize = new Vector2(0.5f*(plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left),
  944. 0.5f*(plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom));
  945. eyeFocus.Set(eyePoint.x / nearSize.x, eyePoint.y / nearSize.y); // Normalized [-1,1]
  946. //Debug.LogFormat("Eye Focus: {0}", eyeFocus.ToString());
  947. FocalPoint = eyeFocus; // Cache for foveated rendering
  948. }
  949. }
  950. }
  951. }
  952. //var isValid = true;
  953. //if (settings.poseStatusFade)
  954. //{
  955. // isValid = !settings.trackPosition
  956. // || ((trackingMode & (int)GSXRPlugin.TrackingMode.kTrackingPosition) == 0)
  957. // || (status.pose & (int)GSXRPlugin.TrackingMode.kTrackingPosition) != 0;
  958. //}
  959. //var targetAlpha = fadeState == eFadeState.FadeOut || !isValid ? 1f : 0f;
  960. var targetAlpha = fadeState == eFadeState.FadeOut ? 1f : 0f;
  961. UpdateOverlayFade(targetAlpha, Time.deltaTime / fadeDuration);
  962. if (plugin.GSXR_Is_SupportOpticsCalibration()) {
  963. if (leftcalib == Matrix4x4.identity || rightCalib == Matrix4x4.identity) {
  964. plugin.GSXR_Get_TransformMatrix(ref outBload, outTransformArray);
  965. if (outBload) {
  966. leftcalib.SetColumn(0, new Vector4(outTransformArray[0], outTransformArray[1], outTransformArray[2], outTransformArray[3]));
  967. leftcalib.SetColumn(1, new Vector4(outTransformArray[4], outTransformArray[5], outTransformArray[6], outTransformArray[7]));
  968. leftcalib.SetColumn(2, new Vector4(outTransformArray[8], outTransformArray[9], outTransformArray[10], outTransformArray[11]));
  969. leftcalib.SetColumn(3, new Vector4(outTransformArray[12], outTransformArray[13], outTransformArray[14], outTransformArray[15]));
  970. rightCalib.SetColumn(0, new Vector4(outTransformArray[16], outTransformArray[17], outTransformArray[18], outTransformArray[19]));
  971. rightCalib.SetColumn(1, new Vector4(outTransformArray[20], outTransformArray[21], outTransformArray[22], outTransformArray[23]));
  972. rightCalib.SetColumn(2, new Vector4(outTransformArray[24], outTransformArray[25], outTransformArray[26], outTransformArray[27]));
  973. rightCalib.SetColumn(3, new Vector4(outTransformArray[28], outTransformArray[29], outTransformArray[30], outTransformArray[31]));
  974. Debug.Log($"leftcalib [{leftcalib.m00}, {leftcalib.m01}, {leftcalib.m02}, {leftcalib.m03};" +
  975. $"{leftcalib.m10}, {leftcalib.m11}, {leftcalib.m12}, {leftcalib.m13};" +
  976. $"{leftcalib.m20}, {leftcalib.m21}, {leftcalib.m22}, {leftcalib.m23};" +
  977. $"{leftcalib.m30}, {leftcalib.m31}, {leftcalib.m32}, {leftcalib.m33}]");
  978. Debug.Log($"rightCalib [{rightCalib.m00}, {rightCalib.m01}, {rightCalib.m02}, {rightCalib.m03};" +
  979. $"{rightCalib.m10}, {rightCalib.m11}, {rightCalib.m12}, {rightCalib.m13};" +
  980. $"{rightCalib.m20}, {rightCalib.m21}, {rightCalib.m22}, {rightCalib.m23};" +
  981. $"{rightCalib.m30}, {rightCalib.m31}, {rightCalib.m32}, {rightCalib.m33}]");
  982. }
  983. }
  984. //if (outBload) {
  985. // Matrix4x4 xx = leftcalib * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(leftCamera.transform.position, leftCamera.transform.rotation, leftCamera.transform.lossyScale));
  986. // Matrix4x4 yy = rightCalib * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(rightCamera.transform.position, rightCamera.transform.rotation, rightCamera.transform.lossyScale));
  987. // Debug.Log("SlamManager: OpticsCalibration leftCamera.worldToCameraMatrix:" + xx);
  988. // Debug.Log("SlamManager: OpticsCalibration rightCamera.worldToCameraMatrix:" + yy);
  989. //}
  990. if (head.position != head.localPosition || head.rotation != head.localRotation) {
  991. ///for If Head parent not at origin,must mul the delta Matirx for Camera ViewMatrix
  992. //MD*Ml*P = Mw*P ==> MD == Mw * (M1 -1 ni)
  993. headDeltaInitLocalToWorld = Matrix4x4.TRS(head.position, head.rotation, Vector3.one) * Matrix4x4.Inverse(Matrix4x4.TRS(head.localPosition, head.localRotation, Vector3.one));
  994. }
  995. leftCamera.worldToCameraMatrix = plugin.leftViewMatrix * invertZ;
  996. leftCamera.worldToCameraMatrix = Matrix4x4.Inverse(headDeltaInitLocalToWorld * leftCamera.cameraToWorldMatrix/* not worldToCameraMatrix*/);
  997. rightCamera.worldToCameraMatrix = plugin.rightViewMatrix * invertZ;
  998. rightCamera.worldToCameraMatrix = Matrix4x4.Inverse(headDeltaInitLocalToWorld * rightCamera.cameraToWorldMatrix/* not worldToCameraMatrix*/);
  999. //Debug.Log("SlamManager: leftCamera.worldToCameraMatrix:" + leftCamera.worldToCameraMatrix);
  1000. //Debug.Log("SlamManager: rightCamera.worldToCameraMatrix:" + rightCamera.worldToCameraMatrix);
  1001. }
  1002. }
  1003. public void Shutdown()
  1004. {
  1005. Debug.Log("GSXRManager.Shutdown()");
  1006. status.running = false;
  1007. if (submitFrame != null) { StopCoroutine(submitFrame); submitFrame = null; }
  1008. if (plugin.IsRunning()) plugin.EndVr();
  1009. if (IsDontDestroyOnLoad)
  1010. {
  1011. if (plugin.IsInitialized()) plugin.Shutdown();
  1012. }
  1013. status.initialized = false;
  1014. }
  1015. void OnDestroy() {
  1016. if (Instance != this)
  1017. return;
  1018. UnregisterListeners();
  1019. // plugin.GSXR_Set_ControllerBondEventCallback(null); //UnRegister Controller binding callback
  1020. Shutdown();
  1021. }
  1022. public delegate void OnApplicationPauseDele(bool pause);
  1023. public static event OnApplicationPauseDele onApplicationPauseDele;
  1024. void OnApplicationPause(bool pause)
  1025. {
  1026. return;
  1027. Debug.LogFormat("GSXRManager.OnApplicationPause({0})",pause);
  1028. if (pause)
  1029. {
  1030. onApplicationPauseDele?.Invoke(true);
  1031. }
  1032. SetPause(pause);
  1033. }
  1034. void OnApplicationQuit()
  1035. {
  1036. Debug.Log("GSXRManager.OnApplicationQuit()");
  1037. if (!IsDontDestroyOnLoad)
  1038. {
  1039. Shutdown();
  1040. if (plugin.IsInitialized()) plugin.Shutdown();
  1041. }
  1042. }
  1043. static public Matrix4x4 Perspective(float left, float right, float bottom, float top, float near, float far)
  1044. {
  1045. float x = 2.0F * near / (right - left);
  1046. float y = 2.0F * near / (top - bottom);
  1047. float a = (right + left) / (right - left);
  1048. float b = (top + bottom) / (top - bottom);
  1049. float c = -(far + near) / (far - near);
  1050. float d = -(2.0F * far * near) / (far - near);
  1051. float e = -1.0F;
  1052. Matrix4x4 m = new Matrix4x4();
  1053. m[0, 0] = x;
  1054. m[0, 1] = 0;
  1055. m[0, 2] = a;
  1056. m[0, 3] = 0;
  1057. m[1, 0] = 0;
  1058. m[1, 1] = y;
  1059. m[1, 2] = b;
  1060. m[1, 3] = 0;
  1061. m[2, 0] = 0;
  1062. m[2, 1] = 0;
  1063. m[2, 2] = c;
  1064. m[2, 3] = d;
  1065. m[3, 0] = 0;
  1066. m[3, 1] = 0;
  1067. m[3, 2] = e;
  1068. m[3, 3] = 0;
  1069. return m;
  1070. }
  1071. void RegisterListeners()
  1072. {
  1073. GSXROverrideSettings.OnEyeAntiAliasingChangedEvent += OnEyeAntiAliasingChanged;
  1074. GSXROverrideSettings.OnEyeDepthChangedEvent += OnEyeDepthChanged;
  1075. GSXROverrideSettings.OnEyeResolutionScaleFactorChangedEvent += OnEyeResolutionScaleFactorChanged;
  1076. GSXROverrideSettings.OnOverlayAntiAliasingChangedEvent += OnOverlayAntiAliasingChanged;
  1077. GSXROverrideSettings.OnOverlayDepthChangedEvent += OnOverlayDepthChanged;
  1078. GSXROverrideSettings.OnOverlayResolutionScaleFactorChangedEvent += OnOverlayResolutionScaleFactorChanged;
  1079. GSXROverrideSettings.OnChromaticAberrationCorrectionChangedEvent += OnChromaticAberrationCorrectionChanged;
  1080. GSXROverrideSettings.OnVSyncCountChangedEvent += OnVSyncCountChanged;
  1081. GSXROverrideSettings.OnMasterTextureLimitChangedEvent += OnMasterTextureLimitChanged;
  1082. GSXROverrideSettings.OnPerfLevelChangedEvent += OnPerfLevelChanged;
  1083. GSXROverrideSettings.OnFoveateChangedEvent += OnFoveateChanged;
  1084. }
  1085. void UnregisterListeners()
  1086. {
  1087. GSXROverrideSettings.OnEyeAntiAliasingChangedEvent -= OnEyeAntiAliasingChanged;
  1088. GSXROverrideSettings.OnEyeDepthChangedEvent -= OnEyeDepthChanged;
  1089. GSXROverrideSettings.OnEyeResolutionScaleFactorChangedEvent -= OnEyeResolutionScaleFactorChanged;
  1090. GSXROverrideSettings.OnOverlayAntiAliasingChangedEvent -= OnOverlayAntiAliasingChanged;
  1091. GSXROverrideSettings.OnOverlayDepthChangedEvent -= OnOverlayDepthChanged;
  1092. GSXROverrideSettings.OnOverlayResolutionScaleFactorChangedEvent -= OnOverlayResolutionScaleFactorChanged;
  1093. GSXROverrideSettings.OnChromaticAberrationCorrectionChangedEvent -= OnChromaticAberrationCorrectionChanged;
  1094. GSXROverrideSettings.OnVSyncCountChangedEvent -= OnVSyncCountChanged;
  1095. GSXROverrideSettings.OnMasterTextureLimitChangedEvent -= OnMasterTextureLimitChanged;
  1096. GSXROverrideSettings.OnPerfLevelChangedEvent -= OnPerfLevelChanged;
  1097. GSXROverrideSettings.OnFoveateChangedEvent -= OnFoveateChanged;
  1098. }
  1099. void OnEyeAntiAliasingChanged(GSXROverrideSettings.eAntiAliasing antiAliasing)
  1100. {
  1101. foreach (GSXREye eye in eyes)
  1102. {
  1103. eye.AntiAliasing = antiAliasing == GSXROverrideSettings.eAntiAliasing.NoOverride ?
  1104. (int)settings.eyeAntiAliasing : (int)antiAliasing;
  1105. }
  1106. }
  1107. void OnEyeDepthChanged(GSXROverrideSettings.eDepth depth)
  1108. {
  1109. foreach (GSXREye eye in eyes)
  1110. {
  1111. eye.Depth = depth == GSXROverrideSettings.eDepth.NoOverride ?
  1112. (int)settings.eyeDepth : (int)depth;
  1113. }
  1114. }
  1115. void OnEyeResolutionScaleFactorChanged(float scaleFactor)
  1116. {
  1117. foreach (GSXREye eye in eyes)
  1118. {
  1119. eye.ResolutionScaleFactor = scaleFactor <= 0 ? settings.eyeResolutionScaleFactor : scaleFactor;
  1120. }
  1121. }
  1122. void OnOverlayAntiAliasingChanged(GSXROverrideSettings.eAntiAliasing antiAliasing)
  1123. {
  1124. foreach (GSXROverlay overlay in overlays)
  1125. {
  1126. overlay.AntiAliasing = antiAliasing == GSXROverrideSettings.eAntiAliasing.NoOverride ?
  1127. (int)settings.overlayAntiAliasing : (int)antiAliasing;
  1128. }
  1129. }
  1130. void OnOverlayDepthChanged(GSXROverrideSettings.eDepth depth)
  1131. {
  1132. foreach (GSXROverlay overlay in overlays)
  1133. {
  1134. overlay.Depth = depth == GSXROverrideSettings.eDepth.NoOverride ?
  1135. (int)settings.overlayDepth : (int)depth;
  1136. }
  1137. }
  1138. void OnOverlayResolutionScaleFactorChanged(float scaleFactor)
  1139. {
  1140. foreach (GSXROverlay overlay in overlays)
  1141. {
  1142. overlay.ResolutionScaleFactor = scaleFactor <= 0 ? settings.overlayResolutionScaleFactor : scaleFactor;
  1143. }
  1144. }
  1145. void OnChromaticAberrationCorrectionChanged(GSXROverrideSettings.eChromaticAberrationCorrection aberrationCorrection)
  1146. {
  1147. if(aberrationCorrection == GSXROverrideSettings.eChromaticAberrationCorrection.kDisable)
  1148. {
  1149. plugin.SetFrameOption(GSXRPlugin.FrameOption.kDisableChromaticCorrection);
  1150. }
  1151. else
  1152. {
  1153. plugin.UnsetFrameOption(GSXRPlugin.FrameOption.kDisableChromaticCorrection);
  1154. }
  1155. }
  1156. void OnVSyncCountChanged(GSXROverrideSettings.eVSyncCount vSyncCount)
  1157. {
  1158. if (vSyncCount == GSXROverrideSettings.eVSyncCount.NoOverride)
  1159. {
  1160. plugin.SetVSyncCount((int)settings.vSyncCount);
  1161. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  1162. }
  1163. else
  1164. {
  1165. plugin.SetVSyncCount((int)vSyncCount);
  1166. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  1167. }
  1168. }
  1169. void OnMasterTextureLimitChanged(GSXROverrideSettings.eMasterTextureLimit masterTextureLimit)
  1170. {
  1171. QualitySettings.globalTextureMipmapLimit = masterTextureLimit == GSXROverrideSettings.eMasterTextureLimit.NoOverride ?
  1172. (int)settings.masterTextureLimit : (int)masterTextureLimit;
  1173. }
  1174. void OnPerfLevelChanged(GSXROverrideSettings.ePerfLevel cpuPerfLevel, GSXROverrideSettings.ePerfLevel gpuPerfLevel)
  1175. {
  1176. int currentCpuPerfLevel = cpuPerfLevel == GSXROverrideSettings.ePerfLevel.NoOverride ?
  1177. (int)settings.cpuPerfLevel : (int)GSXROverrideSettings.CpuPerfLevel;
  1178. int currentGpuPerfLevel = gpuPerfLevel == GSXROverrideSettings.ePerfLevel.NoOverride ?
  1179. (int)settings.gpuPerfLevel : (int)GSXROverrideSettings.GpuPerfLevel;
  1180. plugin.SetPerformanceLevels(currentCpuPerfLevel, currentGpuPerfLevel);
  1181. }
  1182. void OnFoveateChanged(Vector2 gain, float area, float minPixelDensity)
  1183. {
  1184. var point = Vector2.zero;
  1185. var currentGain = gain == Vector2.zero ?
  1186. settings.foveationGain : GSXROverrideSettings.FoveateGain;
  1187. var currentArea = area == 0f ?
  1188. settings.foveationArea : GSXROverrideSettings.FoveateArea;
  1189. var currentMinimum = minPixelDensity == 0f ?
  1190. settings.foveationMinimum : GSXROverrideSettings.FoveateMinimum;
  1191. plugin.SetFoveationParameters(0, 0, point.x, point.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  1192. }
  1193. /// <summary>
  1194. /// Update this instance.
  1195. /// </summary>
  1196. //---------------------------------------------------------------------------------------------
  1197. void Update()
  1198. {
  1199. SlamEvent frameEvent = new SlamEvent ();
  1200. while (plugin.PollEvent(ref frameEvent))
  1201. {
  1202. //Debug.LogFormat("SlamEvent: {0}", frameEvent.eventType.ToString());
  1203. for (int i = 0; i < eventListeners.Count; i++) {
  1204. eventListeners [i].OnSlamEvent (frameEvent);
  1205. }
  1206. }
  1207. }
  1208. /// <summary>
  1209. /// Adds the event listener.
  1210. /// </summary>
  1211. /// <param name="listener">Listener.</param>
  1212. //---------------------------------------------------------------------------------------------
  1213. public void AddEventListener(SlamEventListener listener)
  1214. {
  1215. if (listener != null) {
  1216. eventListeners.Insert (0, listener);
  1217. }
  1218. }
  1219. /// <summary>
  1220. /// Start Tracking
  1221. /// </summary>
  1222. /// <returns>Handle to the controller</returns>
  1223. /// <param name="desc">Desc.</param>
  1224. //---------------------------------------------------------------------------------------------
  1225. public int ControllerStartTracking(string desc)
  1226. {
  1227. return plugin.ControllerStartTracking(desc);
  1228. }
  1229. /// <summary>
  1230. /// Stop Tracking
  1231. /// </summary>
  1232. /// <param name="handle">Handle.</param>
  1233. //---------------------------------------------------------------------------------------------
  1234. public void ControllerStopTracking(int handle)
  1235. {
  1236. plugin.ControllerStopTracking(handle);
  1237. }
  1238. /// <summary>
  1239. /// Get current state
  1240. /// </summary>
  1241. /// <returns>Controller State.</returns>
  1242. /// <param name="handle">Handle.</param>
  1243. //---------------------------------------------------------------------------------------------
  1244. public GSXRControllerState ControllerGetState(int handle, int space = 0)
  1245. {
  1246. return plugin.ControllerGetState(handle, space);
  1247. }
  1248. /// <summary>
  1249. /// Send an event to the controller
  1250. /// </summary>
  1251. /// <param name="handle">Handle.</param>
  1252. /// <param name="what">What.</param>
  1253. /// <param name="arg1">Arg1.</param>
  1254. /// <param name="arg2">Arg2.</param>
  1255. //---------------------------------------------------------------------------------------------
  1256. public void ControllerSendMessage(int handle, GSXRController.slamControllerMessageType what, int arg1, int arg2)
  1257. {
  1258. plugin.ControllerSendMessage (handle, what, arg1, arg2);
  1259. }
  1260. /// <summary>
  1261. /// Controllers the query.
  1262. /// </summary>
  1263. /// <returns>The query.</returns>
  1264. /// <param name="handle">Handle.</param>
  1265. /// <param name="what">What.</param>
  1266. /// <param name="mem">Mem.</param>
  1267. /// <param name="size">Size.</param>
  1268. //---------------------------------------------------------------------------------------------
  1269. public object ControllerQuery(int handle, GSXRController.slamControllerQueryType what)
  1270. {
  1271. return plugin.ControllerQuery (handle, what);
  1272. }
  1273. Coroutine startSlameCor;
  1274. public void StartSlam() {
  1275. if (startSlameCor == null) {
  1276. Debug.Log("StartSlam Coroutine Start");
  1277. startSlameCor = StartCoroutine(startSlam());
  1278. } else {
  1279. Debug.Log("startSlame Coroutine Not Null");
  1280. }
  1281. }
  1282. IEnumerator startSlam() {
  1283. yield return new WaitUntil(() => GSXRManager.Instance != null);
  1284. yield return new WaitUntil(() => !GSXRManager.Instance.IsRunning);
  1285. GSXRManager.Instance.SetPause(false);
  1286. yield return new WaitUntil(() => IsTrackingValid);
  1287. startSlameCor = null;
  1288. }
  1289. Coroutine stopSlameCor;
  1290. //when stopSlam you must be sure no StartCorutine run before!
  1291. public void StopSlam() {
  1292. if (stopSlameCor == null && startSlameCor == null) {
  1293. Debug.Log("stopSlame Coroutine Start");
  1294. stopSlameCor = StartCoroutine(stopSlam());
  1295. } else if (stopSlameCor != null) {
  1296. Debug.Log("stopSlame Coroutine Not Null");
  1297. } else if (startSlameCor != null) {
  1298. Debug.Log("stopSlame: startSlame Coroutine Not Null");
  1299. }
  1300. }
  1301. IEnumerator stopSlam() {
  1302. yield return new WaitUntil(() => GSXRManager.Instance != null);
  1303. yield return new WaitUntil(() => GSXRManager.Instance.IsRunning);
  1304. GSXRManager.Instance.SetPause(true);
  1305. yield return new WaitUntil(() => !GSXRManager.Instance.IsRunning);
  1306. stopSlameCor = null;
  1307. }
  1308. Coroutine resetSlameCor;
  1309. public void ResetSlam() {
  1310. if (resetSlameCor == null) {
  1311. Debug.Log("resetSlameCor Coroutine Start");
  1312. resetSlameCor = StartCoroutine(resetSlam());
  1313. } else {
  1314. Debug.Log("resetSlameCor Coroutine Not Null");
  1315. }
  1316. }
  1317. IEnumerator resetSlam() {
  1318. Debug.Log("ResetSlam Coroutine Step 0: CheckFlag...");
  1319. yield return new WaitUntil(() => GSXRManager.Instance != null);
  1320. yield return new WaitUntil(() => GSXRManager.Instance.IsRunning);
  1321. Debug.Log("ResetSlam Coroutine Step 1: StopSlam");
  1322. GSXRManager.Instance.SetPause(true);
  1323. yield return new WaitUntil(() => !GSXRManager.Instance.IsRunning);
  1324. Debug.Log("ResetSlam Coroutine Step 2: StartSlam");
  1325. GSXRManager.Instance.SetPause(false);
  1326. yield return new WaitUntil(() => IsTrackingValid);
  1327. Debug.Log("ResetSlam Coroutine Finish");
  1328. resetSlameCor = null;
  1329. }
  1330. public bool IsTrackingValid {
  1331. get {
  1332. if (GSXRManager.Instance && GSXRManager.Instance.IsRunning) {
  1333. return !GSXRManager.Instance.settings.trackPosition
  1334. || ((GSXRManager.Instance.plugin.GetTrackingMode() & (int)GSXRPlugin.TrackingMode.kTrackingPosition) == 0)
  1335. || (GSXRManager.Instance.status.pose & (int)GSXRPlugin.TrackingMode.kTrackingPosition) != 0;
  1336. }
  1337. return false;
  1338. }
  1339. }
  1340. public Shoulder shoulder;
  1341. public class Shoulder {
  1342. public Transform Left { get; private set; }
  1343. public Transform Right { get; private set; }
  1344. private Transform head;
  1345. private Vector3 leftOffset;
  1346. public Shoulder(Transform head,Vector3 leftOffset) {
  1347. this.head = head;
  1348. this.leftOffset = leftOffset;
  1349. if (head) {
  1350. Left = new GameObject("LeftShoulder").transform;
  1351. Left.SetParent(head,false);
  1352. Left.localPosition = leftOffset;
  1353. Right = new GameObject("RightShoulder").transform;
  1354. Right.SetParent(head, false);
  1355. Right.localPosition = new Vector3(-leftOffset.x, leftOffset.y, leftOffset.z) ;
  1356. }
  1357. }
  1358. }
  1359. public void GSXR_Set_OnFloorOrOnHead(int type)
  1360. {
  1361. if (type != 0 && type != 1)
  1362. {
  1363. DebugMy.Log("GSXR_Set_OnFloorOrOnHead: index Must 1 or 0", this, true);
  1364. return ;
  1365. }
  1366. plugin.GSXR_Set_OnFloorOrOnHead(type);
  1367. }
  1368. Coroutine VibrateCoroutine0, VibrateCoroutine1;
  1369. public void GSXR_Set_ControllerVibrate(int index,bool isOn, VibrateOnType vibrateOnType, float time) {
  1370. if (index != 0 && index != 1) {
  1371. DebugMy.Log("GSXR_Set_ControllerVibrate: index Must 1 or 0", this, true);
  1372. return;
  1373. }
  1374. if (vibrateOnType == VibrateOnType.Null) {
  1375. //DebugMy.Log("GSXR_Set_ControllerVibrate: vibrateOnType Null", this, true);
  1376. return;
  1377. }
  1378. //DebugMy.Log("GSXR_Set_ControllerVibrate:" + index + " " + isOn + " " + vibrateOnType + " " + time, this, true);
  1379. if (index == 0 && VibrateCoroutine0 != null) {
  1380. StopCoroutine(VibrateCoroutine0);
  1381. VibrateCoroutine0 = null;
  1382. } else if (index == 1 && VibrateCoroutine1 != null) {
  1383. StopCoroutine(VibrateCoroutine1);
  1384. VibrateCoroutine1 = null;
  1385. }
  1386. if (isOn) {
  1387. if (index == 0) {
  1388. VibrateCoroutine0 = StartCoroutine(VibrateRun(index, vibrateOnType, time));
  1389. } else if (index == 1) {
  1390. VibrateCoroutine1 = StartCoroutine(VibrateRun(index, vibrateOnType, time));
  1391. }
  1392. } else {
  1393. plugin.GSXR_Set_ControllerVibrate(index, false);
  1394. }
  1395. }
  1396. public int GSXR_Set_ControllerVibrate(int index, bool isOn, float amplitude, float frequency, float time)
  1397. {
  1398. if (index != 0 && index != 1 && index != 2)
  1399. {
  1400. DebugMy.Log("GSXR_Set_ControllerVibrateStatus: index Must 2 or 1 or 0", this, true);
  1401. return -1;
  1402. }
  1403. int amplitude1 = Convert.ToInt32(Math.Ceiling(amplitude * 16));
  1404. int frequency1 = Convert.ToInt32(Math.Ceiling(frequency * 16));
  1405. int time1 = Convert.ToInt32(Math.Round(time * 10));
  1406. //Debug.Log("KMSet_ControllerVibrate: "+index+","+isOn+","+amplitude1+","+ frequency1+","+ time1);
  1407. return plugin.GSXR_Set_ControllerVibrate(index, isOn, amplitude1, frequency1, time1);
  1408. }
  1409. public bool GSXR_Get_ControllerVibrateStatus(int index)
  1410. {
  1411. if (index != 0 && index != 1)
  1412. {
  1413. DebugMy.Log("GSXR_Get_ControllerVibrateStatus: index Must 1 or 0", this, true);
  1414. return false;
  1415. }
  1416. return plugin.GSXR_Get_ControllerVibrateStatus(index);
  1417. }
  1418. public int GSXR_Get_ControllerVibrateState(int index)
  1419. {
  1420. if (index != 0 && index != 1 && index != 2)
  1421. {
  1422. DebugMy.Log("GSXR_Get_ControllerVibrateState: index Must 2 or 1 or 0", this, true);
  1423. return -1;
  1424. }
  1425. return ((plugin.GSXR_Get_ControllerVibrateState(index) >> 2) & 1);
  1426. }
  1427. public enum VibrateOnType {
  1428. Shutdown,
  1429. OneShot,
  1430. Continuous,
  1431. OneShotContinuous,
  1432. Null,
  1433. }
  1434. IEnumerator VibrateRun(int index, VibrateOnType vibrateOnType, float time) {
  1435. yield return null;
  1436. if (vibrateOnType == VibrateOnType.OneShot) {
  1437. plugin.GSXR_Set_ControllerVibrate(index, true);
  1438. yield return new WaitForSeconds(time);
  1439. plugin.GSXR_Set_ControllerVibrate(index, false);
  1440. } else if (vibrateOnType == VibrateOnType.Continuous) {
  1441. plugin.GSXR_Set_ControllerVibrate(index, true);
  1442. while (true) {
  1443. yield return null;
  1444. }
  1445. } else if (vibrateOnType == VibrateOnType.OneShotContinuous) {
  1446. while (true) {
  1447. plugin.GSXR_Set_ControllerVibrate(index, true);
  1448. yield return new WaitForSeconds(time);
  1449. plugin.GSXR_Set_ControllerVibrate(index, false);
  1450. yield return new WaitForSeconds(time / 2);
  1451. }
  1452. } else if (vibrateOnType == VibrateOnType.Shutdown) {
  1453. plugin.GSXR_Set_ControllerVibrate(index, false);
  1454. }
  1455. if (index == 0) {
  1456. VibrateCoroutine0 = null;
  1457. } else if (index == 1) {
  1458. VibrateCoroutine1 = null;
  1459. }
  1460. }
  1461. public int GSXR_Get_ControllerAccelerometer(float[] orientationArray, int index) {
  1462. if (index != 0 && index != 1)
  1463. {
  1464. DebugMy.Log("GSXR_Get_ControllerAccelerometer: index Must 1 or 0", this, true);
  1465. return -4;
  1466. }
  1467. return plugin.GSXR_Get_ControllerAccelerometer(orientationArray, index);
  1468. }
  1469. public int GSXR_Get_ControllerGyroscope(float[] orientationArray, int index) {
  1470. if (index != 0 && index != 1)
  1471. {
  1472. DebugMy.Log("GSXR_Get_ControllerGyroscope: index Must 1 or 0", this, true);
  1473. return -4;
  1474. }
  1475. return GSXR_Get_ControllerGyroscope(orientationArray, index);
  1476. }
  1477. public int GSXR_Get_ControllerAngleVelocity(float[] orientationArray, int index)
  1478. {
  1479. if (index != 0 && index != 1)
  1480. {
  1481. DebugMy.Log("GSXR_Get_ControllerAngleVelocity: index Must 1 or 0", this, true);
  1482. return -4;
  1483. }
  1484. return plugin.GSXR_Get_ControllerAngleVelocity(orientationArray, index);
  1485. }
  1486. public int GSXR_Get_ControllerLinearVelocity(float[] orientationArray, int index)
  1487. {
  1488. if (index != 0 && index != 1)
  1489. {
  1490. DebugMy.Log("GSXR_Get_ControllerLinearVelocity: index Must 1 or 0", this, true);
  1491. return -4;
  1492. }
  1493. return plugin.GSXR_Get_ControllerLinearVelocity(orientationArray, index);
  1494. }
  1495. public void GSXR_Bind_Controller(int index, int type) {
  1496. if (index != 0 && index != 1)
  1497. {
  1498. DebugMy.Log("GSXR_Bind_Controller: index Must 1 or 0", this, true);
  1499. return;
  1500. }
  1501. plugin.GSXR_Bind_Controller(index, type);
  1502. }
  1503. public void GSXR_Unbind_Controller(int index, int type) {
  1504. if (index != 0 && index != 1)
  1505. {
  1506. DebugMy.Log("GSXR_Unbind_Controller: index Must 1 or 0", this, true);
  1507. return;
  1508. }
  1509. plugin.GSXR_Unbind_Controller(index, type);
  1510. }
  1511. public int GSXR_Get_ControllerBondState()
  1512. {
  1513. return plugin.GSXR_Get_ControllerBondState();
  1514. }
  1515. public void GSXR_Set_ControllerBondEventCallback(bool isEnable)
  1516. {
  1517. if (isEnable)
  1518. {
  1519. plugin.GSXR_Set_ControllerBondEventCallback(ControllerBondStateCallBack);
  1520. }
  1521. else
  1522. {
  1523. plugin.GSXR_Set_ControllerBondEventCallback(null);
  1524. }
  1525. }
  1526. [MonoPInvokeCallback(typeof(Action<int>))]
  1527. private static void ControllerBondStateCallBack(int bondState)
  1528. {
  1529. if (OnBondStateEvent != null && OnBondStateEvent.GetInvocationList().Length != 0)
  1530. {
  1531. OnBondStateEvent(bondState);
  1532. }
  1533. }
  1534. private static Action<int> OnBondStateEvent;
  1535. public void GSXR_Add_ControllerBondEventCallback(Action<int> callback) //Register the Controller binding status callback
  1536. {
  1537. OnBondStateEvent += callback;
  1538. }
  1539. public void GSXR_Remove_ControllerBondEventCallback(Action<int> callback) //UnRegister the Controller binding status callback
  1540. {
  1541. OnBondStateEvent -= callback;
  1542. }
  1543. }