扭曲 GrapPass,CommandBuffer对比

屏幕图像捕捉:
Shader的GrabPass 过程 最费 会打断绘制流程
    GrabPass可以很方便地捕获当前渲染时刻的FrameBuffer中的图像。
    其原理就是从当前FrameBuffer中copy一份纹理,通过SetTexture的方式设置纹理。
    至于GrabPass的性能问题,一般认为是对FrameBuffer 进行的一些pixel copy operations造成的,
    具体Unity是怎么实现的,不得而知。
    GrabPass { } 不带参数的 默认名字为 "_GrabTexture" 会在当时为每一的使用的obj抓取一次
    GrabPass { "TextureName" } 每个名字在 每帧,第一次使用时抓取一次
GrapPass在每帧至少捕获一次,优化思路是 可以统一关闭,减少抓取次数
    基本思路是,独立一个只绘制扭曲层的相机,在OnPreRender中检查抓取cd,引用次数,扭曲开关等,
    用Graphics.ExecuteCommandBuffer(commandBuffer);的方式手动抓取

核心部分
x
 
1
private void Awake()
2
{
3
    ... ...
4
        
5
    var cam = GetComponent<Camera>();
6
    rt = RenderTexture.GetTemporary(cam.pixelWidth, cam.pixelHeight, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default, 1);
7
    
8
    commandBuffer = new CommandBuffer();
9
    commandBuffer.name = "GrabScreenCommand";
10
    commandBuffer.Blit(BuiltinRenderTextureType.CurrentActive, rt);
11
}
12
13
void OnPreRender()
14
{
15
    if (UseCount <= 0 || Time.time < nextGrapTime)
16
        return;
17
    
18
    nextGrapTime = Time.time + grapCD;
19
    Graphics.ExecuteCommandBuffer(commandBuffer);
20
}

扭曲效果
主要使用两个内置函数 https://www.jianshu.com/p/df878a386bec 
    float4 ComputeScreenPos(float4 pos) 
        将摄像机的齐次坐标下的坐标转为 齐次坐标系下的屏幕坐标值,其范围为[0, w]
        值用作tex2Dproj指令的参数值,tex2Dproj会在对纹理采样前除以w分量。
        当然你也可以自己除以w分量后进行采样,但是效率不如内置指令tex2Dproj
    half4 tex2Dproj(sampler2D s, in half4 t) { return tex2D(s, t.xy / t.w); }
扭曲使用贴图计算UV偏移
核心部分:
14
 
1
    v2f vert (input v) {
2
        v2f o;
3
        o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
4
        o.texcoord = v.texcoord;
5
        o.uvgrab = ComputeGrabScreenPos(o.vertex);
6
        return o;
7
    }
8
9
    fixed4 frag (v2f i) : COLOR {
10
          fixed2 norm = UnpackNormal(tex2D(_Distortion, i.texcoord)).rg;
11
          i.uvgrab.xy -= _Strength * norm.rg * _RaceDropTex_TexelSize.xy;
12
          fixed4 col = tex2Dproj(_RaceDropTex, UNITY_PROJ_COORD(i.uvgrab));
13
          return col;
14
    }

猜你喜欢

转载自www.cnblogs.com/Hichy/p/9274866.html