Add water system package

This commit is contained in:
Vova
2023-12-06 20:29:45 +02:00
parent 627a90012a
commit 58d0f79bd1
140 changed files with 33167 additions and 3 deletions
@@ -0,0 +1,291 @@
using System;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Serialization;
using Unity.Mathematics;
namespace UnityEngine.Rendering.Universal
{
[ExecuteAlways]
public class PlanarReflections : MonoBehaviour
{
[Serializable]
public enum ResolutionMulltiplier
{
Full,
Half,
Third,
Quarter
}
[Serializable]
public class PlanarReflectionSettings
{
public ResolutionMulltiplier m_ResolutionMultiplier = ResolutionMulltiplier.Third;
public float m_ClipPlaneOffset = 0.07f;
public LayerMask m_ReflectLayers = -1;
public bool m_Shadows;
}
[SerializeField]
public PlanarReflectionSettings m_settings = new PlanarReflectionSettings();
public GameObject target;
[FormerlySerializedAs("camOffset")] public float m_planeOffset;
private static Camera _reflectionCamera;
private RenderTexture _reflectionTexture;
private readonly int _planarReflectionTextureId = Shader.PropertyToID("_PlanarReflectionTexture");
private int2 _oldReflectionTextureSize;
public static event Action<ScriptableRenderContext, Camera> BeginPlanarReflections;
private void OnEnable()
{
RenderPipelineManager.beginCameraRendering += ExecutePlanarReflections;
}
// Cleanup all the objects we possibly have created
private void OnDisable()
{
Cleanup();
}
private void OnDestroy()
{
Cleanup();
}
private void Cleanup()
{
RenderPipelineManager.beginCameraRendering -= ExecutePlanarReflections;
if(_reflectionCamera)
{
_reflectionCamera.targetTexture = null;
SafeDestroy(_reflectionCamera.gameObject);
}
if (_reflectionTexture)
{
RenderTexture.ReleaseTemporary(_reflectionTexture);
}
}
private static void SafeDestroy(Object obj)
{
if (Application.isEditor)
{
DestroyImmediate(obj);
}
else
{
Destroy(obj);
}
}
private void UpdateCamera(Camera src, Camera dest)
{
if (dest == null) return;
dest.CopyFrom(src);
dest.useOcclusionCulling = false;
if (dest.gameObject.TryGetComponent(out UniversalAdditionalCameraData camData))
{
camData.renderShadows = m_settings.m_Shadows; // turn off shadows for the reflection camera
}
}
private void UpdateReflectionCamera(Camera realCamera)
{
if (_reflectionCamera == null)
_reflectionCamera = CreateMirrorObjects();
// find out the reflection plane: position and normal in world space
Vector3 pos = Vector3.zero;
Vector3 normal = Vector3.up;
if (target != null)
{
pos = target.transform.position + Vector3.up * m_planeOffset;
normal = target.transform.up;
}
UpdateCamera(realCamera, _reflectionCamera);
// Render reflection
// Reflect camera around reflection plane
var d = -Vector3.Dot(normal, pos) - m_settings.m_ClipPlaneOffset;
var reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);
var reflection = Matrix4x4.identity;
reflection *= Matrix4x4.Scale(new Vector3(1, -1, 1));
CalculateReflectionMatrix(ref reflection, reflectionPlane);
var oldPosition = realCamera.transform.position - new Vector3(0, pos.y * 2, 0);
var newPosition = ReflectPosition(oldPosition);
_reflectionCamera.transform.forward = Vector3.Scale(realCamera.transform.forward, new Vector3(1, -1, 1));
_reflectionCamera.worldToCameraMatrix = realCamera.worldToCameraMatrix * reflection;
// Setup oblique projection matrix so that near plane is our reflection
// plane. This way we clip everything below/above it for free.
var clipPlane = CameraSpacePlane(_reflectionCamera, pos - Vector3.up * 0.1f, normal, 1.0f);
var projection = realCamera.CalculateObliqueMatrix(clipPlane);
_reflectionCamera.projectionMatrix = projection;
_reflectionCamera.cullingMask = m_settings.m_ReflectLayers; // never render water layer
_reflectionCamera.transform.position = newPosition;
}
// Calculates reflection matrix around the given plane
private static void CalculateReflectionMatrix(ref Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1F - 2F * plane[0] * plane[0]);
reflectionMat.m01 = (-2F * plane[0] * plane[1]);
reflectionMat.m02 = (-2F * plane[0] * plane[2]);
reflectionMat.m03 = (-2F * plane[3] * plane[0]);
reflectionMat.m10 = (-2F * plane[1] * plane[0]);
reflectionMat.m11 = (1F - 2F * plane[1] * plane[1]);
reflectionMat.m12 = (-2F * plane[1] * plane[2]);
reflectionMat.m13 = (-2F * plane[3] * plane[1]);
reflectionMat.m20 = (-2F * plane[2] * plane[0]);
reflectionMat.m21 = (-2F * plane[2] * plane[1]);
reflectionMat.m22 = (1F - 2F * plane[2] * plane[2]);
reflectionMat.m23 = (-2F * plane[3] * plane[2]);
reflectionMat.m30 = 0F;
reflectionMat.m31 = 0F;
reflectionMat.m32 = 0F;
reflectionMat.m33 = 1F;
}
private static Vector3 ReflectPosition(Vector3 pos)
{
var newPos = new Vector3(pos.x, -pos.y, pos.z);
return newPos;
}
private float GetScaleValue()
{
switch(m_settings.m_ResolutionMultiplier)
{
case ResolutionMulltiplier.Full:
return 1f;
case ResolutionMulltiplier.Half:
return 0.5f;
case ResolutionMulltiplier.Third:
return 0.33f;
case ResolutionMulltiplier.Quarter:
return 0.25f;
default:
return 0.5f; // default to half res
}
}
// Compare two int2
private static bool Int2Compare(int2 a, int2 b)
{
return a.x == b.x && a.y == b.y;
}
// Given position/normal of the plane, calculates plane in camera space.
private Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
var offsetPos = pos + normal * m_settings.m_ClipPlaneOffset;
var m = cam.worldToCameraMatrix;
var cameraPosition = m.MultiplyPoint(offsetPos);
var cameraNormal = m.MultiplyVector(normal).normalized * sideSign;
return new Vector4(cameraNormal.x, cameraNormal.y, cameraNormal.z, -Vector3.Dot(cameraPosition, cameraNormal));
}
private Camera CreateMirrorObjects()
{
var go = new GameObject("Planar Reflections",typeof(Camera));
var cameraData = go.AddComponent(typeof(UniversalAdditionalCameraData)) as UniversalAdditionalCameraData;
cameraData.requiresColorOption = CameraOverrideOption.Off;
cameraData.requiresDepthOption = CameraOverrideOption.Off;
cameraData.SetRenderer(1);
var t = transform;
var reflectionCamera = go.GetComponent<Camera>();
reflectionCamera.transform.SetPositionAndRotation(t.position, t.rotation);
reflectionCamera.depth = -10;
reflectionCamera.enabled = false;
go.hideFlags = HideFlags.HideAndDontSave;
return reflectionCamera;
}
private void PlanarReflectionTexture(Camera cam)
{
if (_reflectionTexture == null)
{
var res = ReflectionResolution(cam, UniversalRenderPipeline.asset.renderScale);
bool useHdr10 = RenderingUtils.SupportsRenderTextureFormat(RenderTextureFormat.RGB111110Float);
RenderTextureFormat hdrFormat = useHdr10 ? RenderTextureFormat.RGB111110Float : RenderTextureFormat.DefaultHDR;
_reflectionTexture = RenderTexture.GetTemporary(res.x, res.y, 16,
GraphicsFormatUtility.GetGraphicsFormat(hdrFormat, true));
}
_reflectionCamera.targetTexture = _reflectionTexture;
}
private int2 ReflectionResolution(Camera cam, float scale)
{
var x = (int)(cam.pixelWidth * scale * GetScaleValue());
var y = (int)(cam.pixelHeight * scale * GetScaleValue());
return new int2(x, y);
}
private void ExecutePlanarReflections(ScriptableRenderContext context, Camera camera)
{
// we dont want to render planar reflections in reflections or previews
if (camera.cameraType == CameraType.Reflection || camera.cameraType == CameraType.Preview)
return;
UpdateReflectionCamera(camera); // create reflected camera
PlanarReflectionTexture(camera); // create and assign RenderTexture
var data = new PlanarReflectionSettingData(); // save quality settings and lower them for the planar reflections
data.Set(); // set quality settings
Shader.EnableKeyword("_PLANAR_REFLECTION_CAMERA");
BeginPlanarReflections?.Invoke(context, _reflectionCamera); // callback Action for PlanarReflection
UniversalRenderPipeline.RenderSingleCamera(context, _reflectionCamera); // render planar reflections
data.Restore(); // restore the quality settings
Shader.SetGlobalTexture(_planarReflectionTextureId, _reflectionTexture); // Assign texture to water shader
Shader.DisableKeyword("_PLANAR_REFLECTION_CAMERA");
}
class PlanarReflectionSettingData
{
private readonly bool _fog;
private readonly int _maxLod;
private readonly float _lodBias;
public PlanarReflectionSettingData()
{
_fog = RenderSettings.fog;
_maxLod = QualitySettings.maximumLODLevel;
_lodBias = QualitySettings.lodBias;
}
public void Set()
{
GL.invertCulling = true;
RenderSettings.fog = false; // disable fog for now as it's incorrect with projection
QualitySettings.maximumLODLevel = 1;
QualitySettings.lodBias = _lodBias * 0.5f;
}
public void Restore()
{
GL.invertCulling = false;
RenderSettings.fog = _fog;
QualitySettings.maximumLODLevel = _maxLod;
QualitySettings.lodBias = _lodBias;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3971d89a730cd5846a1944ab0228bf76
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,234 @@
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace WaterSystem
{
public class WaterSystemFeature : ScriptableRendererFeature
{
#region Water Effects Pass
class WaterFxPass : ScriptableRenderPass
{
private const string k_RenderWaterFXTag = "Render Water FX";
private ProfilingSampler m_WaterFX_Profile = new ProfilingSampler(k_RenderWaterFXTag);
private readonly ShaderTagId m_WaterFXShaderTag = new ShaderTagId("WaterFX");
private readonly Color m_ClearColor = new Color(0.0f, 0.5f, 0.5f, 0.5f); //r = foam mask, g = normal.x, b = normal.z, a = displacement
private FilteringSettings m_FilteringSettings;
private RTHandle m_WaterFX;
public WaterFxPass()
{
m_WaterFX=RTHandles.Alloc("_WaterFXMap", "_WaterFXMap");
// only wanting to render transparent objects
m_FilteringSettings = new FilteringSettings(RenderQueueRange.transparent);
}
// Calling Configure since we are wanting to render into a RenderTexture and control cleat
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
// no need for a depth buffer
cameraTextureDescriptor.depthBufferBits = 0;
// Half resolution
cameraTextureDescriptor.width /= 2;
cameraTextureDescriptor.height /= 2;
// default format TODO research usefulness of HDR format
cameraTextureDescriptor.colorFormat = RenderTextureFormat.Default;
// get a temp RT for rendering into
cmd.GetTemporaryRT(Shader.PropertyToID(m_WaterFX.name), cameraTextureDescriptor, FilterMode.Bilinear);
ConfigureTarget(m_WaterFX);
// clear the screen with a specific color for the packed data
ConfigureClear(ClearFlag.Color, m_ClearColor);
}
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
CommandBuffer cmd = CommandBufferPool.Get();
using (new ProfilingScope(cmd, m_WaterFX_Profile)) // makes sure we have profiling ability
{
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
// here we choose renderers based off the "WaterFX" shader pass and also sort back to front
var drawSettings = CreateDrawingSettings(m_WaterFXShaderTag, ref renderingData,
SortingCriteria.CommonTransparent);
// draw all the renderers matching the rules we setup
context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref m_FilteringSettings);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
public override void OnCameraCleanup(CommandBuffer cmd)
{
// since the texture is used within the single cameras use we need to cleanup the RT afterwards
cmd.ReleaseTemporaryRT(Shader.PropertyToID(m_WaterFX.name));
}
}
#endregion
#region Caustics Pass
class WaterCausticsPass : ScriptableRenderPass
{
private const string k_RenderWaterCausticsTag = "Render Water Caustics";
private ProfilingSampler m_WaterCaustics_Profile = new ProfilingSampler(k_RenderWaterCausticsTag);
public Material WaterCausticMaterial;
private static Mesh m_mesh;
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
var cam = renderingData.cameraData.camera;
// Stop the pass rendering in the preview or material missing
if (cam.cameraType == CameraType.Preview || !WaterCausticMaterial)
return;
CommandBuffer cmd = CommandBufferPool.Get();
using (new ProfilingScope(cmd, m_WaterCaustics_Profile))
{
var sunMatrix = RenderSettings.sun != null
? RenderSettings.sun.transform.localToWorldMatrix
: Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-45f, 45f, 0f), Vector3.one);
WaterCausticMaterial.SetMatrix("_MainLightDir", sunMatrix);
// Create mesh if needed
if (!m_mesh)
m_mesh = GenerateCausticsMesh(1000f);
// Create the matrix to position the caustics mesh.
var position = cam.transform.position;
position.y = 0; // TODO should read a global 'water height' variable.
var matrix = Matrix4x4.TRS(position, Quaternion.identity, Vector3.one);
// Setup the CommandBuffer and draw the mesh with the caustic material and matrix
cmd.DrawMesh(m_mesh, matrix, WaterCausticMaterial, 0, 0);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
}
#endregion
WaterFxPass m_WaterFxPass;
WaterCausticsPass m_CausticsPass;
public WaterSystemSettings settings = new WaterSystemSettings();
[HideInInspector][SerializeField] private Shader causticShader;
[HideInInspector][SerializeField] private Texture2D causticTexture;
private Material _causticMaterial;
private static readonly int SrcBlend = Shader.PropertyToID("_SrcBlend");
private static readonly int DstBlend = Shader.PropertyToID("_DstBlend");
private static readonly int Size = Shader.PropertyToID("_Size");
private static readonly int CausticTexture = Shader.PropertyToID("_CausticMap");
public override void Create()
{
// WaterFX Pass
m_WaterFxPass = new WaterFxPass {renderPassEvent = RenderPassEvent.BeforeRenderingOpaques};
// Caustic Pass
m_CausticsPass = new WaterCausticsPass();
causticShader = causticShader ? causticShader : Shader.Find("Hidden/BoatAttack/Caustics");
if (causticShader == null) return;
if (_causticMaterial)
{
DestroyImmediate(_causticMaterial);
}
_causticMaterial = CoreUtils.CreateEngineMaterial(causticShader);
_causticMaterial.SetFloat("_BlendDistance", settings.causticBlendDistance);
if (causticTexture == null)
{
Debug.Log("Caustics Texture missing, attempting to load.");
#if UNITY_EDITOR
causticTexture = UnityEditor.AssetDatabase.LoadAssetAtPath<Texture2D>("Packages/com.verasl.water-system/Textures/WaterSurface_single.tif");
#endif
}
_causticMaterial.SetTexture(CausticTexture, causticTexture);
switch (settings.debug)
{
case WaterSystemSettings.DebugMode.Caustics:
_causticMaterial.SetFloat(SrcBlend, 1f);
_causticMaterial.SetFloat(DstBlend, 0f);
_causticMaterial.EnableKeyword("_DEBUG");
m_CausticsPass.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing;
break;
case WaterSystemSettings.DebugMode.WaterEffects:
break;
case WaterSystemSettings.DebugMode.Disabled:
// Caustics
_causticMaterial.SetFloat(SrcBlend, 2f);
_causticMaterial.SetFloat(DstBlend, 0f);
_causticMaterial.DisableKeyword("_DEBUG");
m_CausticsPass.renderPassEvent = RenderPassEvent.AfterRenderingSkybox + 1;
// WaterEffects
break;
}
_causticMaterial.SetFloat(Size, settings.causticScale);
m_CausticsPass.WaterCausticMaterial = _causticMaterial;
}
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
renderer.EnqueuePass(m_WaterFxPass);
renderer.EnqueuePass(m_CausticsPass);
}
/// <summary>
/// This function Generates a flat quad for use with the caustics pass.
/// </summary>
/// <param name="size">The length of the quad.</param>
/// <returns></returns>
private static Mesh GenerateCausticsMesh(float size)
{
var m = new Mesh();
size *= 0.5f;
var verts = new[]
{
new Vector3(-size, 0f, -size),
new Vector3(size, 0f, -size),
new Vector3(-size, 0f, size),
new Vector3(size, 0f, size)
};
m.vertices = verts;
var tris = new[]
{
0, 2, 1,
2, 3, 1
};
m.triangles = tris;
return m;
}
[System.Serializable]
public class WaterSystemSettings
{
[Header("Caustics Settings")] [Range(0.1f, 1f)]
public float causticScale = 0.25f;
public float causticBlendDistance = 3f;
[Header("Advanced Settings")] public DebugMode debug = DebugMode.Disabled;
public enum DebugMode
{
Disabled,
WaterEffects,
Caustics
}
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: adbe377f4f72c497faee64bc3f0580b9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- causticShader: {fileID: 4800000, guid: 90939d2e4b62841d29c136c866715501, type: 3}
- causticTexture: {fileID: 2800000, guid: f395b7d64f44848c6a3cba1f1173fe90, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: