Unity Shader Getting Started Essentials learning notes-16th. Rendering Optimization technology in unity

Source: Internet
Author: User

From Fengle, "Unity Shader Essentials of Getting Started"

Features of the mobile platform

To minimize overdraw (that is, one pixel is drawn multiple times) for as many hidden surfaces as possible, the PowerVR chip (typically used for iOS devices and some Android devices) uses a tile-based deferred rendering (TBDR) architecture that loads all the rendered images into tiles, The visible slices are then found by the hardware, and only these visible elements execute the slice shader. Other tile-based GPU architectures, such as the Adreno (high-pass chip) and the Mali (ARM's chip), adapt to early-z or similar techniques for a low-precision depth-detection to eliminate elements that do not need to be rendered. Some GPUs, such as Tegra (Nvidia's chips), use traditional architecture designs, so overdraw is more likely to cause performance bottlenecks on these devices.

Factors that affect performance

We can divide the main cause of the game performance bottleneck into the following aspects

1) CPU

Too many draw call

Complex scripting or physical simulations

2) GPU

Vertex processing (too many vertices, too many vertex-wise calculations)

Chip processing (too many slices, too much chip-by-element calculation)

3) Bandwidth

Use a large, uncompressed texture

Frame cache with high resolution

For CPUs, the limit is mainly the number of draw call per frame. Draw call, simply put, is that the CPU needs to prepare the vertex data in advance before each notification to the GPU, then calls a series of APIs to place them at the specified location that the GPU can access, and finally calls a draw command. When the draw command is called, a draw call is generated. Too many draw calls cause CPU performance bottlenecks, because each time a draw call is called, the CPU is often a setting that needs to change a lot of rendering state, and these operations are time consuming. Of course, other causes can also cause CPU bottlenecks, such as physics, not simulation, skinning, particle simulations, and so on, which are computationally significant operations.

For the GPU, it is responsible for the entire rendering pipeline. It starts with the processing of the model data passed by the CPU, carries out a series of work such as vertex shaders, slice shaders, and finally outputs each pixel on the screen. Therefore, GPU performance bottlenecks and the number of vertices to be processed, screen resolution, video memory and other factors.

The optimization techniques we are dealing with are

1) CPU Optimization

Use batch technology to reduce the number of draw call.

2) GPU Optimization

Reduce the number of vertices that need to be processed (optimize geometry, LOD techniques using models, LOD techniques using models, occlusion culling techniques)

Reduce the number of slices that need to be processed (control drawing order, beware of transparent objects, reduce real-time illumination)

Reduced computational complexity (LOD technology using shader, code optimization)

3) Save Memory bandwidth

Reduce texture size

Scale with resolution

