??去年參加Unite2017 Tokyo的時候,Unity可編程渲染管道(Scriptable Render Pipeline忘晤,下面簡稱SRP)其實已經(jīng)出來了(資料在這里)捏顺。那時候?qū)nity不太熟所以沒有特別關(guān)注勾拉,現(xiàn)在Unity2018已經(jīng)可以用SRP了炒考,所以簡單介紹一下來龍去脈疆液,以及入門級的用法,拋磚引玉表窘。
為什么需要SRP
??Unity內(nèi)置的渲染管道只有Forward和Deferred兩種典予,如下圖甜滨。
??這兩種內(nèi)置的管道各有優(yōu)缺點 乐严,而你都看不到源代碼,如果為了表現(xiàn)某種特殊的視覺效果修改起來非常不便衣摩,所以就有了SRP的誕生昂验。另外捂敌,根據(jù)項目的需求寫合適的SRP,也可以降低DC既琴,提高運行效率占婉。
怎么使用SRP
安裝
??從這里下載Unity2018之后,就自帶了SRP甫恩,無需另外安裝逆济。
使用
?? 接下來我會一步一步地做一個只是把屏幕涂成綠色的SRP,可能你不太懂每一步的意義磺箕,但是請耐心地跟著做完奖慌,再回頭看看每一步就懂了。
第一步:繼承RenderPipeline,編寫實際的渲染代碼類。
public class BasicPipeInstance : RenderPipeline
{
//要涂的顏色
private Color m_ClearColor = Color.black;
public BasicPipeInstance(Color clearColor)
{
m_ClearColor = clearColor;
}
//渲染函數(shù)盈匾,其中ScriptableRenderContext是渲染的上下文漠魏,
//用來執(zhí)行CommandBuffer,而CommandBuffer就是渲染管線每一步的處理
//CommandBuffer是Unity之前的就有的東西掸驱,想詳細了解請自行百度谷歌
public override void Render(ScriptableRenderContext context, Camera[] cameras)
{
// does not so much yet :()
base.Render(context, cameras);
// clear buffers to the configured color
var cmd = new CommandBuffer();
cmd.ClearRenderTarget(true, true, m_ClearColor);
context.ExecuteCommandBuffer(cmd);
cmd.Release();
context.Submit();
}
}
第二步:繼承RenderPipelineAsset,編寫生成SRP數(shù)據(jù)文件的類。
public class BasicAssetPipe : RenderPipelineAsset
{
public Color clearColor = Color.green;
#if UNITY_EDITOR
[UnityEditor.MenuItem("SRP-Demo/01 - Create Basic Asset Pipeline")]
static void CreateBasicAssetPipeline()
{
//生成ScriptableObject
var instance = ScriptableObject.CreateInstance<BasicAssetPipe>();
//將ScriptableObject保存為文件
UnityEditor.AssetDatabase.CreateAsset(instance, "Assets/BasicAssetPipe.asset");
}
#endif
protected override IRenderPipeline InternalCreatePipeline()
{
//應(yīng)該是運行時被調(diào)用生成SRP
return new BasicPipeInstance(clearColor);
}
}
第三步:創(chuàng)建SRP asset啦逆,如下圖。
??這時候Assets文件夾里會生成一個BasicAssetPipe.asset文件脸哀。
第四步:將BasicAssetPipe.asset設(shè)置為當前使用的SRP蹦浦。
??打開Editor->Project Settings->Graphics,然后將剛才的BasicAssetPipe.asset文件拖到Scriptable Render Pipeline Settings撞蜂,如下圖盲镶。
??然后你就可以看到游戲變成一片綠了。
??代碼在官方的例子里有蝌诡,路徑和使用的包請自行修改添加溉贿。作為不錯的入門學習,也可以看看這位日本大哥的代碼浦旱。
參考資料:
https://blogs.unity3d.com/cn/2018/01/31/srp-overview/
http://tips.hecomi.com/entry/2018/02/19/000846