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
| public class GaussianBlur : MonoBehaviour { [SerializeField] private Texture _texture; [SerializeField] private Shader _shader; [SerializeField, Range(1f, 10f)] private float _offset = 1f; [SerializeField, Range(10f, 1000f)] private float _blur = 100f;
private Material _material; private Renderer _renderer; private RenderTexture _rt1; private RenderTexture _rt2; private float[] _weights = new float[10]; private bool _isInitialized = false;
#region ### MonoBehaviour ### private void Awake() { Initialize(); } private void OnValidate() { if (!Application.isPlaying) { return; } UpdateWeights(); Blur(); } #endregion ### MonoBehaviour ###
private void Initialize() { if (_isInitialized) { return; } _material = new Material(_shader); _material.hideFlags = HideFlags.HideAndDontSave;
_rt1 = new RenderTexture(_texture.width / 2, _texture.height / 2, 0, RenderTextureFormat.ARGB32); _rt2 = new RenderTexture(_texture.width / 2, _texture.height / 2, 0, RenderTextureFormat.ARGB32);
_renderer = GetComponent<Renderer>(); UpdateWeights(); _isInitialized = true; }
public void Blur() { if (!_isInitialized) { Initialize(); }
Graphics.Blit(_texture, _rt1); _material.SetFloatArray("_Weights", _weights); float x = _offset / _rt1.width; float y = _offset / _rt1.height;
_material.SetVector("_Offsets", new Vector4(x, 0, 0, 0)); Graphics.Blit(_rt1, _rt2, _material);
_material.SetVector("_Offsets", new Vector4(0, y, 0, 0)); Graphics.Blit(_rt2, _rt1, _material);
_renderer.material.mainTexture = _rt1; }
private void UpdateWeights() { float total = 0; float d = _blur * _blur * 0.001f; for (int i = 0; i < _weights.Length; i++) { float x = i * 2f; float w = Mathf.Exp(-0.5f * (x * x) / d); _weights[i] = w; if (i > 0) { w *= 2.0f; } total += w; } for (int i = 0; i < _weights.Length; i++) { _weights[i] /= total; } } }
|