Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

448 lines
14 KiB

  1. /************************************************************************************
  2. Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
  3. Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
  4. the Utilities SDK except in compliance with the License, which is provided at the time of installation
  5. or download, or which otherwise accompanies this software in either electronic or hard copy form.
  6. You may obtain a copy of the License at
  7. https://developer.oculus.com/licenses/utilities-1.31
  8. Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
  9. under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  10. ANY KIND, either express or implied. See the License for the specific language governing
  11. permissions and limitations under the License.
  12. ************************************************************************************/
  13. using System.Collections;
  14. using System.Collections.Generic;
  15. using UnityEngine;
  16. using UnityEngine.Rendering;
  17. /// <summary>
  18. /// A component to apply a Colored vignette effect to the camera
  19. /// </summary>
  20. [RequireComponent(typeof(Camera))]
  21. [ExecuteInEditMode]
  22. public class OVRVignette : MonoBehaviour {
  23. /// <summary>
  24. /// Controls the number of triangles in the vignette mesh.
  25. /// </summary>
  26. public enum MeshComplexityLevel
  27. {
  28. VerySimple,
  29. Simple,
  30. Normal,
  31. Detailed,
  32. VeryDetailed
  33. }
  34. /// <summary>
  35. /// Controls the falloff appearance.
  36. /// </summary>
  37. public enum FalloffType
  38. {
  39. Linear,
  40. Quadratic
  41. }
  42. private static readonly string QUADRATIC_FALLOFF = "QUADRATIC_FALLOFF";
  43. [SerializeField]
  44. [HideInInspector]
  45. private Shader VignetteShader;
  46. // These are only used at startup.
  47. [SerializeField]
  48. [Tooltip("Controls the number of triangles used for the vignette mesh." +
  49. " Normal is best for most purposes.")]
  50. private MeshComplexityLevel MeshComplexity = MeshComplexityLevel.Normal;
  51. [SerializeField]
  52. [Tooltip("Controls how the falloff looks.")]
  53. private FalloffType Falloff = FalloffType.Linear;
  54. // These can be controlled dynamically at runtime
  55. [Tooltip("The Vertical FOV of the vignette")]
  56. public float VignetteFieldOfView = 60;
  57. [Tooltip("The Aspect ratio of the vignette controls the " +
  58. "Horizontal FOV. (Larger numbers are wider)")]
  59. public float VignetteAspectRatio = 1f;
  60. [Tooltip("The width of the falloff for the vignette in degrees")]
  61. public float VignetteFalloffDegrees = 10f;
  62. [ColorUsage(false)]
  63. [Tooltip("The color of the vignette. Alpha value is ignored")]
  64. public Color VignetteColor;
  65. private Camera _Camera;
  66. private MeshFilter _OpaqueMeshFilter;
  67. private MeshFilter _TransparentMeshFilter;
  68. private MeshRenderer _OpaqueMeshRenderer;
  69. private MeshRenderer _TransparentMeshRenderer;
  70. private Mesh _OpaqueMesh;
  71. private Mesh _TransparentMesh;
  72. private Material _OpaqueMaterial;
  73. private Material _TransparentMaterial;
  74. private int _ShaderScaleAndOffset0Property;
  75. private int _ShaderScaleAndOffset1Property;
  76. private Vector4[] _TransparentScaleAndOffset0 = new Vector4[2];
  77. private Vector4[] _TransparentScaleAndOffset1 = new Vector4[2];
  78. private Vector4[] _OpaqueScaleAndOffset0 = new Vector4[2];
  79. private Vector4[] _OpaqueScaleAndOffset1 = new Vector4[2];
  80. private bool _OpaqueVignetteVisible = false;
  81. private bool _TransparentVignetteVisible = false;
  82. #if UNITY_EDITOR
  83. // in the editor, allow these to be changed at runtime
  84. private MeshComplexityLevel _InitialMeshComplexity;
  85. private FalloffType _InitialFalloff;
  86. #endif
  87. private int GetTriangleCount()
  88. {
  89. switch(MeshComplexity)
  90. {
  91. case MeshComplexityLevel.VerySimple: return 32;
  92. case MeshComplexityLevel.Simple: return 64;
  93. case MeshComplexityLevel.Normal: return 128;
  94. case MeshComplexityLevel.Detailed: return 256;
  95. case MeshComplexityLevel.VeryDetailed: return 512;
  96. default: return 128;
  97. }
  98. }
  99. private void BuildMeshes()
  100. {
  101. #if UNITY_EDITOR
  102. _InitialMeshComplexity = MeshComplexity;
  103. #endif
  104. int triangleCount = GetTriangleCount();
  105. Vector3[] innerVerts = new Vector3[triangleCount];
  106. Vector2[] innerUVs = new Vector2[triangleCount];
  107. Vector3[] outerVerts = new Vector3[triangleCount];
  108. Vector2[] outerUVs = new Vector2[triangleCount];
  109. int[] tris = new int[triangleCount * 3];
  110. for (int i = 0; i < triangleCount; i += 2)
  111. {
  112. float angle = 2 * i * Mathf.PI / triangleCount;
  113. float x = Mathf.Cos(angle);
  114. float y = Mathf.Sin(angle);
  115. outerVerts[i] = new Vector3(x, y, 0);
  116. outerVerts[i + 1] = new Vector3(x, y, 0);
  117. outerUVs[i] = new Vector2(0, 1);
  118. outerUVs[i + 1] = new Vector2(1, 1);
  119. innerVerts[i] = new Vector3(x, y, 0);
  120. innerVerts[i + 1] = new Vector3(x, y, 0);
  121. innerUVs[i] = new Vector2(0, 1);
  122. innerUVs[i + 1] = new Vector2(1, 0);
  123. int ti = i * 3;
  124. tris[ti] = i;
  125. tris[ti + 1] = i + 1;
  126. tris[ti + 2] = (i + 2) % triangleCount;
  127. tris[ti + 3] = i + 1;
  128. tris[ti + 4] = (i + 3) % triangleCount;
  129. tris[ti + 5] = (i + 2) % triangleCount;
  130. }
  131. if (_OpaqueMesh != null)
  132. {
  133. DestroyImmediate(_OpaqueMesh);
  134. }
  135. if (_TransparentMesh != null)
  136. {
  137. DestroyImmediate(_TransparentMesh);
  138. }
  139. _OpaqueMesh = new Mesh()
  140. {
  141. name = "Opaque Vignette Mesh",
  142. hideFlags = HideFlags.HideAndDontSave
  143. };
  144. _TransparentMesh = new Mesh()
  145. {
  146. name = "Transparent Vignette Mesh",
  147. hideFlags = HideFlags.HideAndDontSave
  148. };
  149. _OpaqueMesh.vertices = outerVerts;
  150. _OpaqueMesh.uv = outerUVs;
  151. _OpaqueMesh.triangles = tris;
  152. _OpaqueMesh.UploadMeshData(true);
  153. _OpaqueMesh.bounds = new Bounds(Vector3.zero, Vector3.one * 10000);
  154. _OpaqueMeshFilter.sharedMesh = _OpaqueMesh;
  155. _TransparentMesh.vertices = innerVerts;
  156. _TransparentMesh.uv = innerUVs;
  157. _TransparentMesh.triangles = tris;
  158. _TransparentMesh.UploadMeshData(true);
  159. _TransparentMesh.bounds = new Bounds(Vector3.zero, Vector3.one * 10000);
  160. _TransparentMeshFilter.sharedMesh = _TransparentMesh;
  161. }
  162. private void BuildMaterials()
  163. {
  164. #if UNITY_EDITOR
  165. _InitialFalloff = Falloff;
  166. #endif
  167. if (VignetteShader == null)
  168. {
  169. VignetteShader = Shader.Find("Oculus/OVRVignette");
  170. }
  171. if (VignetteShader == null)
  172. {
  173. Debug.LogError("Could not find Vignette Shader! Vignette will not be drawn!");
  174. return;
  175. }
  176. if (_OpaqueMaterial == null)
  177. {
  178. _OpaqueMaterial = new Material(VignetteShader)
  179. {
  180. name = "Opaque Vignette Material",
  181. hideFlags = HideFlags.HideAndDontSave,
  182. renderQueue = (int)RenderQueue.Background
  183. };
  184. _OpaqueMaterial.SetFloat("_BlendSrc", (float)BlendMode.One);
  185. _OpaqueMaterial.SetFloat("_BlendDst", (float)BlendMode.Zero);
  186. _OpaqueMaterial.SetFloat("_ZWrite", 1);
  187. }
  188. _OpaqueMeshRenderer.sharedMaterial = _OpaqueMaterial;
  189. if (_TransparentMaterial == null)
  190. {
  191. _TransparentMaterial = new Material(VignetteShader)
  192. {
  193. name = "Transparent Vignette Material",
  194. hideFlags = HideFlags.HideAndDontSave,
  195. renderQueue = (int)RenderQueue.Overlay
  196. };
  197. _TransparentMaterial.SetFloat("_BlendSrc", (float)BlendMode.SrcAlpha);
  198. _TransparentMaterial.SetFloat("_BlendDst", (float)BlendMode.OneMinusSrcAlpha);
  199. _TransparentMaterial.SetFloat("_ZWrite", 0);
  200. }
  201. if (Falloff == FalloffType.Quadratic)
  202. {
  203. _TransparentMaterial.EnableKeyword(QUADRATIC_FALLOFF);
  204. }
  205. else
  206. {
  207. _TransparentMaterial.DisableKeyword(QUADRATIC_FALLOFF);
  208. }
  209. _TransparentMeshRenderer.sharedMaterial = _TransparentMaterial;
  210. }
  211. private void OnEnable()
  212. {
  213. #if UNITY_2019_1_OR_NEWER
  214. RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
  215. #elif UNITY_2018_1_OR_NEWER
  216. UnityEngine.Experimental.Rendering.RenderPipeline.beginCameraRendering += OnBeginCameraRendering;
  217. #endif
  218. }
  219. private void OnDisable()
  220. {
  221. #if UNITY_2019_1_OR_NEWER
  222. RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
  223. #elif UNITY_2018_1_OR_NEWER
  224. UnityEngine.Experimental.Rendering.RenderPipeline.beginCameraRendering -= OnBeginCameraRendering;
  225. #endif
  226. DisableRenderers();
  227. }
  228. private void Awake()
  229. {
  230. _Camera = GetComponent<Camera>();
  231. _ShaderScaleAndOffset0Property = Shader.PropertyToID("_ScaleAndOffset0");
  232. _ShaderScaleAndOffset1Property = Shader.PropertyToID("_ScaleAndOffset1");
  233. GameObject opaqueObject = new GameObject("Opaque Vignette") { hideFlags = HideFlags.HideAndDontSave };
  234. opaqueObject.transform.SetParent(_Camera.transform, false);
  235. _OpaqueMeshFilter = opaqueObject.AddComponent<MeshFilter>();
  236. _OpaqueMeshRenderer = opaqueObject.AddComponent<MeshRenderer>();
  237. _OpaqueMeshRenderer.receiveShadows = false;
  238. _OpaqueMeshRenderer.shadowCastingMode = ShadowCastingMode.Off;
  239. _OpaqueMeshRenderer.lightProbeUsage = LightProbeUsage.Off;
  240. _OpaqueMeshRenderer.reflectionProbeUsage = ReflectionProbeUsage.Off;
  241. _OpaqueMeshRenderer.allowOcclusionWhenDynamic = false;
  242. _OpaqueMeshRenderer.enabled = false;
  243. GameObject transparentObject = new GameObject("Transparent Vignette") { hideFlags = HideFlags.HideAndDontSave };
  244. transparentObject.transform.SetParent(_Camera.transform, false);
  245. _TransparentMeshFilter = transparentObject.AddComponent<MeshFilter>();
  246. _TransparentMeshRenderer = transparentObject.AddComponent<MeshRenderer>();
  247. _TransparentMeshRenderer.receiveShadows = false;
  248. _TransparentMeshRenderer.shadowCastingMode = ShadowCastingMode.Off;
  249. _TransparentMeshRenderer.lightProbeUsage = LightProbeUsage.Off;
  250. _TransparentMeshRenderer.reflectionProbeUsage = ReflectionProbeUsage.Off;
  251. _TransparentMeshRenderer.allowOcclusionWhenDynamic = false;
  252. _TransparentMeshRenderer.enabled = false;
  253. BuildMeshes();
  254. BuildMaterials();
  255. }
  256. private void GetTanFovAndOffsetForStereoEye(Camera.StereoscopicEye eye, out float tanFovX, out float tanFovY, out float offsetX, out float offsetY)
  257. {
  258. var pt = _Camera.GetStereoProjectionMatrix(eye).transpose;
  259. var right = pt * new Vector4(-1, 0, 0, 1);
  260. var left = pt * new Vector4(1, 0, 0, 1);
  261. var up = pt * new Vector4(0, -1, 0, 1);
  262. var down = pt * new Vector4(0, 1, 0, 1);
  263. float rightTanFovX = right.z / right.x;
  264. float leftTanFovX = left.z / left.x;
  265. float upTanFovY = up.z / up.y;
  266. float downTanFovY = down.z / down.y;
  267. offsetX = -(rightTanFovX + leftTanFovX) / 2;
  268. offsetY = -(upTanFovY + downTanFovY) / 2;
  269. tanFovX = (rightTanFovX - leftTanFovX) / 2;
  270. tanFovY = (upTanFovY - downTanFovY) / 2;
  271. }
  272. private void GetTanFovAndOffsetForMonoEye(out float tanFovX, out float tanFovY, out float offsetX, out float offsetY)
  273. {
  274. // When calculating from Unity's camera fields, this is the calculation used.
  275. // We can't use this for stereo eyes because VR projection matrices are usually asymmetric.
  276. tanFovY = Mathf.Tan(Mathf.Deg2Rad * _Camera.fieldOfView * 0.5f);
  277. tanFovX = tanFovY * _Camera.aspect;
  278. offsetX = 0f;
  279. offsetY = 0f;
  280. }
  281. private bool VisibilityTest(float scaleX, float scaleY, float offsetX, float offsetY)
  282. {
  283. // because the corners of our viewport are the furthest from the center of our vignette,
  284. // we only need to test that the farthest corner is outside the vignette ring.
  285. return new Vector2((1 + Mathf.Abs(offsetX)) / scaleX, (1 + Mathf.Abs(offsetY)) / scaleY).sqrMagnitude > 1.0f;
  286. }
  287. private void Update()
  288. {
  289. #if UNITY_EDITOR
  290. if (MeshComplexity != _InitialMeshComplexity)
  291. {
  292. // rebuild meshes
  293. BuildMeshes();
  294. }
  295. if(Falloff != _InitialFalloff)
  296. {
  297. // rebuild materials
  298. BuildMaterials();
  299. }
  300. #endif
  301. // The opaque material could not be created, so just return
  302. if (_OpaqueMaterial == null)
  303. {
  304. return;
  305. }
  306. float tanInnerFovY = Mathf.Tan(VignetteFieldOfView * Mathf.Deg2Rad * 0.5f);
  307. float tanInnerFovX = tanInnerFovY * VignetteAspectRatio;
  308. float tanMiddleFovX = Mathf.Tan((VignetteFieldOfView + VignetteFalloffDegrees) * Mathf.Deg2Rad * 0.5f);
  309. float tanMiddleFovY = tanMiddleFovX * VignetteAspectRatio;
  310. _TransparentVignetteVisible = false;
  311. _OpaqueVignetteVisible = false;
  312. for (int i = 0; i < 2; i++)
  313. {
  314. float tanFovX, tanFovY, offsetX, offsetY;
  315. if (_Camera.stereoEnabled)
  316. {
  317. GetTanFovAndOffsetForStereoEye((Camera.StereoscopicEye)i, out tanFovX, out tanFovY, out offsetX, out offsetY);
  318. }
  319. else
  320. {
  321. GetTanFovAndOffsetForMonoEye(out tanFovX, out tanFovY, out offsetX, out offsetY);
  322. }
  323. float borderScale = new Vector2((1 + Mathf.Abs(offsetX)) / VignetteAspectRatio, 1 + Mathf.Abs(offsetY)).magnitude * 1.01f;
  324. float innerScaleX = tanInnerFovX / tanFovX;
  325. float innerScaleY = tanInnerFovY / tanFovY;
  326. float middleScaleX = tanMiddleFovX / tanFovX;
  327. float middleScaleY = tanMiddleFovY / tanFovY;
  328. float outerScaleX = borderScale * VignetteAspectRatio;
  329. float outerScaleY = borderScale;
  330. // test for visibility.
  331. _TransparentVignetteVisible |= VisibilityTest(innerScaleX, innerScaleY, offsetX, offsetY);
  332. _OpaqueVignetteVisible |= VisibilityTest(middleScaleX, middleScaleY, offsetX, offsetY);
  333. _OpaqueScaleAndOffset0[i] = new Vector4(outerScaleX, outerScaleY, offsetX, offsetY);
  334. _OpaqueScaleAndOffset1[i] = new Vector4(middleScaleX, middleScaleY, offsetX, offsetY);
  335. _TransparentScaleAndOffset0[i] = new Vector4(middleScaleX, middleScaleY, offsetX, offsetY);
  336. _TransparentScaleAndOffset1[i] = new Vector4(innerScaleX, innerScaleY, offsetX, offsetY);
  337. }
  338. // if the vignette falloff is less than or equal to zero, we don't need to draw
  339. // the transparent mesh.
  340. _TransparentVignetteVisible &= VignetteFalloffDegrees > 0.0f;
  341. _OpaqueMaterial.SetVectorArray(_ShaderScaleAndOffset0Property, _OpaqueScaleAndOffset0);
  342. _OpaqueMaterial.SetVectorArray(_ShaderScaleAndOffset1Property, _OpaqueScaleAndOffset1);
  343. _OpaqueMaterial.color = VignetteColor;
  344. _TransparentMaterial.SetVectorArray(_ShaderScaleAndOffset0Property, _TransparentScaleAndOffset0);
  345. _TransparentMaterial.SetVectorArray(_ShaderScaleAndOffset1Property, _TransparentScaleAndOffset1);
  346. _TransparentMaterial.color = VignetteColor;
  347. }
  348. private void EnableRenderers()
  349. {
  350. _OpaqueMeshRenderer.enabled = _OpaqueVignetteVisible;
  351. _TransparentMeshRenderer.enabled = _TransparentVignetteVisible;
  352. }
  353. private void DisableRenderers()
  354. {
  355. _OpaqueMeshRenderer.enabled = false;
  356. _TransparentMeshRenderer.enabled = false;
  357. }
  358. // Objects are enabled on pre cull and disabled on post render so they only draw in this camera
  359. private void OnPreCull()
  360. {
  361. EnableRenderers();
  362. }
  363. private void OnPostRender()
  364. {
  365. DisableRenderers();
  366. }
  367. #if UNITY_2019_1_OR_NEWER
  368. private void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
  369. #else
  370. private void OnBeginCameraRendering(Camera camera)
  371. #endif
  372. {
  373. if (camera == _Camera)
  374. {
  375. EnableRenderers();
  376. }
  377. else
  378. {
  379. DisableRenderers();
  380. }
  381. }
  382. }