1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering;
public class RainWater : MonoBehaviour { private static Mesh m_mesh; public static Mesh fullScreenMesh { get { if(m_mesh != null) { return m_mesh; } m_mesh = new Mesh(); m_mesh.vertices = new Vector3[] { new Vector3(-1,-1,0), new Vector3(-1,1,0), new Vector3(1,1,0), new Vector3(1,-1,0), }; m_mesh.uv = new Vector2[] { new Vector3(0,1), new Vector3(0,0), new Vector3(1,0), new Vector3(1,1), };
m_mesh.SetIndices(new int[] { 0, 1, 2, 3 }, MeshTopology.Quads, 0); return m_mesh; } }
public RenderTexture targetTexture; public ComputeShader shader; public Material mat; public float timeSpeed = 1.25f; private CommandBuffer buffer; private Matrix4x4[] matrix = new Matrix4x4[COUNT]; private Vector2[] times = new Vector2[COUNT]; private Material gausBlurMat; private int kernal; private ComputeBuffer matrixBuffers; private ComputeBuffer timeSliceBuffers;
const int COUNT = 1023; const float SCALE = 0.02f;
private void Awake() { buffer = new CommandBuffer(); for(int i = 0; i < COUNT; ++i) { times[i] = new Vector2(Random.Range(-1f, 1f), Random.Range(0.8f, 1.2f)); matrix[i] = Matrix4x4.identity; matrix[i].m00 = SCALE; matrix[i].m11 = SCALE; matrix[i].m22 = SCALE; matrix[i].m03 = Random.Range(-1f,1f); matrix[i].m13 = Random.Range(-1f, 1f); }
matrixBuffers = new ComputeBuffer(COUNT,64); matrixBuffers.SetData(matrix); timeSliceBuffers = new ComputeBuffer(COUNT, 8); timeSliceBuffers.SetData(times); kernal = shader.FindKernel("CSMain"); shader.SetBuffer(kernal, ShaderIDs.matrixBuffer, matrixBuffers); shader.SetBuffer(kernal, ShaderIDs.timeSliceBuffer, timeSliceBuffers); gausBlurMat = new Material(Shader.Find("Hidden/GaussianBlur")); mat.SetBuffer(ShaderIDs.timeSliceBuffer,timeSliceBuffers); }
private void Update() { shader.SetFloat(ShaderIDs._DeltaFlashSpeed,Time.deltaTime * timeSpeed); shader.Dispatch(kernal, COUNT, 1, 1); matrixBuffers.GetData(matrix); buffer.Clear(); buffer.SetRenderTarget(targetTexture); buffer.ClearRenderTarget(true, true, new Color(0.5f, 0.5f, 1, 1));
buffer.DrawMeshInstanced(fullScreenMesh,0,mat,0,matrix); buffer.GetTemporaryRT(ShaderIDs._TempTexture, targetTexture.descriptor); buffer.Blit(targetTexture, ShaderIDs._TempTexture, gausBlurMat, 0); buffer.Blit(ShaderIDs._TempTexture, targetTexture, gausBlurMat, 1); Graphics.ExecuteCommandBuffer(buffer); } }
|