Using multiple materials in the toolkit does not help with dynamic batching
There is a very interesting forum thread going on about performance and Dynamic Batching:
https://forums.hololens.com/discussion/6376/gameobject-limit-on-performance
It appears that accessing .material instead of .sharedmaterial causes shared materials to become instanced and breaks dynamic batching. It also appears that some of the toolkit behaviors (e.g. gaze responder) access materials in this way.
My knowledge of the Unity rendering pipeline doesn't go deep enough to validate this, but I think it's worth having someone with more knowledge take a look and see if these behaviors could be improved. By changing toolkit behavior code, this user was able to get another 12 FPS out of their app. Though it's wort noting that these changes seemed to cause other issues (like with the cursor).
Yes, using the renderer.material property does cause the renderer to create a new instance of the shared material. Using renderer.sharedMaterial avoids this, but any changes made to the material properties (such as color and texture) will be applied to all renderers using that shared material (excepting those that have instanced off a new material using the .material property). There are also a 'materials' and 'sharedMaterials' properties that have the same behavior.
You can avoid instancing materials and allow per-renderer property changes using MaterialPropertyBlock. MaterialPropertyBlock allows changes to the property of a shared material per-renderer and without spinning off a new instance of the material. We have been using this method and though it does take a bit more developer attention, it is more performant than creating instanced materials using the material property.
~~I believe you'll still have to either to grab the .sharedMaterial or the .material instance.~~ Not cleaning up the material instance properly is known to cause memory leaks.
[edit] You can access the MaterialPropertyBlock directly from the renderer.
There is an example of using the MaterialPropertyBlock in the ManualHandControl class, ~~but I think it updates the color property incorrectly by setting the color in the material reference and not in the MaterialPropertyBlock. This causes a new material instance to be created every time we set a new color.~~
Correct:
private PropertyBlock m_PropertyBlock ;
private Renderer myRenderer;
private void Start()
{
myRenderer = GetComponentInChildren<Renderer>();
m_PropertyBlock = new MaterialPropertyBlock();
}
private void Update()
{
m_PropertyBlock.SetColor("_EmissionColor", newColor * 7.8f);
myRenderer.SetPropertyBlock(m_PropertyBlock);
}
Good Material Property Block Tutorial: http://thomasmountainborn.com/2016/05/25/materialpropertyblocks/
Note that while it is possible to use renderer.SetPropertyBlock() on a shader property that does not have the [PerRendererData] keyword, Unity will simply create a new material instance behind your back.
[edit]
Something else to point out is that if you add [PerRendererData] to your shader, then the material properties disappear in the inspector window for your associated material. So each material that uses HTK shaders with this attribute will also need a custom material inspector window.
Also I know the shaders were recently updated to allow for single pass (stereo) https://github.com/Microsoft/HoloToolkit-Unity/pull/393 ~~so it might just be a matter of updating how each developer handles the material instances based on their specific needs.~~
[edit] The shaders would need to be updated with the [PerRendererData] attribute tag and custom inspectors would also need to be written for each material using the shaders.
I worked on this briefly last month. Probably a good place to start looking if anyone would like to make changes and make improvements: https://github.com/Microsoft/HoloToolkit-Unity/pull/424
I would like to point out that a majority of these scripts live in test/example folders, are not production ready, and most likely doesn't represent each the needs of each developer.
Unfortunately GitHub won't let you search for ".material" because "." is an invalid search character. So I opened the toolkit in Visual Studio and did a search. Here are all the instances of referencing .material.
Looks like there are only 21 of them. 5 of them are in HoloToolkit-Examples. 5 of them are in a path that includes "Test" 11 of them in core code.
// Examples
HoloToolkit-Examples\ColorPicker\GazeableColorPicker.cs(33):
Texture2D texture = rendererComponent.material.mainTexture as Texture2D;
HoloToolkit-Examples\GazeRuler\Scripts\ModeTip.cs(23):
material = GetComponent<Renderer>().material;
HoloToolkit-Examples\SharingWithUNET\Scripts\PlayerController.cs(74):
GetComponentInChildren<MeshRenderer>().material.color = Color.red;
HoloToolkit-Examples\SharingWithUNET\Scripts\PlayerController.cs(119):
GetComponentInChildren<MeshRenderer>().material.color = Color.blue;
HoloToolkit-Examples\SpatialUnderstanding\SpatialUnderstanding-FeatureOverview\Scripts\LineDrawer.cs(407):
lineData.Renderer.material = MaterialLine;
// Tests
HoloToolkit\Input\Tests\Scripts\FocusedObjectColorChanger.cs(23):
cachedMaterial = GetComponent<Renderer>().material;
HoloToolkit\Input\Tests\Scripts\GazeResponder.cs(18):
defaultMaterials = GetComponent<Renderer>().materials;
HoloToolkit\Input\Tests\Scripts\SelectedObjectMessageReceiver.cs(23):
cachedMaterial = GetComponent<Renderer>().material;
HoloToolkit\Input\Tests\Scripts\SphereGlobalKeywords.cs(20):
cachedChildMaterials[i] = childRenderers[i].material;
HoloToolkit\Input\Tests\Scripts\SphereKeywords.cs(15):
cachedMaterial = GetComponent<Renderer>().material;
HoloToolkit\Input\Tests\Scripts\TestButton.cs(108):
cachedToolTipMaterial = ToolTipRenderer.material;
// Core
HoloToolkit\Utilities\Scripts\DirectionIndicator.cs(97):
indicatorMaterial = directionIndicatorRenderer.material;
HoloToolkit\Input\Scripts\Utilities\ManualHandControl.cs(273):
leftHandVisualRenderer.material.SetColor("_Color", LeftHandInView ? ActiveHandColor : DroppedHandColor);
HoloToolkit\Input\Scripts\Utilities\ManualHandControl.cs(274):
rightHandVisualRenderer.material.SetColor("_Color", RightHandInView ? ActiveHandColor : DroppedHandColor);
HoloToolkit\Sharing\Scripts\Utilities\Utils.cs(104):
t.gameObject.GetComponent<Renderer>().material = mat;
HoloToolkit\Sharing\Scripts\Utilities\Utils.cs(128):
t.gameObject.GetComponent<Renderer>().material = mat;
HoloToolkit\SpatialMapping\Scripts\SpatialProcessing\SurfacePlane.cs(198):
renderer.material = FloorMaterial;
HoloToolkit\SpatialMapping\Scripts\SpatialProcessing\SurfacePlane.cs(204):
renderer.material = TableMaterial;
HoloToolkit\SpatialMapping\Scripts\SpatialProcessing\SurfacePlane.cs(210):
renderer.material = CeilingMaterial;
HoloToolkit\SpatialMapping\Scripts\SpatialProcessing\SurfacePlane.cs(216):
renderer.material = WallMaterial;
HoloToolkit\SpatialMapping\Scripts\SpatialProcessing\SurfacePlane.cs(222):
renderer.material = UnknownMaterial;
This probably wouldn't be too terribly time consuming for someone who knows what they're doing to review those uses and see if there's a better way to do it.
One thing I'm not clear on, if a GameObject has a .material set, can I access that through the .sharedMaterial property? Or is there a way to somehow check whether a shared material or instanced material is being used?
Looks like there are only 21 of them. 5 of them are in HoloToolkit-Examples. 5 of them are in a path that includes "Test" 11 of them in core code.
The HoloToolkit-Examples definitively use .material improperly, causing material leaks.
The Test and Core scripts could be improved to better handle dynamic batching using MaterialPropertyBlocks, but without the [PerRendererData] attribute tag in the shader code, we're pretty much back at the start.
Something else to point out is that if you add [PerRendererData] to your shader, then the material properties disappear in the inspector window for your associated material. So each material that uses HTK shaders with this attribute will also need a custom material inspector window located on the game objects that implement them.
A bit of research in the Unity Documentation:
Dynamic batching
Unity can automatically batch moving GameObjects into the same draw call if they share the same Material and fulfill other criteria. Dynamic batching is done automatically and does not require any additional effort on your side.
- Batching dynamic GameObjects has certain overhead per vertex, so batching is applied only to Meshes containing fewer than 900 vertex attributes in total.
- If your Shader is using Vertex Position, Normal and single UV, then you can batch up to 300 verts, while if your Shader is using Vertex Position, Normal, UV0, UV1 and Tangent, then only 180 verts.
- Note: attribute count limit might be changed in future.
- GameObjects are not batched if they contain mirroring on the transform (for example GameObject A with +1 scale and GameObject B with –1 scale cannot be batched together).
- Using different Material instances causes GameObjects not to batch together, even if they are essentially the same. The exception is shadow caster rendering.
- GameObjects with lightmaps have additional renderer parameters: lightmap index and offset/scale into the lightmap. Generally, dynamic lightmapped GameObjects should point to exactly the same lightmap location to be batched.
- Multi-pass Shaders break batching.
- Almost all Unity Shaders support several Lights in forward rendering, effectively doing additional passes for them. The draw calls for “additional per-pixel lights” are not batched.
- The Legacy Deferred (light pre-pass) rendering path has dynamic batching disabled, because it has to draw GameObjects twice.
Does anyone know if GPU instancing is available on the HoloLens?
@HodgsonSDAS Yes, GPU instancing works (drawing approx. 200k tris on the Hololens right now with that). I took the HoloToolkit shaders a while back and converted them to use it, but it is very specialized for my use case.
Right, as @HodgsonSDAS mentioned for dynamic batching to truly help its usually recommended to have one material and a combined texture atlas that can help with multiple game objects in the scene.
@dbastienMS any thoughts on material Vs sharedMaterial usage and any improvements we could make?
Swapping materials, using sharedMaterial, or using property blocks are the ways to handle this, and it depends on the particular use case.
Accessing .material should almost never be done.
FYI though - dynamic batching isn't likely to improve performance a ton anyway for most applications - draw call overhead will be massively dwarfed by per-pixel ALU ops. Most applications I look at have ~50-100 batches which should be no problem whatsoever.
If you're having perf trouble I recommend switching to the new FastConfigurable shader and additionally making sure you're not overdrawing the screen too much.
I'm going to change this label from bug to enhancement because the requirements are different from developer to developer.
Addressed in the coding style guide. Internal to the MRTK, we will be enforcing good behavior as new features are brought online (and old ones take change requests).
We will also go through the scripts pointed out by @jbienz to make sure we have addressed what he found.