UnityMol  0.9.6-875
UnityMol viewer / In developement
BlurOptimized.cs
Go to the documentation of this file.
1 using System;
2 using UnityEngine;
3 
4 namespace UnityStandardAssets.ImageEffects
5 {
6  [ExecuteInEditMode]
7  [RequireComponent (typeof(Camera))]
8  [AddComponentMenu ("Image Effects/Blur/Blur (Optimized)")]
10  {
11 
12  [Range(0, 2)]
13  public int downsample = 1;
14 
15  public enum BlurType {
16  StandardGauss = 0,
17  SgxGauss = 1,
18  }
19 
20  [Range(0.0f, 10.0f)]
21  public float blurSize = 3.0f;
22 
23  [Range(1, 4)]
24  public int blurIterations = 2;
25 
26  public BlurType blurType= BlurType.StandardGauss;
27 
28  public Shader blurShader = null;
29  private Material blurMaterial = null;
30 
31 
32  public override bool CheckResources () {
33  CheckSupport (false);
34 
35  blurMaterial = CheckShaderAndCreateMaterial (blurShader, blurMaterial);
36 
37  if (!isSupported)
38  ReportAutoDisable ();
39  return isSupported;
40  }
41 
42  public void OnDisable () {
43  if (blurMaterial)
44  DestroyImmediate (blurMaterial);
45  }
46 
47  public void OnRenderImage (RenderTexture source, RenderTexture destination) {
48  if (CheckResources() == false) {
49  Graphics.Blit (source, destination);
50  return;
51  }
52 
53  float widthMod = 1.0f / (1.0f * (1<<downsample));
54 
55  blurMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod, -blurSize * widthMod, 0.0f, 0.0f));
56  source.filterMode = FilterMode.Bilinear;
57 
58  int rtW = source.width >> downsample;
59  int rtH = source.height >> downsample;
60 
61  // downsample
62  RenderTexture rt = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
63 
64  rt.filterMode = FilterMode.Bilinear;
65  Graphics.Blit (source, rt, blurMaterial, 0);
66 
67  var passOffs= blurType == BlurType.StandardGauss ? 0 : 2;
68 
69  for(int i = 0; i < blurIterations; i++) {
70  float iterationOffs = (i*1.0f);
71  blurMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod + iterationOffs, -blurSize * widthMod - iterationOffs, 0.0f, 0.0f));
72 
73  // vertical blur
74  RenderTexture rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
75  rt2.filterMode = FilterMode.Bilinear;
76  Graphics.Blit (rt, rt2, blurMaterial, 1 + passOffs);
77  RenderTexture.ReleaseTemporary (rt);
78  rt = rt2;
79 
80  // horizontal blur
81  rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
82  rt2.filterMode = FilterMode.Bilinear;
83  Graphics.Blit (rt, rt2, blurMaterial, 2 + passOffs);
84  RenderTexture.ReleaseTemporary (rt);
85  rt = rt2;
86  }
87 
88  Graphics.Blit (rt, destination);
89 
90  RenderTexture.ReleaseTemporary (rt);
91  }
92  }
93 }
void OnRenderImage(RenderTexture source, RenderTexture destination)