作用:
- 批渲染Mesh相同的那些物體,以降低DrawCall數
- 這些物體可以有不同的參數,比如顏色與縮放
GPU Instancing與靜態批處理,動態批處理的區別
-
使用靜態,動態批處理物體的材質的所有參數是相同的,因為使用
Renderer.sharedMaterial
修改參數,則所有物體都會受影響。而使用Renderer.material
會生成新實例,沒法進行批處理 -
使用GPU Instancing的同一類物體的材質對象相同,但可以在代碼中通過接口設置不同的參數,但仍會被批渲染。
使用條件:
-
兼容的平台及API
-
相同的Mesh與Material
-
不支持SkinnedMeshRenderer
-
Shader支持GPU Instancing
GPU Instancing支持的平台:
- DirectX 11 and DirectX 12 on Windows
- OpenGL Core 4.1+/ES3.0+ on Windows, macOS,
- Linux, iOS and Android
- Metal on macOS and iOS
- Vulkan on Windows and Android
- PlayStation 4 and Xbox One
- WebGL (requires WebGL 2.0 API)
注意:
-
使用multiple per-instance屬性時,不用在MaterialPropertyBlocks中填充所有屬性
-
如果一個instance缺少了屬性,則會使用材質的默認值,沒有默認值則使用0
-
不要將非instanced的屬性寫入MaterialPropertyBlocks中,否則會造成instancing關閉,會創建出不同的材質
-
靜態批渲染優先級比GPU Instancing高
-
有些情況會導致instancing失敗
- 材質改變
- 深度排序
如果想強制使用instancing繪制這些物體,就得使用Graphics.DrawMeshInstanced
Graphics.DrawMeshInstanced
- 提交的批處理的實例數量不能超過最大值500
- 當使用OpenGL,Metal的graphics tools時,最大值500還要除以4
- 建議使用預先分配的instancing數組,具體參見Automatic Memory Management
- API
Graphics.DrawMeshInstancedIndirect
- 用來讀取instancing draw calls的參數
- API
param instancing_options
-
maccount: batchSize
- 盡量接近實際的instance數量,以減少Shader編譯時間
- 使用opengl或metal最大數量將除以4
-
force_same_maxcount_for_gl
- 強制opengl或metal中最大instance數量不除以4
-
assumeuniformscaling
指定所有的縮放都為統一縮放 -
lodfade
-
procedual:FunctionName
注意
-
Surface Shader默認開啟了instancing,如果要關閉則定義
#param noinstancing
-
Unity默認剔除未使用的的Instancing,如要全部使用則需要在
Graphics Setting
中設置選項Instancing Variants
-
使用Graphics.DrawMeshInstanced時,需要勾選材質中的選項
Enable Instancing
。使用Graphics.DrawMeshInstancedIndirect則不需要勾選。此時PROCEDURAL_INSTANCING_ON
不被stripping影響 -
Instanced draw calls在Frame Debugger中表現為
Draw Mesh(instanced)
-
雖然不需要總是定義逐instance的屬性,但是還是要設置instance ID。因為世界矩陣需要這個參數才能正常工作。Surface會自動添加,但是自定義的頂點片元Shader需要手動添加
UNITY_SETUP_INSTANCE_ID
-
在前向渲染中,不支持多光照,只有base pass才會生效,參考Forward Rendering 和 Pass Tags
-
使用了lightmaps,不同的光或Reflection Probes時instancing不會生效
-
使用了多個pass的shader中,只有第一個pass才能使用instancing,因為對於一個物體,之后所有的pass會一同渲染,造成材質變化。
-
所有宏命令都在
UnityInstancing.cginc
中
https://docs.unity3d.com/560/Documentation/Manual/GPUInstancing.html
作者:曉龍醬
鏈接:https://www.jianshu.com/p/1492611bb432
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。