123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476 |
- // Copyright (C) 2019-2021 Alexander Bogarsukov. All rights reserved.
- // See the LICENSE.md file in the project root for more information.
- using System;
- using System.Collections.Generic;
- using System.Runtime.CompilerServices;
- using UnityEngine;
- using UnityEngine.Rendering;
- using UnityEngine.XR;
- namespace UnityFx.Outline
- {
- /// <summary>
- /// Helper class for outline rendering with <see cref="CommandBuffer"/>.
- /// </summary>
- /// <remarks>
- /// <para>The class can be used on its own or as part of a higher level systems. It is used
- /// by higher level outline implementations (<see cref="OutlineEffect"/> and
- /// <see cref="OutlineBehaviour"/>). It is fully compatible with Unity post processing stack as well.</para>
- /// <para>The class implements <see cref="IDisposable"/> to be used inside <see langword="using"/>
- /// block as shown in the code samples. Disposing <see cref="OutlineRenderer"/> does not dispose
- /// the corresponding <see cref="CommandBuffer"/>.</para>
- /// <para>Command buffer is not cleared before rendering. It is user responsibility to do so if needed.</para>
- /// </remarks>
- /// <example>
- /// var commandBuffer = new CommandBuffer();
- ///
- /// using (var renderer = new OutlineRenderer(commandBuffer, resources))
- /// {
- /// renderer.Render(renderers, settings);
- /// }
- ///
- /// camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, commandBuffer);
- /// </example>
- /// <seealso cref="OutlineResources"/>
- public readonly struct OutlineRenderer : IDisposable
- {
- #region data
- private readonly TextureDimension _rtDimention;
- private readonly RenderTargetIdentifier _rt;
- private readonly RenderTargetIdentifier _depth;
- private readonly CommandBuffer _commandBuffer;
- private readonly OutlineResources _resources;
- #endregion
- #region interface
- /// <summary>
- /// A default <see cref="CameraEvent"/> outline rendering should be assosiated with.
- /// </summary>
- public const CameraEvent RenderEvent = CameraEvent.AfterSkybox;
- /// <summary>
- /// A default render texture format for the outline effect.
- /// </summary>
- public const RenderTextureFormat RtFormat = RenderTextureFormat.R8;
- /// <summary>
- /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
- /// </summary>
- /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
- /// <param name="resources">Outline resources.</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
- public OutlineRenderer(CommandBuffer cmd, OutlineResources resources)
- : this(cmd, resources, BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.Depth, Vector2Int.zero)
- {
- }
- /// <summary>
- /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
- /// </summary>
- /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
- /// <param name="resources">Outline resources.</param>
- /// <param name="renderingPath">The rendering path of target camera (<see cref="Camera.actualRenderingPath"/>).</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
- public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderingPath renderingPath)
- : this(cmd, resources, BuiltinRenderTextureType.CameraTarget, GetBuiltinDepth(renderingPath), Vector2Int.zero)
- {
- }
- /// <summary>
- /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
- /// </summary>
- /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
- /// <param name="resources">Outline resources.</param>
- /// <param name="dst">Render target.</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
- public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderTargetIdentifier dst)
- : this(cmd, resources, dst, BuiltinRenderTextureType.Depth, Vector2Int.zero)
- {
- }
- /// <summary>
- /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
- /// </summary>
- /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
- /// <param name="dst">Render target.</param>
- /// <param name="renderingPath">The rendering path of target camera (<see cref="Camera.actualRenderingPath"/>).</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
- public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderTargetIdentifier dst, RenderingPath renderingPath, Vector2Int rtSize)
- : this(cmd, resources, dst, GetBuiltinDepth(renderingPath), rtSize)
- {
- }
- /// <summary>
- /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
- /// </summary>
- /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
- /// <param name="resources">Outline resources.</param>
- /// <param name="dst">Render target.</param>
- /// <param name="depth">Depth dexture to use.</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
- public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderTargetIdentifier dst, RenderTargetIdentifier depth, Vector2Int rtSize)
- {
- if (cmd is null)
- {
- throw new ArgumentNullException(nameof(cmd));
- }
- if (resources is null)
- {
- throw new ArgumentNullException(nameof(resources));
- }
- if (rtSize.x <= 0)
- {
- rtSize.x = -1;
- }
- if (rtSize.y <= 0)
- {
- rtSize.y = -1;
- }
- if (XRSettings.enabled)
- {
- var rtDesc = XRSettings.eyeTextureDesc;
- rtDesc.shadowSamplingMode = ShadowSamplingMode.None;
- rtDesc.depthBufferBits = 0;
- rtDesc.colorFormat = RtFormat;
- cmd.GetTemporaryRT(resources.MaskTexId, rtDesc, FilterMode.Bilinear);
- cmd.GetTemporaryRT(resources.TempTexId, rtDesc, FilterMode.Bilinear);
- _rtDimention = rtDesc.dimension;
- }
- else
- {
- cmd.GetTemporaryRT(resources.MaskTexId, rtSize.x, rtSize.y, 0, FilterMode.Bilinear, RtFormat);
- cmd.GetTemporaryRT(resources.TempTexId, rtSize.x, rtSize.y, 0, FilterMode.Bilinear, RtFormat);
- _rtDimention = TextureDimension.Tex2D;
- }
- _rt = dst;
- _depth = depth;
- _commandBuffer = cmd;
- _resources = resources;
- }
- /// <summary>
- /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
- /// </summary>
- /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
- /// <param name="resources">Outline resources.</param>
- /// <param name="dst">Render target.</param>
- /// <param name="depth">Depth dexture to use.</param>
- /// <param name="rtDesc">Render texture decsriptor.</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
- public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderTargetIdentifier dst, RenderTargetIdentifier depth, RenderTextureDescriptor rtDesc)
- {
- if (cmd is null)
- {
- throw new ArgumentNullException(nameof(cmd));
- }
- if (resources is null)
- {
- throw new ArgumentNullException(nameof(resources));
- }
- if (rtDesc.width <= 0)
- {
- rtDesc.width = -1;
- }
- if (rtDesc.height <= 0)
- {
- rtDesc.height = -1;
- }
- if (rtDesc.dimension == TextureDimension.None || rtDesc.dimension == TextureDimension.Unknown)
- {
- rtDesc.dimension = TextureDimension.Tex2D;
- }
- rtDesc.shadowSamplingMode = ShadowSamplingMode.None;
- rtDesc.depthBufferBits = 0;
- rtDesc.colorFormat = RtFormat;
- rtDesc.msaaSamples = 1;
- cmd.GetTemporaryRT(resources.MaskTexId, rtDesc, FilterMode.Bilinear);
- cmd.GetTemporaryRT(resources.TempTexId, rtDesc, FilterMode.Bilinear);
- _rtDimention = rtDesc.dimension;
- _rt = dst;
- _depth = depth;
- _commandBuffer = cmd;
- _resources = resources;
- }
- /// <summary>
- /// Renders outline around a single object.
- /// </summary>
- /// <param name="obj">An object to be outlined.</param>
- /// <seealso cref="Render(IReadOnlyList{OutlineRenderObject})"/>
- public void Render(OutlineRenderObject obj)
- {
- Render(obj.Renderers, obj.OutlineSettings, obj.Tag);
- }
- /// <summary>
- /// Renders outline around multiple <paramref name="objects"/>.
- /// </summary>
- /// <param name="objects">An object to be outlined.</param>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="objects"/> is <see langword="null"/>.</exception>
- /// <seealso cref="Render(OutlineRenderObject)"/>
- public void Render(IReadOnlyList<OutlineRenderObject> objects)
- {
- if (objects is null)
- {
- throw new ArgumentNullException(nameof(objects));
- }
- for (var i = 0; i < objects.Count; i++)
- {
- Render(objects[i]);
- }
- }
- /// <summary>
- /// Renders outline around multiple <paramref name="renderers"/>.
- /// </summary>
- /// <param name="renderers">One or more renderers representing a single object to be outlined.</param>
- /// <param name="settings">Outline settings.</param>
- /// <param name="sampleName">Optional name of the sample (visible in profiler).</param>
- /// <exception cref="ArgumentNullException">Thrown if any of the arguments is <see langword="null"/>.</exception>
- /// <seealso cref="Render(Renderer, IOutlineSettings, string)"/>
- public void Render(IReadOnlyList<Renderer> renderers, IOutlineSettings settings, string sampleName = null)
- {
- if (renderers is null)
- {
- throw new ArgumentNullException(nameof(renderers));
- }
- if (settings is null)
- {
- throw new ArgumentNullException(nameof(settings));
- }
- if (renderers.Count > 0)
- {
- // NOTE: Remove BeginSample/EndSample for now (https://github.com/Arvtesh/UnityFx.Outline/issues/44).
- //if (string.IsNullOrEmpty(sampleName))
- //{
- // sampleName = renderers[0].name;
- //}
- //_commandBuffer.BeginSample(sampleName);
- {
- RenderObjectClear(settings.OutlineRenderMode);
- for (var i = 0; i < renderers.Count; ++i)
- {
- DrawRenderer(renderers[i], settings);
- }
- RenderOutline(settings);
- }
- //_commandBuffer.EndSample(sampleName);
- }
- }
- /// <summary>
- /// Renders outline around a single <paramref name="renderer"/>.
- /// </summary>
- /// <param name="renderer">A <see cref="Renderer"/> representing an object to be outlined.</param>
- /// <param name="settings">Outline settings.</param>
- /// <param name="sampleName">Optional name of the sample (visible in profiler).</param>
- /// <exception cref="ArgumentNullException">Thrown if any of the arguments is <see langword="null"/>.</exception>
- /// <seealso cref="Render(IReadOnlyList{Renderer}, IOutlineSettings, string)"/>
- public void Render(Renderer renderer, IOutlineSettings settings, string sampleName = null)
- {
- if (renderer is null)
- {
- throw new ArgumentNullException(nameof(renderer));
- }
- if (settings is null)
- {
- throw new ArgumentNullException(nameof(settings));
- }
- // NOTE: Remove BeginSample/EndSample for now (https://github.com/Arvtesh/UnityFx.Outline/issues/44).
- //if (string.IsNullOrEmpty(sampleName))
- //{
- // sampleName = renderer.name;
- //}
- // NOTE: Remove this for now (https://github.com/Arvtesh/UnityFx.Outline/issues/44).
- //_commandBuffer.BeginSample(sampleName);
- {
- RenderObjectClear(settings.OutlineRenderMode);
- DrawRenderer(renderer, settings);
- RenderOutline(settings);
- }
- //_commandBuffer.EndSample(sampleName);
- }
- /// <summary>
- /// Specialized render target setup. Do not use if not sure.
- /// </summary>
- public void RenderObjectClear(OutlineRenderFlags flags)
- {
- // NOTE: Use the camera depth buffer when rendering the mask. Shader only reads from the depth buffer (ZWrite Off).
- if ((flags & OutlineRenderFlags.EnableDepthTesting) != 0)
- {
- if (_rtDimention == TextureDimension.Tex2DArray)
- {
- // NOTE: Need to use this SetRenderTarget overload for XR, otherwise single pass instanced rendering does not function properly.
- _commandBuffer.SetRenderTarget(_resources.MaskTex, _depth, 0, CubemapFace.Unknown, -1);
- }
- else
- {
- _commandBuffer.SetRenderTarget(_resources.MaskTex, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, _depth, RenderBufferLoadAction.Load, RenderBufferStoreAction.DontCare);
- }
- }
- else
- {
- if (_rtDimention == TextureDimension.Tex2DArray)
- {
- _commandBuffer.SetRenderTarget(_resources.MaskTex, 0, CubemapFace.Unknown, -1);
- }
- else
- {
- _commandBuffer.SetRenderTarget(_resources.MaskTex, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
- }
- }
- _commandBuffer.ClearRenderTarget(false, true, Color.clear);
- }
- /// <summary>
- /// Renders outline. Do not use if not sure.
- /// </summary>
- public void RenderOutline(IOutlineSettings settings)
- {
- var mat = _resources.OutlineMaterial;
- var props = _resources.GetProperties(settings);
- _commandBuffer.SetGlobalFloatArray(_resources.GaussSamplesId, _resources.GetGaussSamples(settings.OutlineWidth));
- if (_rtDimention == TextureDimension.Tex2DArray)
- {
- // HPass
- _commandBuffer.SetRenderTarget(_resources.TempTex, 0, CubemapFace.Unknown, -1);
- Blit(_resources.MaskTex, OutlineResources.OutlineShaderHPassId, mat, props);
- // VPassBlend
- _commandBuffer.SetRenderTarget(_rt, 0, CubemapFace.Unknown, -1);
- Blit(_resources.TempTex, OutlineResources.OutlineShaderVPassId, mat, props);
- }
- else
- {
- // HPass
- _commandBuffer.SetRenderTarget(_resources.TempTex, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
- Blit(_resources.MaskTex, OutlineResources.OutlineShaderHPassId, mat, props);
- // VPassBlend
- _commandBuffer.SetRenderTarget(_rt, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
- Blit(_resources.TempTex, OutlineResources.OutlineShaderVPassId, mat, props);
- }
- }
- #endregion
- #region IDisposable
- /// <summary>
- /// Finalizes the effect rendering and releases temporary textures used. Should only be called once.
- /// </summary>
- public void Dispose()
- {
- _commandBuffer.ReleaseTemporaryRT(_resources.TempTexId);
- _commandBuffer.ReleaseTemporaryRT(_resources.MaskTexId);
- }
- #endregion
- #region implementation
- private void DrawRenderer(Renderer renderer, IOutlineSettings settings)
- {
- if (renderer && renderer.enabled && renderer.isVisible && renderer.gameObject.activeInHierarchy)
- {
- // NOTE: Accessing Renderer.sharedMaterials triggers GC.Alloc. That's why we use a temporary
- // list of materials, cached with the outline resources.
- renderer.GetSharedMaterials(_resources.TmpMaterials);
- if (_resources.TmpMaterials.Count > 0)
- {
- if (settings.IsAlphaTestingEnabled())
- {
- for (var i = 0; i < _resources.TmpMaterials.Count; ++i)
- {
- var mat = _resources.TmpMaterials[i];
- // Use material cutoff value if available.
- if (mat.HasProperty(_resources.AlphaCutoffId))
- {
- _commandBuffer.SetGlobalFloat(_resources.AlphaCutoffId, mat.GetFloat(_resources.AlphaCutoffId));
- }
- else
- {
- _commandBuffer.SetGlobalFloat(_resources.AlphaCutoffId, settings.OutlineAlphaCutoff);
- }
- _commandBuffer.SetGlobalTexture(_resources.MainTexId, _resources.TmpMaterials[i].mainTexture);
- _commandBuffer.DrawRenderer(renderer, _resources.RenderMaterial, i, OutlineResources.RenderShaderAlphaTestPassId);
- }
- }
- else
- {
- for (var i = 0; i < _resources.TmpMaterials.Count; ++i)
- {
- _commandBuffer.DrawRenderer(renderer, _resources.RenderMaterial, i, OutlineResources.RenderShaderDefaultPassId);
- }
- }
- }
- else
- {
- // NOTE: No materials set for renderer means we should still render outline for it.
- _commandBuffer.DrawRenderer(renderer, _resources.RenderMaterial, 0, OutlineResources.RenderShaderDefaultPassId);
- }
- }
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void Blit(RenderTargetIdentifier src, int shaderPass, Material mat, MaterialPropertyBlock props)
- {
- // Set source texture as _MainTex to match Blit behavior.
- _commandBuffer.SetGlobalTexture(_resources.MainTexId, src);
- // NOTE: SystemInfo.graphicsShaderLevel check is not enough sometimes (esp. on mobiles), so there is SystemInfo.supportsInstancing
- // check and a flag for forcing DrawMesh.
- if (SystemInfo.graphicsShaderLevel >= 35 && SystemInfo.supportsInstancing && !_resources.UseFullscreenTriangleMesh)
- {
- _commandBuffer.DrawProcedural(Matrix4x4.identity, mat, shaderPass, MeshTopology.Triangles, 3, 1, props);
- }
- else
- {
- _commandBuffer.DrawMesh(_resources.FullscreenTriangleMesh, Matrix4x4.identity, mat, 0, shaderPass, props);
- }
- }
- private static RenderTargetIdentifier GetBuiltinDepth(RenderingPath renderingPath)
- {
- return (renderingPath == RenderingPath.DeferredShading || renderingPath == RenderingPath.DeferredLighting) ? BuiltinRenderTextureType.ResolvedDepth : BuiltinRenderTextureType.Depth;
- }
- #endregion
- }
- }
|