LOD techniques for using modelsRendering analysis tools in UnityUnity has built-in tools to help us easily view and render relevant statistical data. This data can help us analyze game rendering performance for more targeted optimization. Unity5 provides a new window, the render Statistics window, to display the various render statistics variables for the current game, which you can open by clicking the Stats button in the menu at the top right of the Games view, as shown in. As you can see, the Render Statistics window contains 3 aspects of audio, image, and grid information. The Render Statistics window shows a number of important rendering data. The following table shows each of the information displayed in the Render Statistics window. One of the most obvious differences between the rendering statistics window of Unity 5 compared to the previous version is that the display of the number of draw call is removed, and the number of batches is added. Bathes and Saved by batching make it easier for developers to understand the optimization results of batch processing. Of course, we want to see more detailed data such as the number of draw call, which can be viewed through the Unity Editor's Performance Analyzer. We can open the Performance Analyzer for unity by clicking the Profiler on window. The rendering area in the Performance Analyzer provides more statistical information about rendering, and gives rendering analysis results. The Performance Analyzer shows most of the information provided in the Render Statistics window, for example, the Green line shows the number of batches, the number of passes shown on the blue Line, and many other useful information, such as the number of draw call, the number of dynamic batches/static batches, Number of rendered textures, memory footprint, and so on. We can open the Frame debugger through window, frame Debugger, as shown. The debug panel of the frame debugger shows all the rendering events needed to render this frame, in this case, the number of events is 14, which contains 10 draw call events (many of the other rendering events are empty caches, etc.). By clicking each event on the panel, we can view the drawing results of the event in the game view, while the data on the render statistics panel will also show the individual rendering statistics as of the current event.reduce the number of DrawcallThe optimization technique we see most often is batch processing. The implementation of batching is designed to reduce the number of draw calls per frame. To render an object to the screen, the CPU needs to check which light sources affect the object, bind shader to set its parameters, and then send the rendering fame to the GPU. These operations can be time-consuming when a large number of objects are included in the scene. An extreme example is that if we need to render 1000 triangles, it takes much longer to render them in 1000 separate meshes than to render a mesh with 1000 triangles. In both cases, the GPU's performance consumption is not much different, but the number of draw call on the CPU becomes a performance bottleneck. Therefore, the idea of batch processing is simple, which is to deal with as many objects as possible each time you face draw call. Objects with the same material can be processed together. For objects that use the same material, the difference between them is only the differences in vertex data. We can combine these vertex data together and send it together to the GPU to complete a batch processing. Two batches are supported in unity: one is dynamic batching, and the other is static batch processing. For dynamic batching, it's all about unity Auto-complete, no need to do anything on our own, and objects can be moved, but the downside is that there are a lot of limitations that could inadvertently damage this mechanism, causing unity to not dynamically batch some objects that use the same material. For static batching, it has the advantage of being very liberal and limited, but the disadvantage is that it may take up more memory, and all objects in the static batch can no longer be moved. The principle of dynamic batching is that each frame merges a model grid that can be batched, then passes the merged model data to the GPU and renders it using the same material. Another benefit of the dynamic batching process is that the batch object can still be moved because unity merges the mesh once per frame. While Unity's dynamic batching does not require us to do any extra work, only the models that meet the criteria can be dynamically batched. The limitations to be noted are: 1) The scale of the mesh vertex attributes that are capable of dynamic batching is less than 900. For example, if you need to use the 3 vertex properties of vertex position, normals, and texture coordinates in shader, you want to allow the model to be dynamically batched, it cannot have more than 300 vertices. It is important to note that this number is likely to change in the future, so do not rely on this data. 2) in general, all objects need to use the same scaling scale. An exception to this is that if all objects use different non-uniform scaling, they can also be dynamically batched. In Unity 5, however, this limitation on model scaling no longer exists. 3Objects that use light textures need to be handled with extra care. These objects require additional rendering parameters, such as index, offset, and zoom information on the light texture. Therefore, in order for these objects to be dynamically batched, we need to make sure that they point to the same position in the light texture. 4) Multiple pass shader will interrupt batch processing. In forward rendering, we sometimes need to use an extra pass to add more lighting effects to the model, but the model is dynamically batched. We have a scene that contains 3 cubes that use a material and also contain a sphere that uses a different material. The scene also contains a parallel light, but we have closed its shadow effect to avoid the effect of shadow calculations on the number of batches. The rendering statistics for such a scene are as shown. As you can see, it takes two batches to render a scene that contains 4 objects. Where one batch is used to draw a 3 cube grid after a dynamic batch merge, and another batch is used to draw the sphere. We can see from save by batching that the batch helped us save two draw call. Now, we add a point light to the scene and adjust its position so that it illuminates 4 objects in the scene. Because the objects in the scene use multiple pass shader, the point light will have a light effect on them. The rendering statistics after adding a point light source are given. As you can see, the number of batches required to render a frame increases to 8, and the number of save by batching becomes. It is important to note that only the object is within the scope of the point light, unity will invoke an additional pass to handle it. Therefore, if the scene's midpoint light source is far away from the object, they will still be dynamically batched. Dynamic batching has more restrictive conditions, for example, in many cases, our model data tends to exceed the 900 vertex limit. At this point we can use the static batch process. Static batching is suitable for a geometric model of any size, relative to a dynamic batch process. It does this by merging models that require static batching into a new grid structure only at the start of the run, which means that the models cannot be moved at any time. But because it only requires a single merge operation, it is more efficient than dynamic batching. The downside is that it often takes more memory to store the merged geometry. This is because, if some objects share the same mesh before the static batch, each object in memory corresponds to a copy of the mesh, i.e. one mesh becomes multiple grids and then sent to the GPU. This can be a performance bottleneck if you have a lot of objects that use the same grid. For example, using static batching in a forest with 1000 identical tree models would use 1000 times times more memory, which would have a serious memory impact. At this time, the solution sideThe method is either tolerated, either using dynamic batching, or by writing a batch method on its own. The implementation of the static batch is very simple, just tick the static checkbox on the object panel (we only need to tick batching static) as shown in. In the internal implementation, Unity first transforms these static objects into world space and then constructs a larger vertex and all caches for them. For objects that use the same material, unity only needs to invoke a draw call to draw all the objects. For objects that use different materials, static batching can also improve rendering performance. It is still necessary to call multiple draw calls after these objects. But static batching can reduce the state transitions between these draw call, which are often time-consuming operations. As you can see from the previous content, both dynamic batches and static batches require that the same material be shared between the models. But there will always be different rendering properties between the different models, and we need some strategies to merge the materials as much as possible. If only the textures used between the two materials are different, we can combine the textures into a larger texture, a larger texture called an atlas. Once the same texture is used, we can use the same material, and then use different sample coordinates to sample the texture. But sometimes the textures are different, and different objects have some minor parameter changes on the material, for example, different colors and some floating-point properties. However, whether it is a dynamic batch or a static batch, they are premised on the use of a material. Are the same, instead of using the same shader material, which means that the material they point to must be the same entity. This means that as long as we adjust the parameters, it will affect all objects that use the material. What about a small adjustment? A common approach is to use the mesh's vertex data to store these parameters. As I said earlier, after the batch of my retreat will be processed into a larger VBO sent to GPU,VBO data can be passed as input to the vertex shader, so we can skillfully control the data in the VBO, so as to achieve different effects. One example is that all trees in a forest scene use the same material, and we want them to reduce draw call by batching, but different trees may have different colors. At this point, we can use the color data of the vertex of the grid to adjust. It is important to note that if we need to access the shared material in the script, we should use renderer.shaderdmaterial to make sure that the material that is shared with other objects is modified, but this means that the modification is applied to all objects that use the material. Another similar API is renderer.material, if you use renderer.material to modify the material, UniTy creates a copy of the material, which destroys the application of the batch on the object. When choosing whether to use dynamic batching or static batching, the recommendation is: 1) use static batching whenever possible, but take time to be careful with memory consumption, and remember that objects that have been statically batched cannot be moved again. 2) If you cannot perform static batching and use dynamic batching, be careful with the various limitations mentioned above. 3) for small items in the game, such as coins that can be picked up, you can use dynamic batching. 4) For such objects containing animations, we cannot use static batching in all, but if there is a fixed part, it can be identified as "static" in addition to the above hints, there are some areas to be aware of when using batch processing. Because batch processing needs to transform multiple models into world space and then merge them, if there are some operations based on the coordinates in the model space in shader, the results are often incorrect. One workaround is to use the disablebatching tag in shader to force the shader material not to be batched. Another consideration is that objects that use translucent materials often need to use a strict backward-forward drawing order to ensure the correctness of the blending of the transparency. For these objects, unity will first guarantee the order in which they are drawn, and then try to batch them. This means that batches cannot be successfully applied on these objects when the drawing order is not met.  reduce the number of vertices that need to be processed3 common vertex optimization strategies. 1) optimized geometry in many modeling software macros, there are corresponding optimization options, you can automatically optimize the grid structure. 2) The model's LOD technique principle is that when an object is far away from the camera, many details of the model are beyond my awareness. As a result, LOD allows you to reduce the number of patches on the model when the object gradually principles the camera, thereby improving performance. In unity, we can use LOD Group components to construct an LOD for an object. We need to prepare multiple models with different details for the same object, and then assign them to different levels in the Lod Group components, and Unity will automatically determine which level of model is needed at the current location. 3) Occlusion culling technology occlusion culling can be used to eliminate objects that are not visible behind other objects, which means that resources are not wasted on calculating those unseen vertices for improved performance. We need to distinguish between occlusion culling and the camera's frustum culling. The frustum culling only removes objects that are not in the camera's field of view, but does not determine if any objects in the field of view are blocked by other objects. Occlusion culling uses a virtual X-ray machine to traverse the scene, building a hierarchy of potentially visible object geometries. At run time, each camera will use this data to identify which objects are visible, and those that are blocked by other objects are not visible. Using occlusion culling not only reduces the number of vertices processed, but also reduces overdraw. To use occlusion culling technology in unity, we need to do a series of additional processing work.reduce the number of slices that need to be processedAnother cause of GPU bottlenecks is the need to process too many slices. This part of the optimization is focused on reducing overdraw. Simply put, Overdraw is worth the same pixel being drawn multiple times. 1) Control the drawing order as the depth test exists, if we can guarantee that the object is drawn from the previous one, then the overdraw can be reduced to a great extent. This is because the objects that are drawn behind cannot be tested in depth, so the subsequent rendering is not done. In unity, objects with fewer than 2500 render queues (such as "Background", "Geometry" and "alphatest") are considered opaque objects, which are generally drawn from the past and are used in other queues (such as " Transparent "" Overlay ") objects are drawn from the back and forth. This means that we can set the object's queue to the render queue of the opaque object as much as possible, while avoiding the use of semitransparent queues. Also, we can take advantage of Unity's render queue to control the drawing order. For example, set the queue to "geometry+1". 2) always be alert to transparent objects for translucent objects, since they do not have a deep write on, they must be rendered from behind if the correct rendering is to be achieved. This means that translucent objects will almost certainly cause overdraw. For example, GUI objects, most of them are set to translucent objects, if the screen GUI occupies too much proportion. And the main camera is not adjusted but the entire screen is projected, then the GUI will cause a lot of overdraw. Therefore, we minimize the area occupied by the GUI in the window. You can also draw the GUI and the three-dimensional scene to the different cameras, which is responsible for the three-dimensional scene of the camera's view range as far as possible and the GUI overlap. On mobile platforms, transparency testing can also affect game performance. Although the transparency test did not close the depth test, it was implemented using discard or clip operations that would invalidate some of the hardware's optimization policies. 3) reduce real-time lighting and shadow real-time lighting is a very expensive operation for mobile platforms. If you have too many point lights in your scene, and you use multiple pass shader, you may have degraded performance. We can use baking techniques to bake light into a light texture in advance, and then only need to sample the light from texture samples at run time.Bandwidth SavingsAs mentioned before, using a texture Atlas can help us reduce the number of draw calls, and the size of these textures is also an issue to consider. It is important to note that the aspect ratio of all textures is preferably square, and the length-width value is preferably an integer power of 2. This is because there are many optimization strategies that can only be maximized at this time. In Unity5, even if the length-to-width value of the texture we import is not an integer power of 2, unity will automatically swap the long-width to the power of an integer from its nearest 2. However, we should keep this rule in mind when making art resources, and prevent bad effects due to scaling. In addition, we should use the multi-level fading texture technique and texture compression as much as possible. In unity, we can view the individual import properties of a texture through the texture import panel. By setting the texture type to advanced, you can customize many options, such as whether to create a multistage gradient texture (mipmaps). As shown, when the Generate MIP Maps option is checked, unity creates a texture pyramid with a large number of small textures of different sizes for the same texture. Texture compression can also save bandwidth. But for platforms like Android, where there are many different architectures of GPUs, texture compression becomes a bit more complicated because different GPU architectures have their own texture compression format. Fortunately, unity can choose different compression formats based on different devices, and we just need to set the texture compression format to auto-compress. However, GUI type textures are also an exception, and some times we don't want to compress these textures because of the quality requirements. High screen resolution is also a cause of performance degradation, especially for many low-end phones, in addition to high resolution and other hardware conditions are not satisfactory, this is the game performance of the two bottlenecks: too large screen resolution and bad GPU. Therefore, we may need to scale for specific and resolution. Of course, this may cause the game to degrade, but the performance and picture need to be balanced.reduction of computational complexityShader's LOD technology can control the level of Shader used. The principle is that only the LOD value of shader is less than a set value, the shader will be used, and objects with shader that exceed the set value will not be rendered. We typically use a statement similar to the following in Subshader to indicate the LOD value of the shader.
    1. subshader{
    2. tags{"Rendertype" = "Opaque"}
    3. LOD 200
    4. }
We can also see the LOD values for this shader on the import panel of Unity shader. By default, the Lod you allow is infinitely large. This means that any shader supported by the current graphics card can be used. However, in some cases, we may need to remove some shader rendering that uses complex computations. At this point, we can use Shader.maximumlod or Shader.globalmaximumlod to set the allowable LOD values.
Unity's built-in shader uses different LOD values, for example, Lod for diffuse is 200, and bumped specular Lod is 400 code optimization: First use low-precision floating-point values as much as possible. It is also important to note that we should try to avoid the conversion between different precision. And try not to use full screen post-processing effects. Do not use branch statements and loop statements as much as possible. Avoid using more complex mathematical operations like sin, tan, pow, and log, as much as possible. Use a lookup table to replace it. Try not to use discard

Unity Shader Getting Started Essentials learning notes-16th. Rendering Optimization technology in unity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.