Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Mirror solution in URP

Discussion in 'Universal Render Pipeline' started by ErnestSurys, Sep 30, 2019.

  1. ErnestSurys

    ErnestSurys

    Joined:
    Jan 18, 2018
    Posts:
    82
    Hello,

    I need a mirror solution for my archviz project, since Box Projection of Reflection Probes is not yet supported in URP I started to look for some custom scripts.
    One that I found works in the editor but due to `Camera.Render()` call it gives "Recursive rendering is not supported in SRP (are you calling Camera.Render from within a render pipeline?)." Error.

    I suspect that `ScriptableRendererFeature` may allow this script to work but I have no idea how it could be refactored.

    I ask for help with achieving realistic mirror effect, possibly without spending any money.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using Varunit.Utility;
    4.  
    5. // This is in fact just the Water script from Pro Standard Assets,
    6. // just with refraction stuff removed.
    7. [ExecuteInEditMode] // Make mirror live-update even when not in play mode
    8. public class MirrorReflection : MonoBehaviour
    9. {
    10.     [SerializeField, Collect]
    11.     private Renderer _renderer;
    12.  
    13.     [SerializeField,TagSelector]
    14.     private string _observerCameraTag;
    15.  
    16.     private Camera _observator;
    17.  
    18.     public bool m_DisablePixelLights = true;
    19.     public int m_TextureSize = 256;
    20.     public float m_ClipPlaneOffset = 0.07f;
    21.  
    22.     public LayerMask m_ReflectLayers = -1;
    23.  
    24.     private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table
    25.  
    26.     private RenderTexture m_ReflectionTexture = null;
    27.     private int m_OldReflectionTextureSize = 0;
    28.  
    29.     private static bool s_InsideRendering = false;
    30.  
    31.     // This is called when it's known that the object will be rendered by some
    32.     // camera. We render reflections and do other updates here.
    33.     // Because the script executes in edit mode, reflections for the scene view
    34.     // camera will just work!
    35.     public void OnWillRenderObject()
    36.     {
    37.         if (!enabled || !_renderer || !_renderer.sharedMaterial || !_renderer.enabled)
    38.             return;
    39.      
    40.         Camera cam = Camera.current;
    41.         if (!cam)
    42.             return;
    43.  
    44.         // Safeguard from recursive reflections.      
    45.         if (s_InsideRendering)
    46.             return;
    47.         s_InsideRendering = true;
    48.  
    49.         Camera reflectionCamera;
    50.         CreateMirrorObjects(cam, out reflectionCamera);
    51.  
    52.         // find out the reflection plane: position and normal in world space
    53.         Vector3 pos = transform.position;
    54.         Vector3 normal = transform.up;
    55.  
    56.         // Optionally disable pixel lights for reflection
    57.         int oldPixelLightCount = QualitySettings.pixelLightCount;
    58.         if (m_DisablePixelLights)
    59.             QualitySettings.pixelLightCount = 0;
    60.  
    61.         UpdateCameraModes(cam, reflectionCamera);
    62.  
    63.         // Render reflection
    64.         // Reflect camera around reflection plane
    65.         float d = -Vector3.Dot(normal, pos) - m_ClipPlaneOffset;
    66.         Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);
    67.  
    68.         Matrix4x4 reflection = Matrix4x4.zero;
    69.         CalculateReflectionMatrix(ref reflection, reflectionPlane);
    70.         Vector3 oldpos = cam.transform.position;
    71.         Vector3 newpos = reflection.MultiplyPoint(oldpos);
    72.         reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
    73.  
    74.         // Setup oblique projection matrix so that near plane is our reflection
    75.         // plane. This way we clip everything below/above it for free.
    76.         Vector4 clipPlane = CameraSpacePlane(reflectionCamera, pos, normal, 1.0f);
    77.         //Matrix4x4 projection = cam.projectionMatrix;
    78.         Matrix4x4 projection = cam.CalculateObliqueMatrix(clipPlane);
    79.         reflectionCamera.projectionMatrix = projection;
    80.  
    81.         reflectionCamera.cullingMask = ~(1 << 4) & m_ReflectLayers.value; // never render water layer
    82.         reflectionCamera.targetTexture = m_ReflectionTexture;
    83.  
    84.         GL.invertCulling = true;
    85.  
    86.         reflectionCamera.transform.position = newpos;
    87.         Vector3 euler = cam.transform.eulerAngles;
    88.         reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
    89.         reflectionCamera.Render();
    90.         reflectionCamera.transform.position = oldpos;
    91.  
    92.         GL.invertCulling = false;
    93.  
    94.         Material[] materials = _renderer.sharedMaterials;
    95.         foreach (Material mat in materials)
    96.         {
    97.             if (mat.HasProperty("_ReflectionTex"))
    98.                 mat.SetTexture("_ReflectionTex", m_ReflectionTexture);
    99.         }
    100.  
    101.         // Restore pixel light count
    102.         if (m_DisablePixelLights)
    103.             QualitySettings.pixelLightCount = oldPixelLightCount;
    104.  
    105.         s_InsideRendering = false;
    106.     }
    107.  
    108.  
    109.     // Cleanup all the objects we possibly have created
    110.     void OnDisable()
    111.     {
    112.         if (m_ReflectionTexture)
    113.         {
    114.             DestroyImmediate(m_ReflectionTexture);
    115.             m_ReflectionTexture = null;
    116.         }
    117.         foreach (DictionaryEntry kvp in m_ReflectionCameras)
    118.             DestroyImmediate(((Camera)kvp.Value).gameObject);
    119.         m_ReflectionCameras.Clear();
    120.     }
    121.  
    122.  
    123.     private void UpdateCameraModes(Camera src, Camera dest)
    124.     {
    125.         if (dest == null)
    126.             return;
    127.         // set camera to clear the same way as current camera
    128.         dest.clearFlags = src.clearFlags;
    129.         dest.backgroundColor = src.backgroundColor;
    130.         if (src.clearFlags == CameraClearFlags.Skybox)
    131.         {
    132.             Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
    133.             Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
    134.             if (!sky || !sky.material)
    135.             {
    136.                 mysky.enabled = false;
    137.             }
    138.             else
    139.             {
    140.                 mysky.enabled = true;
    141.                 mysky.material = sky.material;
    142.             }
    143.         }
    144.         // update other values to match current camera.
    145.         // even if we are supplying custom camera&projection matrices,
    146.         // some of values are used elsewhere (e.g. skybox uses far plane)
    147.         dest.farClipPlane = src.farClipPlane;
    148.         dest.nearClipPlane = src.nearClipPlane;
    149.         dest.orthographic = src.orthographic;
    150.         dest.fieldOfView = src.fieldOfView;
    151.         dest.aspect = src.aspect;
    152.         dest.orthographicSize = src.orthographicSize;
    153.     }
    154.  
    155.     // On-demand create any objects we need
    156.     private void CreateMirrorObjects(Camera currentCamera, out Camera reflectionCamera)
    157.     {
    158.         reflectionCamera = null;
    159.  
    160.         // Reflection render texture
    161.         if (!m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize)
    162.         {
    163.             if (m_ReflectionTexture)
    164.                 DestroyImmediate(m_ReflectionTexture);
    165.             m_ReflectionTexture = new RenderTexture(m_TextureSize, m_TextureSize, 16);
    166.             m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID();
    167.             m_ReflectionTexture.isPowerOfTwo = true;
    168.             m_ReflectionTexture.hideFlags = HideFlags.DontSave;
    169.             m_OldReflectionTextureSize = m_TextureSize;
    170.         }
    171.  
    172.         // Camera for reflection
    173.         reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
    174.         if (!reflectionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
    175.         {
    176.             GameObject go = new GameObject("Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox));
    177.             reflectionCamera = go.GetComponent<Camera>();
    178.             reflectionCamera.enabled = false;
    179.             reflectionCamera.transform.position = transform.position;
    180.             reflectionCamera.transform.rotation = transform.rotation;
    181.             reflectionCamera.gameObject.AddComponent<FlareLayer>();
    182.             reflectionCamera.transform.parent = transform;
    183.             //go.hideFlags = HideFlags.HideAndDontSave;
    184.             m_ReflectionCameras[currentCamera] = reflectionCamera;
    185.         }
    186.     }
    187.  
    188.     // Extended sign: returns -1, 0 or 1 based on sign of a
    189.     private static float sgn(float a)
    190.     {
    191.         if (a > 0.0f) return 1.0f;
    192.         if (a < 0.0f) return -1.0f;
    193.         return 0.0f;
    194.     }
    195.  
    196.     // Given position/normal of the plane, calculates plane in camera space.
    197.     private Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign)
    198.     {
    199.         Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
    200.         Matrix4x4 m = cam.worldToCameraMatrix;
    201.         Vector3 cpos = m.MultiplyPoint(offsetPos);
    202.         Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign;
    203.         return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal));
    204.     }
    205.  
    206.     // Calculates reflection matrix around the given plane
    207.     private static void CalculateReflectionMatrix(ref Matrix4x4 reflectionMat, Vector4 plane)
    208.     {
    209.         reflectionMat.m00 = (1F - 2F * plane[0] * plane[0]);
    210.         reflectionMat.m01 = (-2F * plane[0] * plane[1]);
    211.         reflectionMat.m02 = (-2F * plane[0] * plane[2]);
    212.         reflectionMat.m03 = (-2F * plane[3] * plane[0]);
    213.  
    214.         reflectionMat.m10 = (-2F * plane[1] * plane[0]);
    215.         reflectionMat.m11 = (1F - 2F * plane[1] * plane[1]);
    216.         reflectionMat.m12 = (-2F * plane[1] * plane[2]);
    217.         reflectionMat.m13 = (-2F * plane[3] * plane[1]);
    218.  
    219.         reflectionMat.m20 = (-2F * plane[2] * plane[0]);
    220.         reflectionMat.m21 = (-2F * plane[2] * plane[1]);
    221.         reflectionMat.m22 = (1F - 2F * plane[2] * plane[2]);
    222.         reflectionMat.m23 = (-2F * plane[3] * plane[2]);
    223.  
    224.         reflectionMat.m30 = 0F;
    225.         reflectionMat.m31 = 0F;
    226.         reflectionMat.m32 = 0F;
    227.         reflectionMat.m33 = 1F;
    228.     }
    229. }
     
    Last edited: Sep 30, 2019
  2. themeshpotato

    themeshpotato

    Joined:
    Apr 11, 2018
    Posts:
    55
    @ErnestSurys did you have any luck with fixing this? I'm having the same issue, but everything with the reflection still seems to work.
     
  3. larsbertram1

    larsbertram1

    Joined:
    Oct 7, 2008
    Posts:
    6,848
    i would suggest to have a look into unity's boat attack demo which you can find on github.
     
    themeshpotato likes this.
  4. Shadauwa

    Shadauwa

    Joined:
    Jan 12, 2020
    Posts:
    16
    hi have you found how to make mirror under URP?