在前兩篇文章《Unity3D學習筆記6——GPU範例化(1)》《Unity3D學習筆記6——GPU範例化(2)》分別介紹了通過簡單的頂點著色器+片元著色器,以及通過表面著色器實現GPU範例化的過程。而在Unity的官方檔案Creating shaders that support GPU instancing裡,也提供了一個GPU範例化的案例,這裡就詳細論述一下。
一個有意思的地方在於,Unity提供的標準材質支援自動範例化,而不用像《Unity3D學習筆記6——GPU範例化(1)》《Unity3D學習筆記6——GPU範例化(2)》那樣額外編寫指令碼和Shader。並且,會自動將transform,也就是模型矩陣作為每個範例的屬性。
照例,還是編寫一個指令碼掛到一個空的GameObject物件上:
using UnityEngine;
public class Note8Main : MonoBehaviour
{
public Mesh mesh;
public Material material;
public int instanceCount = 5000;
// Start is called before the first frame update
void Start()
{
MaterialPropertyBlock props = new MaterialPropertyBlock();
for (int i = 0; i < instanceCount; i++)
{
GameObject go = new GameObject();
go.name = i.ToString();
MeshFilter mf = go.AddComponent<MeshFilter>();
mf.mesh = mesh;
MeshRenderer mr = go.AddComponent<MeshRenderer>();
mr.material = material;
go.transform.position = Random.insideUnitSphere * 5;
go.transform.eulerAngles = new Vector3(Random.Range(0.0f, 90.0f), Random.Range(0.0f, 90.0f), Random.Range(0.0f, 90.0f));
float s = Random.value;
go.transform.localScale = new Vector3(s, s, s);
go.transform.parent = gameObject.transform;
}
}
// Update is called once per frame
void Update()
{
}
}
這個指令碼的意思是,給掛接的GameObject下新建很多GameObject,它們使用我們傳入的Mesh和Material,但是位置、姿態和大小是隨機的。傳入的Mesh使用Unity自帶的膠囊體,Material使用Unity的標準材質。執行結果如下:
這個時候Unity還沒有自動範例化,開啟Frame Debug就可以看到:
這個時候我們可以在使用的材質上勾選開啟範例化的選項:
再次執行,就會在Frame Debug看到Unity實現了自動範例化,繪製的批次明顯減少,並且效能會有所提升:
可以看到確實是自動進行範例化繪製了,但是這種方式卻似乎存在範例化個數的上限,所有的範例化資料還是分成了好幾個批次進行繪製。與《Unity3D學習筆記6——GPU範例化(1)》《Unity3D學習筆記6——GPU範例化(2)》提到的通過底層介面Graphic進行範例化繪製相比,效率還是要低一些。
自動範例化只能將transform,也就是模型矩陣作為每個範例的屬性。如果需要增加自己的範例屬性,就需要使用MaterialPropertyBlock,也就是材質屬性塊。
修改上面的指令碼:
using UnityEngine;
public class Note8Main : MonoBehaviour
{
public Mesh mesh;
public Material material;
public int instanceCount = 5000;
// Start is called before the first frame update
void Start()
{
MaterialPropertyBlock props = new MaterialPropertyBlock();
for (int i = 0; i < instanceCount; i++)
{
GameObject go = new GameObject();
go.name = i.ToString();
MeshFilter mf = go.AddComponent<MeshFilter>();
mf.mesh = mesh;
MeshRenderer mr = go.AddComponent<MeshRenderer>();
mr.material = material;
float r = Random.Range(0.0f, 1.0f);
float g = Random.Range(0.0f, 1.0f);
float b = Random.Range(0.0f, 1.0f);
props.SetColor("_Color", new Color(r, g, b));
mr.SetPropertyBlock(props);
go.transform.position = Random.insideUnitSphere * 5;
go.transform.eulerAngles = new Vector3(Random.Range(0.0f, 90.0f), Random.Range(0.0f, 90.0f), Random.Range(0.0f, 90.0f));
float s = Random.value;
go.transform.localScale = new Vector3(s, s, s);
go.transform.parent = gameObject.transform;
}
}
// Update is called once per frame
void Update()
{
}
}
指令碼使用的材質,其使用的Shader如下,可以直接在Standard Surface Shader的基礎上改:
Shader "Custom/HiddenSurfaceIntanceShader"
{
Properties
{
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 200
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
sampler2D _MainTex;
struct Input
{
float2 uv_MainTex;
};
half _Glossiness;
half _Metallic;
//fixed4 _Color;
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
// #pragma instancing_options assumeuniformscaling
UNITY_INSTANCING_BUFFER_START(Props)
// put more per-instance properties here
UNITY_DEFINE_INSTANCED_PROP(fixed4, _Color)
UNITY_INSTANCING_BUFFER_END(Props)
void surf (Input IN, inout SurfaceOutputStandard o)
{
// Albedo comes from a texture tinted by color
//fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * UNITY_ACCESS_INSTANCED_PROP(Props, _Color);
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}
關鍵的程式碼在於Unity內建宏UNITY_INSTANCING_BUFFER_START和UNITY_INSTANCING_BUFFER_END、UNITY_DEFINE_INSTANCED_PROP定義了範例化屬性,在著色器中,通過內建宏UNITY_ACCESS_INSTANCED_PROP來獲取這個屬性值。這個範例化屬性也就是指令碼程式碼中MaterialPropertyBlock傳入的顏色值。
檢視Unity Shader原始碼,這四個用於範例化的宏封裝的是一個cbuffer陣列,cbuffer就是hlsl的常數緩衝區:
#define UNITY_INSTANCING_CBUFFER_SCOPE_BEGIN(name) cbuffer name {
#define UNITY_INSTANCING_CBUFFER_SCOPE_END }
#define UNITY_INSTANCING_BUFFER_START(buf) UNITY_INSTANCING_CBUFFER_SCOPE_BEGIN(UnityInstancing_##buf) struct {
#define UNITY_INSTANCING_BUFFER_END(arr) } arr##Array[UNITY_INSTANCED_ARRAY_SIZE]; UNITY_INSTANCING_CBUFFER_SCOPE_END
#define UNITY_DEFINE_INSTANCED_PROP(type, var) type var;
#define UNITY_ACCESS_INSTANCED_PROP(arr, var) arr##Array[unity_InstanceID].var
執行的結果如下:
可以看到除了紋理,每一個膠囊體還獲取了隨機賦予給材質的顏色,也就是我們設定的顏色成為了範例化屬性資料。MaterialPropertyBlock主要由Graphics.DrawMesh和Renderer.SetPropertyBlock使用,在希望繪製具有相同材質,但屬性略有不同的多個物件時可使用它。
個人認為使用MaterialPropertyBlock自動範例化效能比不上使用Graphics.DrawMeshInstancedIndirect(),但是它有個優點是範例化的要求沒那麼高,Graphics.DrawMeshInstancedIndirect()要求使用同一mesh,同一貼圖;但是MaterialPropertyBlock沒這個要求,只要是同一材質,任何屬性不一樣都可以用,在減少繪製批次的同時還能減少材質的個數。