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.

470 lines
17 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Rendering;
  4. namespace UnityEngine.PostProcessing
  5. {
  6. using DebugMode = BuiltinDebugViewsModel.Mode;
  7. #if UNITY_5_4_OR_NEWER
  8. [ImageEffectAllowedInSceneView]
  9. #endif
  10. [RequireComponent(typeof(Camera)), DisallowMultipleComponent, ExecuteInEditMode]
  11. [AddComponentMenu("Effects/Post-Processing Behaviour", -1)]
  12. public class PostProcessingBehaviour : MonoBehaviour
  13. {
  14. // Inspector fields
  15. public PostProcessingProfile profile;
  16. public Func<Vector2, Matrix4x4> jitteredMatrixFunc;
  17. // Internal helpers
  18. Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>> m_CommandBuffers;
  19. List<PostProcessingComponentBase> m_Components;
  20. Dictionary<PostProcessingComponentBase, bool> m_ComponentStates;
  21. MaterialFactory m_MaterialFactory;
  22. RenderTextureFactory m_RenderTextureFactory;
  23. PostProcessingContext m_Context;
  24. Camera m_Camera;
  25. PostProcessingProfile m_PreviousProfile;
  26. bool m_RenderingInSceneView = false;
  27. // Effect components
  28. BuiltinDebugViewsComponent m_DebugViews;
  29. AmbientOcclusionComponent m_AmbientOcclusion;
  30. ScreenSpaceReflectionComponent m_ScreenSpaceReflection;
  31. FogComponent m_FogComponent;
  32. MotionBlurComponent m_MotionBlur;
  33. TaaComponent m_Taa;
  34. EyeAdaptationComponent m_EyeAdaptation;
  35. DepthOfFieldComponent m_DepthOfField;
  36. BloomComponent m_Bloom;
  37. ChromaticAberrationComponent m_ChromaticAberration;
  38. ColorGradingComponent m_ColorGrading;
  39. UserLutComponent m_UserLut;
  40. GrainComponent m_Grain;
  41. VignetteComponent m_Vignette;
  42. DitheringComponent m_Dithering;
  43. FxaaComponent m_Fxaa;
  44. void OnEnable()
  45. {
  46. m_CommandBuffers = new Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>>();
  47. m_MaterialFactory = new MaterialFactory();
  48. m_RenderTextureFactory = new RenderTextureFactory();
  49. m_Context = new PostProcessingContext();
  50. // Keep a list of all post-fx for automation purposes
  51. m_Components = new List<PostProcessingComponentBase>();
  52. // Component list
  53. m_DebugViews = AddComponent(new BuiltinDebugViewsComponent());
  54. m_AmbientOcclusion = AddComponent(new AmbientOcclusionComponent());
  55. m_ScreenSpaceReflection = AddComponent(new ScreenSpaceReflectionComponent());
  56. m_FogComponent = AddComponent(new FogComponent());
  57. m_MotionBlur = AddComponent(new MotionBlurComponent());
  58. m_Taa = AddComponent(new TaaComponent());
  59. m_EyeAdaptation = AddComponent(new EyeAdaptationComponent());
  60. m_DepthOfField = AddComponent(new DepthOfFieldComponent());
  61. m_Bloom = AddComponent(new BloomComponent());
  62. m_ChromaticAberration = AddComponent(new ChromaticAberrationComponent());
  63. m_ColorGrading = AddComponent(new ColorGradingComponent());
  64. m_UserLut = AddComponent(new UserLutComponent());
  65. m_Grain = AddComponent(new GrainComponent());
  66. m_Vignette = AddComponent(new VignetteComponent());
  67. m_Dithering = AddComponent(new DitheringComponent());
  68. m_Fxaa = AddComponent(new FxaaComponent());
  69. // Prepare state observers
  70. m_ComponentStates = new Dictionary<PostProcessingComponentBase, bool>();
  71. foreach (var component in m_Components)
  72. m_ComponentStates.Add(component, false);
  73. useGUILayout = false;
  74. }
  75. void OnPreCull()
  76. {
  77. // All the per-frame initialization logic has to be done in OnPreCull instead of Update
  78. // because [ImageEffectAllowedInSceneView] doesn't trigger Update events...
  79. m_Camera = GetComponent<Camera>();
  80. if (profile == null || m_Camera == null)
  81. return;
  82. #if UNITY_EDITOR
  83. // Track the scene view camera to disable some effects we don't want to see in the
  84. // scene view
  85. // Currently disabled effects :
  86. // - Temporal Antialiasing
  87. // - Depth of Field
  88. // - Motion blur
  89. m_RenderingInSceneView = UnityEditor.SceneView.currentDrawingSceneView != null
  90. && UnityEditor.SceneView.currentDrawingSceneView.camera == m_Camera;
  91. #endif
  92. // Prepare context
  93. var context = m_Context.Reset();
  94. context.profile = profile;
  95. context.renderTextureFactory = m_RenderTextureFactory;
  96. context.materialFactory = m_MaterialFactory;
  97. context.camera = m_Camera;
  98. // Prepare components
  99. m_DebugViews.Init(context, profile.debugViews);
  100. m_AmbientOcclusion.Init(context, profile.ambientOcclusion);
  101. m_ScreenSpaceReflection.Init(context, profile.screenSpaceReflection);
  102. m_FogComponent.Init(context, profile.fog);
  103. m_MotionBlur.Init(context, profile.motionBlur);
  104. m_Taa.Init(context, profile.antialiasing);
  105. m_EyeAdaptation.Init(context, profile.eyeAdaptation);
  106. m_DepthOfField.Init(context, profile.depthOfField);
  107. m_Bloom.Init(context, profile.bloom);
  108. m_ChromaticAberration.Init(context, profile.chromaticAberration);
  109. m_ColorGrading.Init(context, profile.colorGrading);
  110. m_UserLut.Init(context, profile.userLut);
  111. m_Grain.Init(context, profile.grain);
  112. m_Vignette.Init(context, profile.vignette);
  113. m_Dithering.Init(context, profile.dithering);
  114. m_Fxaa.Init(context, profile.antialiasing);
  115. // Handles profile change and 'enable' state observers
  116. if (m_PreviousProfile != profile)
  117. {
  118. DisableComponents();
  119. m_PreviousProfile = profile;
  120. }
  121. CheckObservers();
  122. // Find out which camera flags are needed before rendering begins
  123. // Note that motion vectors will only be available one frame after being enabled
  124. var flags = context.camera.depthTextureMode;
  125. foreach (var component in m_Components)
  126. {
  127. if (component.active)
  128. flags |= component.GetCameraFlags();
  129. }
  130. context.camera.depthTextureMode = flags;
  131. // Temporal antialiasing jittering, needs to happen before culling
  132. if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt)
  133. m_Taa.SetProjectionMatrix(jitteredMatrixFunc);
  134. }
  135. void OnPreRender()
  136. {
  137. if (profile == null)
  138. return;
  139. // Command buffer-based effects should be set-up here
  140. TryExecuteCommandBuffer(m_DebugViews);
  141. TryExecuteCommandBuffer(m_AmbientOcclusion);
  142. TryExecuteCommandBuffer(m_ScreenSpaceReflection);
  143. TryExecuteCommandBuffer(m_FogComponent);
  144. if (!m_RenderingInSceneView)
  145. TryExecuteCommandBuffer(m_MotionBlur);
  146. }
  147. void OnPostRender()
  148. {
  149. if (profile == null || m_Camera == null)
  150. return;
  151. if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt)
  152. m_Context.camera.ResetProjectionMatrix();
  153. }
  154. // Classic render target pipeline for RT-based effects
  155. void OnRenderImage(RenderTexture source, RenderTexture destination)
  156. {
  157. if (profile == null || m_Camera == null)
  158. {
  159. Graphics.Blit(source, destination);
  160. return;
  161. }
  162. // Uber shader setup
  163. bool uberActive = false;
  164. bool fxaaActive = m_Fxaa.active;
  165. bool taaActive = m_Taa.active && !m_RenderingInSceneView;
  166. bool dofActive = m_DepthOfField.active && !m_RenderingInSceneView;
  167. var uberMaterial = m_MaterialFactory.Get("Hidden/Post FX/Uber Shader");
  168. uberMaterial.shaderKeywords = null;
  169. var src = source;
  170. var dst = destination;
  171. if (taaActive)
  172. {
  173. var tempRT = m_RenderTextureFactory.Get(src);
  174. m_Taa.Render(src, tempRT);
  175. src = tempRT;
  176. }
  177. #if UNITY_EDITOR
  178. // Render to a dedicated target when monitors are enabled so they can show information
  179. // about the final render.
  180. // At runtime the output will always be the backbuffer or whatever render target is
  181. // currently set on the camera.
  182. if (profile.monitors.onFrameEndEditorOnly != null)
  183. dst = m_RenderTextureFactory.Get(src);
  184. #endif
  185. Texture autoExposure = GraphicsUtils.whiteTexture;
  186. if (m_EyeAdaptation.active)
  187. {
  188. uberActive = true;
  189. autoExposure = m_EyeAdaptation.Prepare(src, uberMaterial);
  190. }
  191. uberMaterial.SetTexture("_AutoExposure", autoExposure);
  192. if (dofActive)
  193. {
  194. uberActive = true;
  195. m_DepthOfField.Prepare(src, uberMaterial, taaActive, m_Taa.jitterVector, m_Taa.model.settings.taaSettings.motionBlending);
  196. }
  197. if (m_Bloom.active)
  198. {
  199. uberActive = true;
  200. m_Bloom.Prepare(src, uberMaterial, autoExposure);
  201. }
  202. uberActive |= TryPrepareUberImageEffect(m_ChromaticAberration, uberMaterial);
  203. uberActive |= TryPrepareUberImageEffect(m_ColorGrading, uberMaterial);
  204. uberActive |= TryPrepareUberImageEffect(m_Vignette, uberMaterial);
  205. uberActive |= TryPrepareUberImageEffect(m_UserLut, uberMaterial);
  206. var fxaaMaterial = fxaaActive
  207. ? m_MaterialFactory.Get("Hidden/Post FX/FXAA")
  208. : null;
  209. if (fxaaActive)
  210. {
  211. fxaaMaterial.shaderKeywords = null;
  212. TryPrepareUberImageEffect(m_Grain, fxaaMaterial);
  213. TryPrepareUberImageEffect(m_Dithering, fxaaMaterial);
  214. if (uberActive)
  215. {
  216. var output = m_RenderTextureFactory.Get(src);
  217. Graphics.Blit(src, output, uberMaterial, 0);
  218. src = output;
  219. }
  220. m_Fxaa.Render(src, dst);
  221. }
  222. else
  223. {
  224. uberActive |= TryPrepareUberImageEffect(m_Grain, uberMaterial);
  225. uberActive |= TryPrepareUberImageEffect(m_Dithering, uberMaterial);
  226. if (uberActive)
  227. {
  228. if (!GraphicsUtils.isLinearColorSpace)
  229. uberMaterial.EnableKeyword("UNITY_COLORSPACE_GAMMA");
  230. Graphics.Blit(src, dst, uberMaterial, 0);
  231. }
  232. }
  233. if (!uberActive && !fxaaActive)
  234. Graphics.Blit(src, dst);
  235. #if UNITY_EDITOR
  236. if (profile.monitors.onFrameEndEditorOnly != null)
  237. {
  238. Graphics.Blit(dst, destination);
  239. var oldRt = RenderTexture.active;
  240. profile.monitors.onFrameEndEditorOnly(dst);
  241. RenderTexture.active = oldRt;
  242. }
  243. #endif
  244. m_RenderTextureFactory.ReleaseAll();
  245. }
  246. void OnGUI()
  247. {
  248. if (Event.current.type != EventType.Repaint)
  249. return;
  250. if (profile == null || m_Camera == null)
  251. return;
  252. if (m_EyeAdaptation.active && profile.debugViews.IsModeActive(DebugMode.EyeAdaptation))
  253. m_EyeAdaptation.OnGUI();
  254. else if (m_ColorGrading.active && profile.debugViews.IsModeActive(DebugMode.LogLut))
  255. m_ColorGrading.OnGUI();
  256. else if (m_UserLut.active && profile.debugViews.IsModeActive(DebugMode.UserLut))
  257. m_UserLut.OnGUI();
  258. }
  259. void OnDisable()
  260. {
  261. // Clear command buffers
  262. foreach (var cb in m_CommandBuffers.Values)
  263. {
  264. m_Camera.RemoveCommandBuffer(cb.Key, cb.Value);
  265. cb.Value.Dispose();
  266. }
  267. m_CommandBuffers.Clear();
  268. // Clear components
  269. if (profile != null)
  270. DisableComponents();
  271. m_Components.Clear();
  272. // Factories
  273. m_MaterialFactory.Dispose();
  274. m_RenderTextureFactory.Dispose();
  275. GraphicsUtils.Dispose();
  276. }
  277. public void ResetTemporalEffects()
  278. {
  279. m_Taa.ResetHistory();
  280. m_MotionBlur.ResetHistory();
  281. m_EyeAdaptation.ResetHistory();
  282. }
  283. #region State management
  284. List<PostProcessingComponentBase> m_ComponentsToEnable = new List<PostProcessingComponentBase>();
  285. List<PostProcessingComponentBase> m_ComponentsToDisable = new List<PostProcessingComponentBase>();
  286. void CheckObservers()
  287. {
  288. foreach (var cs in m_ComponentStates)
  289. {
  290. var component = cs.Key;
  291. var state = component.GetModel().enabled;
  292. if (state != cs.Value)
  293. {
  294. if (state) m_ComponentsToEnable.Add(component);
  295. else m_ComponentsToDisable.Add(component);
  296. }
  297. }
  298. for (int i = 0; i < m_ComponentsToDisable.Count; i++)
  299. {
  300. var c = m_ComponentsToDisable[i];
  301. m_ComponentStates[c] = false;
  302. c.OnDisable();
  303. }
  304. for (int i = 0; i < m_ComponentsToEnable.Count; i++)
  305. {
  306. var c = m_ComponentsToEnable[i];
  307. m_ComponentStates[c] = true;
  308. c.OnEnable();
  309. }
  310. m_ComponentsToDisable.Clear();
  311. m_ComponentsToEnable.Clear();
  312. }
  313. void DisableComponents()
  314. {
  315. foreach (var component in m_Components)
  316. {
  317. var model = component.GetModel();
  318. if (model != null && model.enabled)
  319. component.OnDisable();
  320. }
  321. }
  322. #endregion
  323. #region Command buffer handling & rendering helpers
  324. // Placeholders before the upcoming Scriptable Render Loop as command buffers will be
  325. // executed on the go so we won't need of all that stuff
  326. CommandBuffer AddCommandBuffer<T>(CameraEvent evt, string name)
  327. where T : PostProcessingModel
  328. {
  329. var cb = new CommandBuffer { name = name };
  330. var kvp = new KeyValuePair<CameraEvent, CommandBuffer>(evt, cb);
  331. m_CommandBuffers.Add(typeof(T), kvp);
  332. m_Camera.AddCommandBuffer(evt, kvp.Value);
  333. return kvp.Value;
  334. }
  335. void RemoveCommandBuffer<T>()
  336. where T : PostProcessingModel
  337. {
  338. KeyValuePair<CameraEvent, CommandBuffer> kvp;
  339. var type = typeof(T);
  340. if (!m_CommandBuffers.TryGetValue(type, out kvp))
  341. return;
  342. m_Camera.RemoveCommandBuffer(kvp.Key, kvp.Value);
  343. m_CommandBuffers.Remove(type);
  344. kvp.Value.Dispose();
  345. }
  346. CommandBuffer GetCommandBuffer<T>(CameraEvent evt, string name)
  347. where T : PostProcessingModel
  348. {
  349. CommandBuffer cb;
  350. KeyValuePair<CameraEvent, CommandBuffer> kvp;
  351. if (!m_CommandBuffers.TryGetValue(typeof(T), out kvp))
  352. {
  353. cb = AddCommandBuffer<T>(evt, name);
  354. }
  355. else if (kvp.Key != evt)
  356. {
  357. RemoveCommandBuffer<T>();
  358. cb = AddCommandBuffer<T>(evt, name);
  359. }
  360. else cb = kvp.Value;
  361. return cb;
  362. }
  363. void TryExecuteCommandBuffer<T>(PostProcessingComponentCommandBuffer<T> component)
  364. where T : PostProcessingModel
  365. {
  366. if (component.active)
  367. {
  368. var cb = GetCommandBuffer<T>(component.GetCameraEvent(), component.GetName());
  369. cb.Clear();
  370. component.PopulateCommandBuffer(cb);
  371. }
  372. else RemoveCommandBuffer<T>();
  373. }
  374. bool TryPrepareUberImageEffect<T>(PostProcessingComponentRenderTexture<T> component, Material material)
  375. where T : PostProcessingModel
  376. {
  377. if (!component.active)
  378. return false;
  379. component.Prepare(material);
  380. return true;
  381. }
  382. T AddComponent<T>(T component)
  383. where T : PostProcessingComponentBase
  384. {
  385. m_Components.Add(component);
  386. return component;
  387. }
  388. #endregion
  389. }
  390. }