GPU instancing介绍

从Unity5.4开始,多了一个叫做GPU instancing的功能。这个功能是做什么用的呢?下面做一个小例子来说明一下:
还是之前做 MaterialPropertyBlock的例子,在屏幕上面做了很多的cube,然后随机给颜色,使用MaterialPropertyBlock的方式设置颜色值。
这里写图片描述
可以看到,正常情况下,在改变完颜色之后,Batches有75个,而SetPass calls有75个。

下面换成GPU instancing的做法,同样的效果,可以看看数据:
这里写图片描述
和之前完全一样的视觉效果,但Batches和SetPass calls都变成只有11了。

这是怎么做到的呢?
首先 ,我们必须是使用MaterialPropertyBlock来设置材质的属性,因为如果用传统的设置颜色,会把材质生成多个实例,这样就没有办法合并了。使用MaterialPropertyBlock由于从始至终只有一个material,所以它们才可以合并。
然后,需要特殊的shader来配合工作。在Unity5.4和5.5版本,都可以看到在创建shader的时候,多了一个选项Standard Surface Shader(Instanced)。这个shader类型就是支持GPU Instancing的。到了Unity5.6这个选项已经消失了,因为默认创建的Standard Surface Shader已经支持GPU Instancing了。
这里写图片描述
当然了,我们不可能每个地方都用 Standard Surface Shader这种消耗特别大的shader,所以我们也可以手动的修改自己写的shader,官方的文档里面也有说明:
#pragma multi_compile_instancing Use this to instruct Unity to generate instancing variants. It is not necessary for surface Shaders.
UNITY_VERTEX_INPUT_INSTANCE_ID Use this in the vertex Shader input/output structure to define an instance ID. See SV_InstanceID for more information.
UNITY_INSTANCING_CBUFFER_START(name) /UNITY_INSTANCING_CBUFFER_END Every per-instance property must be defined in a specially named constant buffer. Use this pair of macros to wrap the properties you want to be made unique to each instance.
UNITY_DEFINE_INSTANCED_PROP(float4, _Color) Use this to define a per-instance Shader property with a type and a name. In this example, the _Color property is unique.
UNITY_SETUP_INSTANCE_ID(v); Use this to make the instance ID accessible to Shader functions. It must be used at the very beginning of a vertex Shader, and is optional for fragment Shaders.
UNITY_TRANSFER_INSTANCE_ID(v, o); Use this to copy the instance ID from the input structure to the output structure in the vertex Shader. This is only necessary if you need to access per-instance data in the fragment Shader.
UNITY_ACCESS_INSTANCED_PROP(color) Use this to access a per-instance Shader property. It uses an instance ID to index into the instance data array.
举例说,我们可以在shader里面添加:
UNITY_INSTANCING_CBUFFER_START(Props)
UNITY_DEFINE_INSTANCED_PROP(fixed4, _Color) // Make _Color an instanced property (i.e. an array)
UNITY_INSTANCING_CBUFFER_END
让它支持GPU Instancing。

在Unity5.4和5.5版本,只要你的Shader支持,自动就会开启GPU Instance。到了Unity5.6,在材质选项里面会多了一个勾选:
这里写图片描述
这是一个开关。假如你不勾选,就算你的shader是支持的,GPU Instance功能也不会生效。

  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值