GSXREye.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine.Rendering;
  6. public class GSXREye : MonoBehaviour, IComparable<GSXREye>
  7. {
  8. public static List<GSXREye> Instances = new List<GSXREye>();
  9. public enum eSide
  10. {
  11. Left = 1,
  12. Right = 2,
  13. Both = 3,
  14. [HideInInspector]
  15. Count = Both
  16. };
  17. public enum eType
  18. {
  19. RenderTexture = 0,
  20. StandardTexture = 1,
  21. EglTexture = 2,
  22. };
  23. public delegate void OnPostRenderCallback(int sideMask, int layerMask);
  24. public OnPostRenderCallback OnPostRenderListener;
  25. public delegate void OnPreRenderCallback(int sideMask, int textureId, int previousId);
  26. public OnPreRenderCallback OnPreRenderListener;
  27. [Tooltip("Layer depth stack")]
  28. public int layerDepth = 0;
  29. [Tooltip("Image display transform")]
  30. public Camera imageCamera;
  31. [Tooltip("Image type: 0/Camera render target, 1/Texture 2d, 2/External egl")]
  32. public eType imageType = eType.RenderTexture;
  33. [Tooltip("Image texture used when ImageType is StandardTexture")]
  34. public Texture imageTexture;
  35. [Tooltip("Image transform for scale, rotation and position (optional)")]
  36. public Transform imageTransform;
  37. [Tooltip("Image display region (camera clip space)")]
  38. public Vector4 clipLowerLeft = new Vector4(-1, -1, 0, 1);
  39. public Vector4 clipUpperLeft = new Vector4(-1, 1, 0, 1);
  40. public Vector4 clipUpperRight = new Vector4(1, 1, 0, 1);
  41. public Vector4 clipLowerRight = new Vector4(1, -1, 0, 1);
  42. [Tooltip("Image source region (texture uv space)")]
  43. public Vector2 uvLowerLeft = new Vector2(0, 0);
  44. public Vector2 uvUpperLeft = new Vector2(0, 1);
  45. public Vector2 uvUpperRight = new Vector2(1, 1);
  46. public Vector2 uvLowerRight = new Vector2(1, 0);
  47. [Tooltip("Side mask")]
  48. public eSide side = eSide.Both;
  49. private float fovMargin = 0f;
  50. private RenderTextureFormat format = RenderTextureFormat.Default;
  51. private Vector2 resolution = new Vector2(1920, 1080);
  52. private float resolutionScaleFactor = 1.0f;
  53. private int antiAliasing = 1;
  54. private int depth = 24;
  55. private int frustumType = 0;
  56. private const int bufferCount = 3;
  57. private RenderTexture[] eyeTextures = new RenderTexture[bufferCount];
  58. private int[] eyeTextureIds = new int[bufferCount];
  59. private int currentTextureIndex = 0;
  60. private Camera[] mainCameras = null;
  61. private bool dirty = false;
  62. private Coroutine recreateBuffersCoroutine = null;
  63. public RenderTexture depthRT;
  64. public int depthRTID=0;
  65. public int CompareTo(GSXREye that)
  66. {
  67. return this.layerDepth.CompareTo(that.layerDepth);
  68. }
  69. public float FovMargin
  70. {
  71. get { return fovMargin; }
  72. set { fovMargin = value; }
  73. }
  74. public int FrustumType
  75. {
  76. get { return frustumType; }
  77. set { frustumType = value; }
  78. }
  79. public void SetImage(Texture2D texture)
  80. {
  81. imageTexture = texture;
  82. InitializeBuffers();
  83. }
  84. public eType ImageType
  85. {
  86. get { return imageType; }
  87. set { imageType = value; }
  88. }
  89. public eSide Side
  90. {
  91. get { return side; }
  92. set { side = value; }
  93. }
  94. public RenderTextureFormat Format
  95. {
  96. get { return format; }
  97. set { SetDirty(format != value); format = value; }
  98. }
  99. public int AntiAliasing
  100. {
  101. get { return antiAliasing; }
  102. set { SetDirty(antiAliasing != value); antiAliasing = value; }
  103. }
  104. public int Depth
  105. {
  106. get { return depth; }
  107. set { SetDirty(depth != value); depth = value; }
  108. }
  109. public Vector2 Resolution
  110. {
  111. get { return resolution; }
  112. set { SetDirty(!Mathf.Approximately(resolution.x, value.x) || !Mathf.Approximately(resolution.y, value.y)); resolution = value; }
  113. }
  114. public float ResolutionScaleFactor
  115. {
  116. get { return resolutionScaleFactor; }
  117. set { SetDirty(!Mathf.Approximately(resolutionScaleFactor, value)); resolutionScaleFactor = value; }
  118. }
  119. void SetDirty(bool value)
  120. {
  121. dirty = dirty == true ? true : value;
  122. }
  123. public int TextureId
  124. {
  125. get { return eyeTextureIds[currentTextureIndex]; }
  126. set { eyeTextureIds[currentTextureIndex] = value; }
  127. }
  128. public int PreviousId
  129. {
  130. get { return eyeTextureIds[(currentTextureIndex + bufferCount - 1) % bufferCount]; }
  131. }
  132. public Texture TexturePtr
  133. {
  134. get { return (imageTexture != null ? imageTexture : (Texture)eyeTextures[currentTextureIndex]); }
  135. }
  136. void Awake()
  137. {
  138. Instances.Add(this);
  139. AcquireComponents();
  140. InitializeCoords();
  141. }
  142. void OnDestroy()
  143. {
  144. Instances.Remove(this);
  145. }
  146. void AcquireComponents()
  147. {
  148. if (imageCamera == null) imageCamera = gameObject.GetComponent<Camera>();
  149. Debug.Assert(imageCamera != null, "ImageCamera object required");
  150. mainCameras = imageCamera.GetComponentsInChildren<Camera>();
  151. foreach(var item in mainCameras){
  152. item.enabled = false;
  153. }
  154. }
  155. IEnumerator WaitSlam() {
  156. yield return new WaitUntil(()=> GSXRManager.Instance.IsRunning);
  157. foreach (var item in mainCameras) {
  158. item.enabled = true;
  159. //if (API_Module_Device.Current.XRType == SC.XR.Unity.XRType.VR) {
  160. // item.clearFlags = CameraClearFlags.Skybox;
  161. //} else if (API_Module_Device.Current.XRType == SC.XR.Unity.XRType.AR || API_Module_Device.Current.XRType == SC.XR.Unity.XRType.MR) {
  162. // item.clearFlags = CameraClearFlags.Color;
  163. //}
  164. }
  165. }
  166. void Start()
  167. {
  168. //Initialize(); Called by GSXRManager.InitializeEyes()
  169. StartCoroutine(WaitSlam()) ;
  170. }
  171. void LateUpdate()
  172. {
  173. UpdateCoords();
  174. }
  175. public void Initialize()
  176. {
  177. InitializeBuffers();
  178. InitializeCameras();
  179. if (imageCamera && GSXRManager.Instance.IsCreateDepthRT) {
  180. imageCamera.depthTextureMode |= DepthTextureMode.Depth;
  181. depthRT = new RenderTexture(eyeTextures[currentTextureIndex]);
  182. depthRT.Create();
  183. depthRTID = depthRT.GetNativeTexturePtr().ToInt32();
  184. }
  185. }
  186. void InitializeBuffers()
  187. {
  188. for (int i = 0; i < bufferCount; ++i)
  189. {
  190. if (eyeTextures[i] != null)
  191. eyeTextures[i].Release();
  192. switch(imageType)
  193. {
  194. case eType.RenderTexture:
  195. eyeTextures[i] = new RenderTexture((int)(resolution.x * resolutionScaleFactor), (int)(resolution.y * resolutionScaleFactor), depth, format);
  196. eyeTextures[i].antiAliasing = antiAliasing;
  197. eyeTextures[i].Create();
  198. eyeTextureIds[i] = eyeTextures[i].GetNativeTexturePtr().ToInt32();
  199. //Debug.Log("Create Render Texture with ID: " + eyeTextureIds[i] + " Width: " + eyeTextures[i].width + " Height: " + eyeTextures[i].height + " AA: " + eyeTextures[i].antiAliasing);
  200. break;
  201. case eType.StandardTexture:
  202. if (imageTexture) eyeTextureIds[i] = imageTexture.GetNativeTexturePtr().ToInt32();
  203. break;
  204. case eType.EglTexture:
  205. eyeTextureIds[i] = 0;
  206. break;
  207. }
  208. }
  209. dirty = false;
  210. }
  211. void InitializeCameras()
  212. {
  213. var deviceInfo = GSXRPlugin.Instance.deviceInfo;
  214. var deviceFov = new Vector2(deviceInfo.targetFovXRad, deviceInfo.targetFovYRad) * Mathf.Rad2Deg;
  215. var frustum = side == eSide.Right ? deviceInfo.targetFrustumRight : deviceInfo.targetFrustumLeft;
  216. foreach (var mainCamera in mainCameras)
  217. {
  218. if (frustumType == (int)GSXRManager.SlamSettings.eFrustumType.Camera)
  219. {
  220. mainCamera.fieldOfView = deviceFov.y + FovMargin * deviceFov.y;
  221. mainCamera.aspect = deviceFov.x / deviceFov.y;
  222. }
  223. else if (frustumType == (int)GSXRManager.SlamSettings.eFrustumType.Device)
  224. {
  225. mainCamera.fieldOfView = deviceFov.y;
  226. mainCamera.aspect = deviceFov.x / deviceFov.y;
  227. mainCamera.projectionMatrix = GSXRManager.Perspective(frustum.left, frustum.right, frustum.bottom, frustum.top, frustum.near, mainCamera.farClipPlane);
  228. }
  229. }
  230. }
  231. void InitializeCoords()
  232. {
  233. clipLowerLeft.Set(-1, -1, 0, 1);
  234. clipUpperLeft.Set(-1, 1, 0, 1);
  235. clipUpperRight.Set(1, 1, 0, 1);
  236. clipLowerRight.Set(1, -1, 0, 1);
  237. }
  238. void UpdateCoords()
  239. {
  240. if (imageTransform == null)
  241. return;
  242. var viewCamera = mainCameras[0];
  243. if (viewCamera == null)
  244. return;
  245. var extents = 0.5f * Vector3.one;
  246. var center = Vector3.zero;
  247. var worldLowerLeft = new Vector4(center.x - extents.x, center.y - extents.y, 0, 1);
  248. var worldUpperLeft = new Vector4(center.x - extents.x, center.y + extents.y, 0, 1);
  249. var worldUpperRight = new Vector4(center.x + extents.x, center.y + extents.y, 0, 1);
  250. var worldLowerRight = new Vector4(center.x + extents.x, center.y - extents.y, 0, 1);
  251. Matrix4x4 MVP = viewCamera.projectionMatrix * viewCamera.worldToCameraMatrix * imageTransform.localToWorldMatrix;
  252. clipLowerLeft = MVP * worldLowerLeft;
  253. clipUpperLeft = MVP * worldUpperLeft;
  254. clipUpperRight = MVP * worldUpperRight;
  255. clipLowerRight = MVP * worldLowerRight;
  256. }
  257. void OnPreCull() {
  258. if (side == eSide.Left) {
  259. Fps.tempLeftRenderTime = Time.realtimeSinceStartup;
  260. } else if (side == eSide.Right) {
  261. Fps.tempRightRenderTime = Time.realtimeSinceStartup;
  262. }
  263. }
  264. void OnPreRender()
  265. {
  266. if (imageType != eType.RenderTexture) return;
  267. SwapBuffers();
  268. if (OnPreRenderListener != null)
  269. {
  270. OnPreRenderListener((int)side, TextureId, PreviousId);
  271. }
  272. }
  273. void SwapBuffers()
  274. {
  275. if (imageType != eType.RenderTexture) return;
  276. currentTextureIndex = ++currentTextureIndex % bufferCount;
  277. var targetTexture = eyeTextures[currentTextureIndex];
  278. if (targetTexture == null) return;
  279. for (int i = 0; i < mainCameras.Length; i++)
  280. {
  281. mainCameras[i].targetTexture = targetTexture;
  282. }
  283. targetTexture.DiscardContents();
  284. }
  285. void OnPostRender()
  286. {
  287. RecreateBuffersIfDirty();
  288. if (OnPostRenderListener != null)
  289. {
  290. OnPostRenderListener((int)side, 0x0);
  291. }
  292. if (depthRT) {
  293. Graphics.Blit(eyeTextures[currentTextureIndex], depthRT, GSXRManager.Instance.DepthM);
  294. }
  295. if (side == eSide.Left) {
  296. Fps.LeftRenderTime = Mathf.Lerp(Fps.LeftRenderTime, 1000 * (Time.realtimeSinceStartup - Fps.tempLeftRenderTime), Fps.lerp);
  297. } else if (side == eSide.Right) {
  298. Fps.RightRenderTime = Mathf.Lerp(Fps.RightRenderTime, 1000 * (Time.realtimeSinceStartup - Fps.tempRightRenderTime), Fps.lerp);
  299. }
  300. Fps.ALLLogicAndRenderTime = Mathf.Lerp(Fps.ALLLogicAndRenderTime, 1000 * (Time.realtimeSinceStartup - Fps.StartALLLogicAndRenderTime), Fps.lerp);
  301. }
  302. void RecreateBuffersIfDirty()
  303. {
  304. if (dirty)
  305. {
  306. if (recreateBuffersCoroutine != null)
  307. {
  308. StopCoroutine(recreateBuffersCoroutine);
  309. recreateBuffersCoroutine = null;
  310. }
  311. recreateBuffersCoroutine = StartCoroutine(RecreateBuffersDeferred());
  312. dirty = false;
  313. }
  314. }
  315. IEnumerator RecreateBuffersDeferred()
  316. {
  317. int i = 0;
  318. while (i < bufferCount)
  319. {
  320. int index = currentTextureIndex - 1;
  321. index = index >= 0 ? index : bufferCount - 1;
  322. if (eyeTextures[index] != null)
  323. eyeTextures[index].Release();
  324. switch (imageType)
  325. {
  326. case eType.RenderTexture:
  327. eyeTextures[index] = new RenderTexture((int)(resolution.x * resolutionScaleFactor), (int)(resolution.y * resolutionScaleFactor), depth, format);
  328. eyeTextures[index].antiAliasing = antiAliasing;
  329. eyeTextures[index].Create();
  330. eyeTextureIds[index] = eyeTextures[index].GetNativeTexturePtr().ToInt32();
  331. Debug.Log("Re-create Render Texture with ID: " + eyeTextureIds[index] + " Width: " + eyeTextures[index].width + " Height: " + eyeTextures[index].height + " AA: " + eyeTextures[index].antiAliasing);
  332. break;
  333. case eType.StandardTexture:
  334. if (imageTexture) eyeTextureIds[index] = imageTexture.GetNativeTexturePtr().ToInt32();
  335. break;
  336. case eType.EglTexture:
  337. eyeTextureIds[index] = 0;
  338. break;
  339. }
  340. int prevTextureIndex = currentTextureIndex;
  341. yield return new WaitUntil(() => currentTextureIndex != prevTextureIndex);
  342. i++;
  343. }
  344. yield break;
  345. }
  346. }