NxrEye.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. // Copyright 2016 Nibiru. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. using UnityEngine;
  15. using UnityEngine.Rendering;
  16. /// Controls one camera of a stereo pair. Each frame, it mirrors the settings of
  17. /// the parent mono Camera, and then sets up side-by-side stereo with
  18. /// the view and projection matrices from the NxrViewer.EyeView and NxrViewer.Projection.
  19. /// The render output is directed to the NxrViewer.StereoScreen render texture, either
  20. /// to the left half or right half depending on the chosen eye.
  21. ///
  22. ///
  23. /// @note If you programmatically change the set of NxrEyes belonging to a
  24. /// StereoController, be sure to call StereoController::InvalidateEyes on it
  25. /// in order to reset its cache.
  26. ///
  27. namespace Nxr.Internal
  28. {
  29. [RequireComponent(typeof(Camera))]
  30. [AddComponentMenu("NXR/Internal/NxrEye")]
  31. public class NxrEye : MonoBehaviour
  32. {
  33. public delegate void OnPostRenderCallback(int cacheTextureId, NxrViewer.Eye eyeType);
  34. public OnPostRenderCallback OnPostRenderListener;
  35. public delegate void OnPreRenderCallback(int cacheTextureId, NxrViewer.Eye eyeType);
  36. public OnPreRenderCallback OnPreRenderListener;
  37. /// Whether this is the left eye or the right eye.
  38. /// Determines which stereo eye to render, that is, which `EyeOffset` and
  39. /// `Projection` matrix to use and which half of the screen to render to.
  40. public NxrViewer.Eye eye;
  41. /// The StereoController in charge of this eye (and whose mono camera
  42. /// we will copy settings from).
  43. public NxrStereoController Controller
  44. {
  45. // This property is set up to work both in editor and in player.
  46. get
  47. {
  48. if (transform.parent == null)
  49. { // Should not happen.
  50. return null;
  51. }
  52. if ((Application.isEditor && !Application.isPlaying) || controller == null)
  53. {
  54. // Go find our controller.
  55. controller = transform.parent.GetComponentInParent<NxrStereoController>();
  56. if (controller == null)
  57. {
  58. controller = FindObjectOfType<NxrStereoController>();
  59. }
  60. }
  61. return controller;
  62. }
  63. set
  64. {
  65. controller = value;
  66. }
  67. }
  68. private NxrStereoController controller;
  69. private StereoRenderEffect stereoEffect;
  70. private Camera monoCamera;
  71. // Convenient accessor to the camera component used throughout this script.
  72. public Camera cam { get; private set; }
  73. public Transform cacheTransform;
  74. void Awake()
  75. {
  76. cam = GetComponent<Camera>();
  77. }
  78. void Start()
  79. {
  80. var ctlr = Controller;
  81. if (ctlr == null)
  82. {
  83. Debug.LogError("NxrEye must be child of a StereoController.");
  84. enabled = false;
  85. return;
  86. }
  87. // Save reference to the found controller and it's camera.
  88. controller = ctlr;
  89. monoCamera = controller.GetComponent<Camera>();
  90. cacheTransform = transform;
  91. }
  92. public void UpdateCameraProjection()
  93. {
  94. if (NxrGlobal.hasInfinityARSDK) return;
  95. // Debug.Log("NxrEye->UpdateStereoValues,"+eye.ToString());
  96. Matrix4x4 proj = NxrViewer.Instance.Projection(eye);
  97. Debug.Log("NxrEye->UpdateCameraProjection," + eye.ToString() + "/" + proj.ToString());
  98. bool useDFT = NxrViewer.USE_DTR && !NxrGlobal.supportDtr;
  99. //DTR不需要修正
  100. if (!NxrViewer.Instance.IsWinPlatform && (Application.isEditor || useDFT))
  101. {
  102. if (monoCamera == null) monoCamera = controller.GetComponent<Camera>();
  103. // Fix aspect ratio and near/far clipping planes.
  104. float nearClipPlane = monoCamera.nearClipPlane;
  105. float farClipPlane = monoCamera.farClipPlane;
  106. float near = (NxrGlobal.fovNear >= 0 && NxrGlobal.fovNear < nearClipPlane) ? NxrGlobal.fovNear : nearClipPlane;
  107. float far = (NxrGlobal.fovFar >= 0 && NxrGlobal.fovFar > farClipPlane) ? NxrGlobal.fovFar : farClipPlane;
  108. // DFT & 编辑器模式修正投影矩阵
  109. Debug.Log(eye.ToString() + ", " + cam.rect.ToString());
  110. NxrCameraUtils.FixProjection(cam.rect, near, far, ref proj);
  111. }
  112. // Set the eye camera's projection for rendering.
  113. cam.projectionMatrix = proj;
  114. NxrViewer.Instance.UpdateEyeCameraProjection(eye);
  115. float ipd = NxrViewer.Instance.Profile.viewer.lenses.separation;
  116. Vector3 localPosition = (eye == NxrViewer.Eye.Left ? -ipd / 2 : ipd / 2) * Vector3.right;
  117. if (localPosition.x != transform.localPosition.x)
  118. {
  119. transform.localPosition = localPosition;
  120. }
  121. BaseARDevice nxrDevice = NxrViewer.Instance.GetDevice();
  122. if (nxrDevice != null && nxrDevice.IsSptEyeLocalRotPos())
  123. {
  124. transform.localRotation = nxrDevice.GetEyeLocalRotation(eye);
  125. transform.localPosition = nxrDevice.GetEyeLocalPosition(eye);
  126. Debug.Log(eye + ". Local Rotation : " + transform.localRotation.eulerAngles.ToString());
  127. Debug.Log(eye + ". Local Position : " + transform.localPosition.x + "," + transform.localPosition.y + "," + transform.localPosition.z);
  128. }
  129. }
  130. private int cacheTextureId = -1;
  131. public int GetTargetTextureId()
  132. {
  133. return cacheTextureId;
  134. }
  135. public void UpdateTargetTexture()
  136. {
  137. // 从so获取纹理idx
  138. int eyeType = eye == NxrViewer.Eye.Left ? 0 : 1;
  139. cacheTextureId = NxrViewer.Instance.GetEyeTextureId(eyeType);
  140. cam.targetTexture = NxrViewer.Instance.GetStereoScreen(eyeType);
  141. cam.targetTexture.DiscardContents();
  142. }
  143. void OnPreRender()
  144. {
  145. if (cacheTextureId == -1 && cam.targetTexture != null)
  146. {
  147. cacheTextureId = (int)cam.targetTexture.GetNativeTexturePtr();
  148. }
  149. if(OnPreRenderListener != null) OnPreRenderListener(cacheTextureId, eye);
  150. }
  151. int frameId = 0;
  152. void OnPostRender()
  153. {
  154. if (cacheTextureId == -1 && cam.targetTexture != null)
  155. {
  156. cacheTextureId = (int)cam.targetTexture.GetNativeTexturePtr();
  157. }
  158. if(OnPostRenderListener != null) OnPostRenderListener(cacheTextureId, eye);
  159. if (eye == NxrViewer.Eye.Left)
  160. {
  161. // 录屏
  162. RenderTexture stereoScreen = cam.targetTexture;
  163. if (stereoScreen != null && NxrViewer.Instance.GetNibiruService() != null)
  164. {
  165. int textureId = (int)stereoScreen.GetNativeTexturePtr();
  166. bool isCapturing = NxrViewer.Instance.GetNibiruService().CaptureDrawFrame(textureId, frameId);
  167. if (isCapturing)
  168. {
  169. GL.InvalidateState();
  170. }
  171. frameId++;
  172. }
  173. }
  174. }
  175. private void SetupStereo()
  176. {
  177. int eyeType = eye == NxrViewer.Eye.Left ? 0 : 1;
  178. if (cam.targetTexture == null
  179. && NxrViewer.Instance.GetStereoScreen(eyeType) != null)
  180. {
  181. cam.targetTexture = monoCamera.targetTexture ?? NxrViewer.Instance.GetStereoScreen(eyeType);
  182. }
  183. }
  184. void OnPreCull()
  185. {
  186. if (NxrGlobal.DEBUG_LOG_ENABLED) Debug.Log(eye+".NxrEye.OnPreCull." + cam.rect.ToString());
  187. if (NxrGlobal.isVR9Platform)
  188. {
  189. cam.targetTexture = null;
  190. return;
  191. } else
  192. {
  193. // Debug.Log("OnPreCull.eye[" + eye + "]");
  194. if (!NxrViewer.Instance.SplitScreenModeEnabled)
  195. {
  196. // Keep stereo enabled flag in sync with parent mono camera.
  197. cam.enabled = false;
  198. return;
  199. }
  200. SetupStereo();
  201. int eyeType = eye == NxrViewer.Eye.Left ? 0 : 1;
  202. if (NxrGlobal.DEBUG_LOG_ENABLED) Debug.Log("OnPreCull.eye[" + eyeType + "]");
  203. if (NxrViewer.Instance.OpenEffectRender && NxrViewer.Instance.GetStereoScreen(eyeType) != null)
  204. {
  205. // Some image effects clobber the whole screen. Add a final image effect to the chain
  206. // which restores side-by-side stereo.
  207. stereoEffect = GetComponent<StereoRenderEffect>();
  208. if (stereoEffect == null)
  209. {
  210. stereoEffect = gameObject.AddComponent<StereoRenderEffect>();
  211. #if UNITY_5_6_OR_NEWER
  212. stereoEffect.UpdateEye(eye);
  213. #endif // UNITY_5_6_OR_NEWER
  214. }
  215. stereoEffect.enabled = true;
  216. }
  217. else if (stereoEffect != null)
  218. {
  219. // Don't need the side-by-side image effect.
  220. stereoEffect.enabled = false;
  221. }
  222. }
  223. }
  224. /// Helper to copy camera settings from the controller's mono camera. Used in SetupStereo() and
  225. /// in the custom editor for StereoController. The parameters parx and pary, if not left at
  226. /// default, should come from a projection matrix returned by the SDK. They affect the apparent
  227. /// depth of the camera's window. See SetupStereo().
  228. public void CopyCameraAndMakeSideBySide(NxrStereoController controller,
  229. float parx = 0, float pary = 0)
  230. {
  231. #if UNITY_EDITOR
  232. // Member variable 'cam' not always initialized when this method called in Editor.
  233. // So, we'll just make a local of the same name.
  234. var cam = GetComponent<Camera>();
  235. #endif
  236. float ipd = NxrViewer.Instance.Profile.viewer.lenses.separation;
  237. Vector3 localPosition = (eye == NxrViewer.Eye.Left ? -ipd / 2 : ipd / 2) * Vector3.right;
  238. if (monoCamera == null)
  239. {
  240. monoCamera = controller.GetComponent<Camera>();
  241. }
  242. // Sync the camera properties.
  243. cam.CopyFrom(monoCamera);
  244. #if UNITY_5_6_OR_NEWER
  245. cam.allowHDR = false;
  246. cam.allowMSAA = false;
  247. // cam.allowDynamicResolution = false;
  248. #endif
  249. monoCamera.useOcclusionCulling = false;
  250. // Not sure why we have to do this, but if we don't then switching between drawing to
  251. // the main screen or to the stereo rendertexture acts very strangely.
  252. cam.depth = eye == NxrViewer.Eye.Left ? monoCamera.depth + 1 : monoCamera.depth + 2;
  253. // Reset transform, which was clobbered by the CopyFrom() call.
  254. // Since we are a child of the mono camera, we inherit its transform already.
  255. transform.localPosition = localPosition;
  256. transform.localRotation = Quaternion.identity;
  257. transform.localScale = Vector3.one;
  258. Rect left = new Rect(0.0f, 0.0f, 0.5f, 1.0f);
  259. Rect right = new Rect(0.5f, 0.0f, 0.5f, 1.0f);
  260. if (eye == NxrViewer.Eye.Left)
  261. cam.rect = left;
  262. else
  263. cam.rect = right;
  264. // VR9 采用左右眼各分一半效果
  265. if (!NxrGlobal.isVR9Platform && NxrViewer.USE_DTR && NxrGlobal.supportDtr && Application.platform == RuntimePlatform.Android)
  266. {
  267. // DTR&DFT的Android模式左右眼视窗大小均为0~1
  268. cam.rect = new Rect(0, 0, 1, 1);
  269. }
  270. if (cam.farClipPlane < NxrGlobal.fovFar)
  271. {
  272. cam.farClipPlane = NxrGlobal.fovFar;
  273. }
  274. if(NxrGlobal.isVR9Platform)
  275. {
  276. // 已有绘制背景图,节省不必要的绘制操作
  277. cam.clearFlags = CameraClearFlags.Nothing;
  278. monoCamera.clearFlags = CameraClearFlags.Nothing;
  279. }
  280. #if NIBIRU_VR
  281. cam.aspect = 1.0f;
  282. #endif
  283. Debug.Log(eye.ToString() + "," + cam.transform.localPosition.x);
  284. }
  285. #if UNITY_STANDALONE_WIN || ANDROID_REMOTE_NRR
  286. public Material _flipMat;
  287. void OnRenderImage(RenderTexture source, RenderTexture destination)
  288. {
  289. if(_flipMat == null)
  290. {
  291. Debug.Log((eye == NxrViewer.Eye.Left ? "Materials/LeftEyeFlip" : "Materials/RightEyeFlip"));
  292. _flipMat = Resources.Load<Material>(eye == NxrViewer.Eye.Left ? "Materials/LeftEyeFlip" : "Materials/RightEyeFlip");
  293. }
  294. Graphics.Blit(source, destination, _flipMat);
  295. }
  296. #endif
  297. private void OnEnable()
  298. {
  299. #if UNITY_2019_1_OR_NEWER
  300. if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset != null)
  301. {
  302. RenderPipelineManager.beginCameraRendering += CameraPreRender;
  303. RenderPipelineManager.endCameraRendering += CameraPostRender;
  304. }
  305. #endif
  306. }
  307. private void OnDisable()
  308. {
  309. #if UNITY_2019_1_OR_NEWER
  310. if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset != null)
  311. {
  312. RenderPipelineManager.beginCameraRendering -= CameraPreRender;
  313. RenderPipelineManager.endCameraRendering -= CameraPostRender;
  314. }
  315. #endif
  316. }
  317. #if UNITY_2019_1_OR_NEWER
  318. public void CameraPreRender(ScriptableRenderContext context, Camera mcam)
  319. {
  320. //Debug.Log(Time.frameCount + "_CameraPreRender_" + mcam.name);
  321. if (mcam.gameObject != this.gameObject)
  322. return;
  323. OnPreCull();
  324. OnPreRender();
  325. }
  326. public void CameraPostRender(ScriptableRenderContext context, Camera mcam)
  327. {
  328. if (mcam.gameObject != this.gameObject)
  329. return;
  330. OnPostRender();
  331. }
  332. #endif
  333. }
  334. }