<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by UWA on Medium]]></title>
        <description><![CDATA[Stories by UWA on Medium]]></description>
        <link>https://medium.com/@uwa4d?source=rss-2a1f9609c2cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VwaaGu8zGs6f0ZAb.jpg</url>
            <title>Stories by UWA on Medium</title>
            <link>https://medium.com/@uwa4d?source=rss-2a1f9609c2cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:25:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uwa4d/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction of the Raytracing Technology]]></title>
            <link>https://medium.com/@uwa4d/introduction-of-the-raytracing-technology-8ce972f5a433?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ce972f5a433</guid>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-engine]]></category>
            <category><![CDATA[unreal]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 07:43:16 GMT</pubDate>
            <atom:updated>2022-12-16T07:43:16.006Z</atom:updated>
            <content:encoded><![CDATA[<p>(Read the full contents: <a href="https://blog.en.uwa4d.com/2022/12/14/introduction-of-the-raytracing-technology-part-1/">https://blog.en.uwa4d.com/2022/12/14/introduction-of-the-raytracing-technology-part-1/</a>)</p><p>In this article, we will introduce the family tree of ray tracing categories and their common parts, and then we will dissect each of them in detail. This article will be divided into two parts for a better reading experience.</p><p>Practitioners in the Graphics field have introduced this idea from the fields of neutron transport, heat transfer, and illumination engineering. As these concepts are studied in many fields, the terminology leading to ray tracing is evolving, and sometimes diverging between and within individual disciplines, which can lead to confusion about the terminology. Therefore, before introducing the concept of ray tracing, we need to clarify the concepts of these terms. Almost all modern ray tracers use recursion and Monte Carlo methods, but few people now call them the “recursive Monte Carlo” method.</p><h3>1. The History of Ray Tracing</h3><ul><li><strong>Ray Casting</strong>, 1968. Arthur Appel.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*zwqh07tRKBINU9Q3.png" /></figure><ul><li><strong>Whitted Ray Tracing</strong>, 1980. Whitted, Kay, and Greenberg proposed the use of recursive ray tracing to describe accurate refraction and reflection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*grnWPXc-Q06rjLV4.png" /></figure><ul><li><strong>Distributed Ray Tracing</strong>, 1984. Cook et al. proposed distributed or distribution ray tracing (DRT). However, this approach is often referred to as stochastic ray tracing to avoid confusion with distributed processing. Both it and path tracing use the Monte Carlo method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*vFa8VjKavSwthTXI.png" /></figure><ul><li><strong>Path Tracing</strong>, 1986. Two important algorithms were introduced. Kajiya called the integral transport equation the rendering equation. The rendering equation he proposed has become the mathematical basis for almost all global illumination algorithms so far. In the same paper, he also proposed the most primitive path-tracing algorithm.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*fg20JEBohCoOwKQ6.png" /></figure><ul><li><strong>Bidirectional Path Tracing</strong> (BidirectionalPath Tracing) was proposed by Lafortune and Willems, and Veach gave a detailed description of bidirectional path tracing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*F_RWlWYqx6-uvMCd.png" /></figure><ul><li><strong>Metropolis Light Transport</strong>,1997. Veach first introduced the Metropolis sampling method, which was first applied in the field of computational physics, into graphics.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*gqk3C0ErQZzagrPx.png" /></figure><ul><li><strong>Energy Redistribution Path Tracing</strong>, 2005</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_T1ZzADB8NDiNstx.png" /></figure><ul><li><strong>Manifold Exploration</strong>, 2012</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*b0T3GHMHXDTb3Gd8.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ce972f5a433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity Mobile Game Performance Optimization: CPU Time Cost Optimization Divided by Engine Modules]]></title>
            <link>https://medium.com/@uwa4d/unity-mobile-game-performance-optimization-cpu-time-cost-optimization-divided-by-engine-modules-73e9077f127b?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/73e9077f127b</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[game-optimization]]></category>
            <category><![CDATA[unity-game-development]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 10:23:17 GMT</pubDate>
            <atom:updated>2022-12-13T10:23:17.290Z</atom:updated>
            <content:encoded><![CDATA[<p>“Unity Mobile Game Performance Optimization Series” starts from some basic discussions on Unity mobile game optimization, exemplifies and analyzes some of the most common performance problems in mobile game projects developed based on Unity in recent years, and shows how to use it. UWA’s performance detection tools identify and address these issues. The full series will cover the basic logic of performance optimization, UWA performance detection tools, and common performance problems, hoping to provide Unity developers with more efficient R&amp;D methods and practical experience.</p><p>Today, we will introduce the third chapter: CPU time-consuming optimization divided by engine modules with a total of 9 sections, including rendering, UI, physics, animation, particle system, loading, CPU Stack, Lua, etc.</p><p>The first part of the article “Introduction to Unity Mobile Game Performance Optimization Sheet Music” and the second part “Unity Mobile Game Performance Optimization Sheet Music for Common Game Memory Control” can be reviewed here, and the full content can be viewed at UWA Academy.</p><h3>1. Overview</h3><h3>1.1 Module Division</h3><p>UWA divides the functions with clear work content and generally high time-consuming ratio in the CPU into rendering, UI, physics, animation, particles, loading, logic, and other modules. But it doesn’t mean that these modules work independently of each other. For example, the performance pressure of rendering modules is bound to be affected by complex UI and particles, and many operations of loading modules are actually called and completed on the logic end.</p><p>Dividing modules helps us identify problems and find key issues. At the same time, it is also necessary to build connections between modules, which helps to solve problems more efficiently.</p><h3>1.2 CPU Time Bottleneck</h3><p>When a project has a low frame rate and obvious freeze due to CPU performance bottleneck, how to find the source of the main problem causing the performance bottleneck becomes the key. Although we have sorted out the main modules in the engine, the problems that will occur between each module are still indistinguishable, and their contribution to the CPU performance pressure is not the same. Then we need to have an accurate understanding of what kind of cost can be considered a potential performance bottleneck.</p><p>In the mobile project, our goal of CPU performance optimization is to run a smooth game process of 30 fps most of the time on low-end and mid-range models. In order to achieve this goal, simply do a division to get our CPU time average should be controlled below 33ms. Of course, this does not mean that projects whose CPU average is already below 33ms have controlled their CPU time well. The performance pressure points are different during the running of the game. There may be very little pressure in a series of UI interfaces, but in turn, the frame rate in the most important battle scene in the game is very low, or there are a lot of crashes or pauses with hundreds of milliseconds or even a few seconds, and the final average is still less than 33ms.</p><p>For this reason, UWA believes that in a test, when the number of frames consuming 33ms and above accounts for less than 10% of the total number of frames, it can be considered that the overall CPU performance of the project is controlled within the normal range. The higher the proportion, the more serious the CPU performance bottleneck of the current project.</p><p>The above discussion mainly revolves around our macro optimization goal of CPU performance. Like memory, we still need to combine the specific data of specific modules to troubleshoot and solve the actual problems in the project.</p><h3>2. Rendering Module</h3><p>For more comprehensive content related to the optimization of the rendering module, please refer to “<a href="https://blog.en.uwa4d.com/2021/12/30/unity-performance-optimization-rendering-module/">Unity Performance Optimization Series — Rendering Module</a>“.</p><h3>2.1 Multi-threaded Rendering</h3><p>In general, in the single-threaded rendering process, during each frame of the game, the main thread (CPU1) executes Update first, and performs a large number of logical updates here, such as game AI, collision detection, and animation updates; then executes Render, and makes rendering-related instruction calls here. While rendering, the main thread needs to call the graphics API to update the rendering state, such as setting Shader, texture, matrix and alpha fusion, etc., and then execute DrawCall. All these graphics API calls interact with the driver layer, and the driver layer maintains all the rendering states, calls to these APIs may trigger the rendering state of the driver layer to change, resulting in a freeze. Since the state of the driver layer is transparent to the upper-layer call, whether the freeze will occur and the duration of the freeze is unknown to the caller of the API (CPU1). At this time, other CPUs may be in an idle waiting state, resulting in waste. Therefore, the rendering part can be extracted and placed in other CPUs to form a separate rendering thread, which is performed at the same time as the logical thread to reduce the main thread jamming.</p><p>The general implementation process is that the graphics API called in the main thread is encapsulated into a command and submitted to the rendering queue, which saves the overhead of calling the graphics API in the main thread, thereby improving the frame rate; the rendering thread obtains from the rendering queue. Rendering instructions and executing calls to the graphics API to interact with the driver layer. This part of the interaction takes time from the main thread to the rendering thread.</p><p>Unity supports Multithreaded Rendering in Project Settings and enables Multithreaded Rendering by default. It is generally recommended to keep it enabled. In the large amount of test data of UWA, it is still found that some projects have turned off multi-threaded rendering. When multi-threaded rendering is turned on, the time spent by the CPU waiting for the GPU to complete the work will be counted in the Gfx.WaitForPresent function, and when multi-threaded rendering is turned off, this part of the time will be counted in Graphics.PresentAndSync. Therefore, whether the Gfx.WaitForPresent function time-consuming is counted in the project as a basis for judging whether multi-threaded rendering is enabled. In particular, during the development and testing phases of the project, you can consider temporarily turning off multi-threaded rendering and packaging the test, so as to more intuitively reflect the performance bottleneck of the rendering module.</p><p>For projects in which multi-threaded rendering is normally enabled, the time-consuming trend of Gfx.WaitForPresent also has considerable reference significance. The greater the local GPU pressure in the test, the longer the CPU waits for the GPU to complete the work, and the longer the time required for Gfx.WaitForPresent. Therefore, when Gfx.WaitForPresent lasts for tens or even hundreds of milliseconds, which means that the GPU pressure of the corresponding scene is relatively high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kt-zpUnJ9HAENzJi.png" /></figure><p>In addition, according to a large number of UWA projects and testing experience, excessive GPU pressure will also increase the overall time-consuming of the main functions on the CPU side of the rendering module (Camera.Render and RenderPipelineManager.DoRenderLoop_Internal). We’ll discuss optimizations specifically for the GPU part at the end.</p><h3>2.2 The number of Triangles rendered on the same screen</h3><p>The two most basic parameters that affect rendering efficiency are undoubtedly Triangle and DrawCall.</p><p>Usually, the number of Triangles is proportional to the GPU rendering time, and for most projects, the number of opaque Triangles is often much larger than that of translucent Triangles, which needs special attention. UWA generally recommends that the number of rendered Triangles on the same screen be controlled within 250,000 on low-end models, and it is not recommended to exceed 600,000 even for high-end models. When you use the tool to find that the number of locally rendered patches on the same screen is too high, you can use the Frame Debugger to check the rendering objects of keyframes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5WGJAO3QqMnOUcJY.png" /></figure><p>A common optimization scheme is that the number of meshes of mesh resources needs to be strictly controlled in production, especially for some character and terrain models with meshes having tens of thousands of faces or more; Another good method is to reduce the number of meshes in the scene through LOD tools — such as using low poly on low-end machines, reducing the display of relatively unimportant small objects in the scene — and thus reducing the rendering overhead.</p><p>It should be pointed out that the number of Triangles concerned and counted by the UWA tool is not the number of Triangles of the scene model in the current frame, but the Triangles rendered in the current frame. Its value is not only related to the number of Triangles used for the model, but also to the rendering. The number of times is related, which more intuitively reflects the rendering pressure caused by the number of tiles rendered on the same screen. For example, if the number of Triangles of the mesh model in the scene is 10,000, and the Shader used has 2 rendering passes, or 2 cameras render it at the same time, or one of the post-processing effects such as SSAO and Reflection is used, then the Triangle value shown here will be 20,000. Therefore, on low-end devices, you should be strictly wary of these operations, which will double the number of rendered patches on the same screen.</p><h3>2.3 Batch (DrawCall)</h3><p>In Unity, we need to distinguish DrawCall and Batch. There will be multiple DrawCalls in a Batch. When this happens, we tend to care more about the number of Batches, because it is the unit that submits rendering data to the GPU, and it is also the real object we need to optimize and control the number of.</p><p>There are usually four ways to reduce batches: dynamic batching, static batching, SRP Batcher, and GPU Instancing. The following briefly summarizes the batching conditions, advantages, and disadvantages of static batching, SRP Batcher, and GPU Instancing.</p><p><strong>(1) Static Batching</strong></p><p>Condition: Different Mesh, just use the same shader.</p><p>Advantages: Binding saves vertex information; saves geometry information transfer; when adjacent materials are the same, saves material transfer.</p><p>Disadvantages: When merging offline, if there are duplicate resources in the merged Mesh, it is easy to make the merged package larger; when merging at runtime, the process of generating Combine Mesh will cause a short-term CPU peak; There are duplicate resources, which will increase the memory footprint after merging.</p><p><strong>(2) SRP Batcher</strong></p><p>Condition: Different Mesh, as long as the same Shader and the same variant are used.</p><p>Advantages: saves the write operation of the Uniform Buffer; divides the batch according to the Shader, generates the Uniform Buffer in advance, and there is no CPU Write inside the Batch.</p><p>Disadvantages: Constant Buffer (CBuffer) memory fixed overhead; MaterialPropertyBlock is not supported.</p><p><strong>(3) GPU Instancing</strong></p><p>Condition: The same Mesh and the same shader is used.</p><p>Advantages: It is suitable for the needs of rendering a large number of monsters of the same kind, and it can reduce the time-consuming of animation modules while batching.</p><p>Disadvantages: There may be negative optimizations, but instead make DrawCall rise; Instancing is sometimes disrupted, and you can use API rendering in groups.</p><h3>2.4 Shader.CreateGPUProgram</h3><p>This API often appears in the stack of the main function of the render module and causes most function spikes in the render module. It is the time-consuming generated when the Shader is rendered for the first time, and its time-consuming is related to the complexity of rendering the Shader. We should pay attention when it is called during gameplay and causes high time-consuming spikes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KEWStwtyHzRVMoiG.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ym_zH9UgbAaalL-P.png" /></figure><p>In this regard, we can collect the variants to be used by Shader through ShaderVariantCollection and packaging AssetBundle. After loading the ShaderVariantCollection resource into the memory, trigger Shader.CreateGPUProgram by calling ShaderVariantCollection.WarmUp in the early game scene, and cache the SVC, so as to avoid triggering this API call when the game is running, and avoid local high CPU consumption Time.</p><p>However, even projects that have done the above operations often detect occasional spikes in the API’s time consumption during runtime, indicating that there are some “fish that slip through the net”. Developers can combine the Timeline mode of Profiler and select the frame that triggers the call to Shader.CreateGPUProgram to check which Shader triggers the API. You can refer to “<a href="https://blog.en.uwa4d.com/2022/03/19/an-idea-of-shader-variant-collection-and-packaging-compilation-optimization/">An idea of Shader variant collection and packaging compilation optimization</a>“.</p><h3>2.5 Culling</h3><p>In most cases, the self-cost of Culling is time-consuming and inconspicuous, and its significance is to reflect some rendering-related problems.</p><p><strong>(1) The number of cameras is large</strong></p><p>When the stack of the main function of the rendering module takes a relatively high proportion of Culling time (about 10%-20% in general projects).</p><p><strong>(2) There are many small objects in the scene</strong></p><p>Culling time is closely related to the number of GameObject widgets in the scene. In this case, it is recommended that the R&amp;D team optimize the scene production method and pay attention to whether there are too many small objects in the scene, which will increase the time-consuming of Culling. You can consider using dynamic loading, block display, or methods such as Culling Group and Culling Distance to optimize the time-consuming of Culling.</p><p><strong>(3) Occlusion Culling</strong></p><p>If the project uses multi-threaded rendering and Occlusion Culling is turned on, it usually causes the pressure on the sub-thread to be too high and the overall Culling is too high.</p><p>Since Occlusion Culling needs to calculate the occlusion relationship according to the objects in the scene, although Occlusion Culling reduces the rendering consumption, its own performance overhead is also worth noting, and it is not necessarily applicable to all scenes. In this case, it is recommended that developers selectively disable part of Occlusion Culling to test the overall consumption of rendering data for comparison, and then decide whether to enable this function.</p><p><strong>(4) Bounding box update</strong></p><p>The FinalizeUpdateRendererBoundingVolumes that sometimes appear in Culling’s stack are time-consuming for bounding box updates. Commonly seen in the bounding box update of Skinned Mesh and particle systems. If the API appears frequently, you need to use screenshots to check whether there are a large number of Skinned Mesh updates or more complex particle system updates at this time.</p><p><strong>(5) PostProcessingLayer.OnPreCull/WaterReflection.OnWillRenderObject</strong></p><p>The method PostProcessLayer.OnPreCull is related to the PostProcessing Stack used in the project. You can add the static variable GlobalNeedUpdateSettings in PostProcessManager.cs, and updateSettings by setting PostProcessManager.GlobalNeedUpdateSettings to true when cutting the scene. In this way, you can avoid doing the UpdateSettings operation every frame, thereby reducing part of the time-consuming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*GgzRRRXDtKzkVBXu.png" /></figure><p>It takes a high CPU Time to use WaterReflection.OnWillRenderObject that is related to the water surface reflection effect in the project. If its CPU Time is high, you can check whether there is room for optimization in the implementation method, such as removing some unnecessary particles, small objects, etc. reflection rendering.</p><p>Read more about the optimization of other modules: <a href="https://blog.en.uwa4d.com/2022/12/07/unity-mobile-game-performance-optimization-cpu-time-cost-optimization-divided-by-engine-modules/">https://blog.en.uwa4d.com/2022/12/07/unity-mobile-game-performance-optimization-cpu-time-cost-optimization-divided-by-engine-modules/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73e9077f127b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction of the ASTC Texture Compression]]></title>
            <link>https://medium.com/@uwa4d/introduction-of-the-astc-texture-compression-6aa748e0b9e7?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aa748e0b9e7</guid>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[texture]]></category>
            <category><![CDATA[file-compression]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Wed, 30 Nov 2022 10:02:38 GMT</pubDate>
            <atom:updated>2022-11-30T10:02:38.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lhlqVbSYOPAKqzEuPnDPg.png" /></figure><p>This article gives an overview of the different ASTC Texture Compression formats available and shows the quality and file size that can be expected for gradients, normal maps, as well as facial albedo textures.</p><p><a href="https://blog.en.uwa4d.com/2022/11/23/introduction-of-the-astc-texture-compression-format/">https://blog.en.uwa4d.com/2022/11/23/introduction-of-the-astc-texture-compression-format/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aa748e0b9e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overview of Unity Game Memory Distribution]]></title>
            <link>https://medium.com/@uwa4d/overview-of-unity-game-memory-distribution-a2e13197e9ff?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e13197e9ff</guid>
            <category><![CDATA[ios-game-development]]></category>
            <category><![CDATA[unity-game-development]]></category>
            <category><![CDATA[in-game-memory]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 10:24:36 GMT</pubDate>
            <atom:updated>2022-11-24T10:24:36.389Z</atom:updated>
            <content:encoded><![CDATA[<p>Memory is a very important aspect of game performance optimization. Especially for mobile devices, when hardware devices are limited, users of such models need to be covered and compatible. Games are developed on PC or Mac but ultimately run (mostly) on mobile (only Android and iOS are considered), if the memory is not well controlled, it will easily be blocked by the mobile OS due to OOM.</p><p>But in fact, under different operating systems, the memory management strategies are quite different. There are more professional memory analysis tools for each platform, but these tools will cause statistical deviations due to different platforms, different statistical strategies, and even different system versions. For example, XCode’s Memory Report page is different from its own statistics under Instrument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*5ZFDs-5rnsErECql.png" /></figure><p>There are also some wrapping losses, such as a Texture, most of its data memory will enter the Native, but it still needs to wrap some Classes for the logic layer to call, and this part will enter the Mono heap. Another example is, part of the Const data of the System Framework will enter Clean memory, while another part will enter Dirty, which may be further compressed into Swap memory by the system.</p><h3>1. The Memory from the Perspective of Unity</h3><p>Memory analysis from the perspective of Unity focuses more on the memory managed by Unity itself (in fact, it is not allocated by it and cannot be managed), but a Unity game actually runs on a platform (such as Android or iOS). ). Then in addition to the memory allocated by Unity itself, there is also a part from the shared library of the system. Furthermore, a complex Unity game often refers to many third-party plug-ins, and the native memory allocated by these plug-ins is beyond Unity’s consideration.</p><p><strong>1.1 The Origin of Memory</strong></p><p>Actually, Unity can be regarded as a game engine developed using C++, which uses the scripting virtual machine of .net. Unity allocates memory for native (C++) objects and virtual machines from virtual memory. Similarly, memory allocations for third-party plugins are also in virtual memory pools.</p><p>Native Memory is the part of virtual memory that is used to allocate memory pages for all required objects, including the Mono Heap.</p><p>As mentioned above, the Mono heap is a portion of native memory that is specially allocated for the needs of the virtual machine. It contains all types of managed memory allocated by C#, and the managed object of this memory is the Garbage Collector, or GC for short.</p><p>There are several specialized allocators inside Unity, which are responsible for managing the short-term and long-term allocation needs of virtual memory. All Unity assets are stored in native memory. But these assets will be lightly packaged into Class for logical access and invocation. That is to say, if we create a Texture in C#, most of its raw data (RawData) exists in the Native memory, and a small Class object will enter the virtual machine, that is, the Mono heap.</p><p><strong>1.2 Reserved/Used</strong></p><p>Memory paging (mostly 16K/page on iOS) is the smallest unit of memory management. When Unity needs to apply for memory, it will apply in block mode (several pages). If a page is still Empty after several GCs (8 times for iOS), it will be freed and the actual physical memory will be returned to the physical memory.</p><p>But since Unity manages memory in virtual memory, the address of the virtual space will not be returned, so it becomes “Reserved”. That is to say, these Reserved address spaces can no longer be allocated repeatedly by Unity.</p><p>Therefore, on a 32-bit operating system, if the virtual memory address is frequently allocated and released, the address space will be exhausted and the system will kill it.</p><p><strong>1.3 GC and Memory Fragmentation</strong></p><p>The physical memory requested by the Mono heap is continuous, and it is very time-consuming for the Mono heap to apply extended memory to the operating system. So in most cases, the Mono heap will try to keep the physical memory that it has applied for to prevent it from being used later. So in addition to the virtual space address, the memory requested by the Mono heap also has the concept of Reserved.</p><p>Since the allocation unit of memory is page, that is to say, if a page only stores an int value, the page will still be represented as Used, and its physical memory will not be released. Of course, if a certain memory is larger than one page, multiple consecutive pages will be applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*xvSd7OEqozSv2006.png" /></figure><p>If at some point, the heap memory is GC, then the physical address of this part will be vacated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*mtbI-rlkCwHUVXDh.png" /></figure><p>The next time you need to apply for heap memory, the Mono heap will first check whether there is continuous space in the current heap to accommodate this memory application. If it is not enough, a GC will be performed, which is the GC operation we hate the most. Afterward, if such a block is still not found, the Mono heap will perform a memory expansion operation and ask the operating system for more memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*knO2XJI06Ql9La5p.png" /></figure><p>And these vacated, but can not be reused memory will become memory fragmentation. They can neither be exploited nor destroyed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*kGG0FUcWQtieDYUQ.png" /></figure><p>For example, in the above picture, the relationship between Mono Reserved/Used:<br><strong>Reserved size</strong> : 256KB + 256KB + 128KB = 640KB<br><strong>Used</strong>: 88 562B</p><p><strong>1.4 Profiler Simple View</strong></p><p>When using Unity’s Profiler for memory analysis, in Simple mode, you can see a screenshot similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VV5TGF4Df4rQqrwB.png" /></figure><p>Shown here is the virtual memory managed by Unity itself.</p><p>This is obvious, the first row shows Used memory, and the second row shows Reserved.</p><ul><li>Total:</li><li>Unity: All the memory requested and managed by Unity minus &lt;Profiler&gt;, &lt;FMOD&gt;, and &lt;Video&gt;. That is, Mono Heap is included.</li><li>Mono: Managed heap memory.</li><li>GfxDriver: GPU memory cost is mainly composed of Texture, Vertex buffer, and index buffer.<br>But Render Targets are not included. <br>(Does not include driver layers for other platforms)</li><li>FMOD:<br>Memory requested by FMOD.</li><li>Video:<br>Memory required for video file playback.</li><li>Profiler: Profiler’s own cost.</li></ul><p>The Total Reserved here is also not the exact value of the game’s virtual memory, because:</p><ul><li>It does not include the size of the game’s binary executable, loaded libraries, and frameworks.</li><li>The GfxDriver value does not include the render target and various buffers allocated by the driver layer.</li><li>The profiler only sees assignments made by Unity code, not third-party native plugins and OS assignments.</li></ul><p><strong>1.5 Profiler Detailed</strong></p><p>The detailed sample view is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9E01_n_9b0mUE-P3.png" /></figure><p>It shows the detailed allocation of virtual memory.</p><ul><li><strong>Assets</strong> — Total assets currently loaded from scenes, Resources, and Asset Bundles.</li><li><strong>Built-in</strong> Resources — Unity Editor resources or Unity default resources.</li><li><strong>Not Saved</strong> — GameObjects marked as DontSaved.</li><li><strong>Scene Memory</strong> — GameObject and its attached Components.</li><li><strong>Other</strong> — Others that are not in the above categories.</li></ul><p>Most of the time, hot issues in memory can be found in Assets. For example, find out the leaks of textures and resources by the number of references (generally leaked resources do not have the number of references).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xLHmqrOGdcN6uWI9.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0xDXt2QeEiB0v2OW.png" /></figure><p>Here I want to pay attention to the Objects item in the Other directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZENqduB6IS9nz1o0.png" /></figure><p>Actually, this value is caused by some bug. This item represents various objects inherited from Object, including textures, Meshes, and so on. They are disconnected from the actual object at some point and can be ignored.</p><ul><li><strong>System.ExecutableAndDlls</strong>: This is Unity’s guess value.<br>It tries to guess the memory consumed by the loaded binary by summing up the file size.</li><li><strong>ShaderLab</strong>: These are assignments related to compiling shaders.<br>Shaders themselves have their own object root and are listed under Shaders.</li></ul><p><strong>1.6 Limitations of Unity’s Perspective</strong></p><p>Unity’s memory analysis is far more than the built-in Profiler. We also use:</p><ul><li><strong>MemoryProfiler</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*fxmL3nHrtgyuIu7_.png" /></figure><ul><li><strong>MemoryProfiler Extension</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/0*xB_ywLNazbpJ6arQ.png" /></figure><p>But they all have the same problem, that is, relying on the Profiler API provided by Unity itself. In other words, although the tools differ in how they present data and operate, they measure the same results.</p><p>That is to say, the tools from the Unity perspective only see the allocation completed by the Unity code, and cannot see the allocation of third-party native plug-ins and operating systems.</p><p>However, a complete Unity project will eventually run on the platform, so it will have a large error with the statistical results of the platform’s memory analysis tool. In addition, it is difficult to grasp the real memory distribution and cost of Unity projects.</p><p>In this article, we will introduce the memory situation of Unity games on the iOS platform.</p><p>Click <a href="https://blog.en.uwa4d.com/2022/10/05/overview-of-unity-game-memory-distribution/">https://blog.en.uwa4d.com/2022/10/05/overview-of-unity-game-memory-distribution/</a> to read more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e13197e9ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Screen Post-processing Effects: Gamma Space and Linear Space]]></title>
            <link>https://medium.com/@uwa4d/screen-post-processing-effects-gamma-space-and-linear-space-8be1af3be554?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be1af3be554</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[unreal]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Thu, 17 Nov 2022 10:23:11 GMT</pubDate>
            <atom:updated>2022-11-17T10:23:11.822Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Origin of Gamma Space</h3><h3>Foreword</h3><p>What we are going to talk about next is related to the post-processing effects and the adjustment of colors. Before starting the main contents of the specific post-processing effects, we need to understand some basic knowledge, one of which is related to the final output display of colors. Next, we will learn about Gamma Space and Linear Space, including the origin of Gamma Correction, the specific application of Color Space in project development, Unity and Unreal engines.</p><p>We need to clarify a concept in the beginning: the current discussion on Gamma Space is based on the limited grayscale budget. The specific content will be explained in more detail later.</p><h3>CRT Display Theory</h3><p>In the not-so-distant past, the mainstream display at that time was the CRT (Cathode-ray tube) display, the full name of which is the cathode ray tube display:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sC9LupU_XB7nBA03.png" /></figure><p>(CRT Monitor)</p><p>For a CRT display: double the voltage, the brightness does not double. The output brightness and voltage are not linear, and the brightness increase is approximately equal to the 2.2 power of the voltage increase, so 2.2 is called the Gamma value of the CRT display, and the color of the CRT display is said to be in the Gamma2.2 space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Rz8flkkpmNwuBaXO.png" /></figure><p>Brightness and Voltage Formula</p><p>When the voltage changes linearly, compared to the real world, the brightness of the CRT display changes slowly in the dark area, resulting in a wider range of dark data and a darker overall picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6RXUqc8PR6XFA6yo.png" /></figure><p>And our goal is to see the normal brightness similar to the real world. Since the CRT display is in the Gamma 2.2 space, the brightness of the picture we input to the display needs to balance the influence of Gamma 2.2. This operation is called gamma correction (Gamma Correction), which is actually approximately equivalent to performing a 0.45th power operation so that the color is in the Gamma 0.45 space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/0*VYUd5NxzcqUF0Rvk.gif" /></figure><p>Gamma Correction</p><p>This allows the color to be restored to resemble the color in real physical space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A_OwUOtDj9lSEUkk.png" /></figure><h3>Theory of Grayscale Perception of the Human Eye</h3><p>On the other hand, in the real physical world, if the light intensity increases from 0 to 1, then the brightness increases linearly with it. But the human eye perceiving brightness is not linear. This point is demonstrated in the Weber-Fechner law: people’s perception of external stimuli is not linear, the increase of the sensory quantity lags behind the physical quantity, the physical quantity grows in geometric progression, and the psychological quantity grows in arithmetic progression. That is: when the brightness perceived by the human eye increases by one level, the light intensity actually increases several times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*2GPfx7tLWDRpOhg9.png" /></figure><p>With a simple mathematical simulation of this phenomenon, it can be considered that people’s psychological perception of brightness is similar to the Gamma 0.45 space curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HrDHtUE7jyexUdcp.png" /></figure><p>It can be seen that people are more sensitive to the perception of darkness. For example, in the same room, lighting in the dark and turning on a light after turning on a hundred lights, give people a completely different feeling of brightness change. Although in the real physical world, the amount of light intensity increases is the same.</p><p>Today’s mainstream pictures are 8 bits per channel, so each channel will have 256 grayscales, and the number of grayscales is relatively small. Because people are more sensitive to dark perception, we need more grayscales to store darker brightness. According to the corresponding relationship in the figure, it is assumed that the brightness of the light intensity in the real physical space is 0.2, and the human eye feels it as the brightness of 0.5, and this data is taken as the 128th grayscale (the middle grayscale). For the brightness perceived by the human eye, we equally divide the number of gray levels, but for the real physical space, the number of gray levels allocated in the 0~0.2 light intensity interval is more.</p><p>In this way, the grayscale is allocated. For the brightness of the light intensity of 0.2 in real physical space, the human eye perceives it as the brightness of 0.5, and the brightness perceived by the human eye is recorded as data. The brightness perceived by the human eye as 0.5 is transmitted to the display for display. For the CRT display, the voltage of 0.5 is adjusted by Gamma 2.2, which just shows the brightness of 0.2, which meets the needs of human vision. This is also the mainstream view on the generation of the Gamma color space: a wonderful coincidence, the error of the CRT monitor matches the perception of the human eye. In fact, the transformation of the human eye’s perception curve of brightness may be more complex, not as simple as the Gamma0.45 space curve. It may be due to this coincidence that a relatively simple and feasible method has been extracted to simulate the human eye’s perception curve of brightness.</p><p>Therefore, even if the current display voltage and brightness are basically linear, this rule is still followed, and the display Gamma value is set, the purpose is to display more brightness in the dark area so that the gray level of the dark area perceived by the human eye is equal to The number of gray levels in the bright area.</p><p>However, with the advancement of technology, one day each channel will be 32-bit so that each channel can have 4294967296 grayscales. With such a huge number of grayscales, the brightness that can be displayed is sufficient, so there is no need for Gamma. The corresponding brightness can be obtained by directly displaying the stored result. This is the premise mentioned at the beginning of this article: the grayscale budget is limited, and a reasonable allocation is required to ensure the brightness range.</p><h3>sRGB</h3><p>In order to match CRT monitors, so that pictures can be displayed on monitors with 8 bits per channel without conversion, HP and Microsoft designed a Standard Red Blue Green color space (sRGB color space) in 1996. Most image files these days are in this color space.</p><p>The sRGB color space corresponds to the space where Gamma0.45 is located, which is equivalent to performing a gamma correction on the color of the physical space. The color in the physical world is stored in the space where Gamma 0.45 is located. After adjustment by the monitor Gamma2.2, the result displayed on the real device is consistent with the color of the real physical space.</p><h3>Summary</h3><p>In this section, we introduce two mainstream views on the origin of Gamma Space, and understand the corresponding calculation methods and practical significance behind them. In the next section, we will talk about how it affects our work, and how we can apply it rationally.</p><h3>Linear Space Workflow</h3><h3>Gamma Space and Linear Space</h3><p>Due to the presence of Gamma Correction, we have a little trouble with the calculations in the render. For example, there is a nonlinear input of an sRGB image, and then the operation is performed in a linear space, and the final output result will deviate from the desired result.</p><p>Because the physical laws of the real world are calculated in linear space, the calculation in Shader is also calculated in linear space. For example, according to the previous curve, the brightness of the actual physical space light intensity is 0.2, and the human eye perceives it as brightness of 0.5. The results obtained by calculating according to 0.2 and calculating according to 0.5 are naturally different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hi_hgCHYVp10wFJQ.png" /></figure><h3>Lighting Display under Different Spaces in the Unity Engine</h3><p>Therefore, in order to ensure a more realistic and accurate restoration of the color of the real physical world, a better production process is to unify the input, calculation, and output in a linear space, then perform Gamma Correction and finally display it on the monitor.</p><p>First, we need to ensure that the input data is in linear space. For sRGB textures, we need to perform Remove Gamma Correction (perform a 2.2 power operation) to bring it back to linear space.</p><p>Next, perform operations through Shader, and this part of the calculation is in linear space.</p><p>Then, Gamma Correction is performed on the result, which is finally output through the display. This gives a result that is close to the real world.</p><p>Let’s take the grayscale value of 1 as an example, assuming that after the Shader operation, the output result is 0.9 times the input result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/0*Vu6pTyu728ycfUrC.png" /></figure><p>If it is located in Linear Space, after Remove Gamma Correction value is 1, then the calculate value in Shader to be 1*0.9=0.9, then perform Gamma Correction 0.9⁰.45=0.95, and finally display as 0.95².2=0.89.</p><p>If it is under Gamma Space, the calculated value in Shader is 1*0.9=0.9, and it is displayed on the display: 0.9².2=0.79.</p><p>It can be seen that the rendering result in Gamma Space is dark. The rendering results in Linear space are a bit brighter.</p><p>Click to learn its implementation in Unity and Unreal: <a href="https://blog.en.uwa4d.com/2022/09/27/screen-post-processing-effects-gamma-space-and-linear-space/">https://blog.en.uwa4d.com/2022/09/27/screen-post-processing-effects-gamma-space-and-linear-space/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be1af3be554" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity Mobile Game Performance Optimization Series: Introduction]]></title>
            <link>https://medium.com/@uwa4d/unity-mobile-game-performance-optimization-series-introduction-8aba39db10e5?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aba39db10e5</guid>
            <category><![CDATA[mobile-games]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 10:14:17 GMT</pubDate>
            <atom:updated>2022-11-16T10:14:17.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2fvOB6Bc-Af5FoTBfK71A.png" /></figure><p>“<a href="https://blog.en.uwa4d.com/2022/11/16/unity-mobile-game-performance-optimization-series-introduction/">Unity Mobile Game Performance Optimization Series</a>” starts from some basic discussions on Unity mobile game optimization, exemplifies and analyzes some of the most common performance problems in mobile game projects developed with Unity in recent years, and shows how to identify and resolve these issues by using UWA’s game performance monitoring tools. <strong>The content includes the basic logic of performance optimization, UWA performance detection tools, and common performance problems</strong>, hoping to provide Unity developers with more efficient R&amp;D methods and practical experience.</p><p>Today I would like to introduce the first part to you, which consists of five subsections.</p><ul><li>Game performance in the vision of players</li><li>Game performance that developers care about</li><li>How to identify the problem</li><li>How to fix the problem</li><li>How to continuously monitor performance</li></ul><h3>1. Game performance in the vision of players</h3><p>Any player will encounter similar questions when playing the game: Why does the game crash after I play for a while? Why is my game so laggy? Why is my phone so hot? Why is my phone battery draining so fast?</p><p>For players, it has nothing to do with whether the art of the game itself is excellent and whether the gameplay is interesting. When these questions arise, the game experience will naturally deteriorate, and it will inevitably lead to a decrease in stickiness. This is a result that every game developer does not want to see.</p><p>The truth is that for the mobile game market we are focusing on today, the performance of various hardware models on the domestic market has a wide range; if the project wants to support a bigger market, the performance pressure that the project has to bear is often greater. So, how to let players with different hardware devices, especially those who have access to our game projects through mid-to-low-end devices, can also experience the game content smoothly and smoothly, which is one of our main goals.</p><h3>2. Game performance that developers care about</h3><p>In the development process of game projects, a very common phenomenon is: for a small-scale or inexperienced development team, in the middle and early stages of a new project, they often put all their energy into implementing functions, while ignoring performance optimization. After testing in the middle and late stages of the game, or even near the launch, it was discovered that the project was filled with a large number of serious performance problems, which affected the normal experience of the game, but they didn’t know where to start optimizing the game performance, and the time was very embarrassing. It is enough to see that performance issues are an important lifeline for a game project. Developers need to establish a good sense of optimization and optimize the knowledge system so that the project can avoid detours.</p><p>Different from the player’s perspective, UWA believes that from the perspective of developers, it should be mainly divided into three categories: memory, CPU and GPU. question. The main content of this article aims to exemplify and discuss common and typical problems in these three categories, so as to form an overview of mobile game performance optimization.</p><p>Then, since several performance problems have been found, how troubleshooting and solving the problem have become the two most critical steps.</p><h3>3. How to identify the problem</h3><p>The first major step after a performance problem is discovered is to identify the cause.</p><p>For example, when our game project runs for a long time, it will crash. Is it because our caching strategy is not done well or there is redundancy, which leads to the crash caused by the continuous increase of memory? Or is it because of the poor memory control of our art resources that a few larger resources can easily expand the overall memory?</p><p>Or maybe we found that a game scene is seriously stuck and the frame rate is very low. Is it because the number of rendered patches and DrawCalls on the same screen is too high, which leads to high pressure on the rendering module? Or is it time-consuming to update because the UI here is too complex and changes frequently?</p><p>Or maybe we feel that the phone in our hand is surprisingly hot, is it because the GPU pressure in the current scene is too high? Are our bandwidth, Shader complexity, Overdraw, post-processing, etc. not well controlled? The grading strategy we are doing on the current aircraft is not appropriate?</p><p>These are just a few of the myriad performance issues that crop up in endless steam. Some of the more common problems are discussed in detail later. In conclusion, the work of identifying the problem is itself a challenge.</p><p><strong>3.1 Knowledge of computer language/graphics/game engine</strong></p><p>Knowledge and experience are undoubtedly the most valuable weapons for a developer when optimizing project performance. Continuous learning and updating is also the process for every programmer to arm himself with. Perfect and full knowledge is not only conducive to identifying problems but also helping to solve problems. I put it here because it is an important prerequisite for our ability to start optimization work.</p><p>In addition to viewing the source code and documentation of various tools, tracking tool updates, reading books written by professional game developers, browsing various technical forums and blogs, etc., you can also find a lot of high-quality content in UWA’s technical community.</p><p><a href="https://edu.uwa4d.com/">UWA Academy</a>: Continue to update various high-quality courses, from the introduction and use of some development tools to the detailed explanation of the mechanism and principle of an engine module; from the latest mobile game technology practice to the case explanation of boutique projects, etc. It also invited many industry leaders and partners of famous game companies with many years of experience in the industry to write articles, covering a wide range and high quality. There is also excellent content from the <a href="https://blog.uwa4d.com/archives/UWADAY2021_Summary.html">UWA DAY Game Developers Conference</a> hosted by UWA Shanghai Technology company every year.</p><p><a href="https://answer.uwa4d.com/">UWA Q&amp;A</a>: Helping developers find better answers. It is a good platform for game developers to communicate and exchange technical issues on a daily basis. Here you can discuss or answer any questions you have about all aspects of game production. Through the most direct technical exchanges to avoid detours and gain field-proven development experience, the process of identifying and solving problems is much easier.</p><p><a href="https://lab.uwa4d.com/">UWA open source library</a>: Helping developers discover better solutions. Open-source projects from various sources are continuously updated and integrated, the complete translation, the classification is clear, and the pictures and texts are abundant, providing developers with a more convenient channel to search, discover and obtain open-source resources.</p><p><a href="https://blog.uwa4d.com/">UWA Blog</a>: Contains various technical articles selected by UWA, UWA Academy high-quality content update notification, integrates Q&amp;A with high-quality questions, introduces UWA products and their updates, and other UWA community trends.</p><p><strong>3.2 A variety of auxiliary tools</strong></p><p>Workers must first sharpen their tools if they want to do well. Using tools to obtain direct and accurate performance data can more intuitively reflect performance bottlenecks, so as to achieve multiplier effects with half the effort.</p><p>With the development and maturity of the industry, major engine, IDE and hardware manufacturers have launched and updated their own performance analysis tools, and many developers or teams like to develop their own performance monitoring plug-ins according to their own projects.</p><p>As far as the engine is concerned, the Unity Profiler is a tool that many developers use and is using. It can record and view the real-time consumption parameters of various modules such as CPU/rendering/memory. A similar feature is already available in Unreal 4.</p><p>In terms of IDE, Windows, MAC OS/iOS, and Andriod platforms all have applicable tools, such as Visual Studio’s performance profiler, XCode’s Instruments, and Android Studio’s Profiler.</p><p>In terms of hardware, there are more types such as SnapDragon Profiler, XCode Metal Frame Capture, Mali Graphics Debugger, etc., so I won’t go into details.</p><p>All in all, according to the developer’s proficiency, the compatibility of different hardware platforms, the coverage of tool functions, and other factors, it is easy for developers to pick and choose suitable performance optimization aids.</p><p><strong>3.3 UWA tool</strong></p><p>So is there an easy-to-use, highly compatible, and comprehensive performance optimization assistant tool?</p><p>Of course, there is-<a href="https://en.uwa4d.com/feature/got-online">The UWA GOT Online</a> tool can be quickly integrated into the test project through the SDK provided by UWA. After the test process is completed on the real device, the data upload and analysis can be completed in a very short time, thereby automatically generating a series of visual charts. At the same time, it is also based on UWA’s rich optimization experience and huge database for scoring and provides targeted analysis suggestions and changes in performance parameters according to each performance module.</p><p>Not only that, but UWA also provides other in-depth optimization services to meet the optimization needs of developers from different dimensions.</p><h3>4. How to solve the problem</h3><p>The second big step in performance is problem-solving. With the support of knowledge and experience and the above tools, the more complex our project is and the later stage, the more we will face a long list of optimization problems. Properly planning and shortening this list in a limited time is our next challenge.</p><p><strong>4.1 Prioritization of optimization work</strong></p><p>Before the specific optimization work, reasonable planning can often save a lot of overall time.</p><p>The first point of planning work is to grasp the main contradiction of the problem. In a long optimization list, it is often impractical to optimize each item in the sequence. At this point, the list needs to be reorganized, reordered by priority, and more invested in optimizing problems that are more cost-effective.</p><p>For the judgment of priority, UWA believes that there are two main points of reference: First, the importance. If a problem has a far greater impact on the performance pressure of the current scene than other factors, it is obviously the main contradiction. If it is not corrected, it is difficult to maintain a normal game experience. Then you should invest more manpower and time to focus on solving it first; The second is the ease of operation if the performance pressure caused by a problem is relatively small, but it is just a little effort, such as just turning off a switch in the engine settings, it should be changed first.</p><p><strong>4.2 Trade-off between performance and effect</strong></p><p>The second point is a trade-off. The optimization of resources and rendering often affects the performance of the game. To this end, programmers often need to strengthen communication with planning and art colleagues to find a balance between the two. This balance is a dynamic balance and needs to be operated in combination with the actual situation. For example, a PUBG game has frequent screen changes and requires smooth combat operations, so the performance requirements can be lower; while a simulation game uses exquisite characters as its selling point, its models and animations need to be very delicate, while sacrificing some performance. Even in the same game, you can focus on performance in cutscenes and character display interfaces, while focusing on performance in battle scenes requires specific analysis of specific issues.</p><p>In general, the ultimate goal of the optimization of game projects is to run smoothly on the player’s hardware and give up a large part of the performance effect for this, which is also the actual choice of most development teams.</p><p><strong>4.3 Classification strategy and setting standards</strong><br>The third point, achieving the above balance on each type of aircraft is our classification strategy. We can turn on post-processing and use high-resolution models on high-end and even flagship models, but use a different set of standards on mid-to-low-end models.</p><p>Developing a grading strategy also requires us to adjust according to the type of project. The more detailed and accurate classification should also refer to the hardware models of the target market of the project and the classification experience of similar games. For details, please refer to <a href="https://blog.uwa4d.com/archives/UWA_PAnormalvalue.html">the article “UWA Performance Standard System Based on Mobile Device Computing Power”</a>.</p><p>In addition, the development team should also preferably specify a set of detailed and reasonable standards to manage and constrain the entire development process. The most common is to specify art resource standards, thus greatly avoiding memory problems. Unity also provides a callback function to perform normalization settings when resources are imported.</p><p><strong>4.4 UWA suggestions</strong></p><p>After the planning is completed, the specific optimization work comes. It’s a tedious job and requires patience, and UWA is happy to help along the way:</p><p>You can certainly look for ways in the UWA community, or find solutions in the automated reporting of UWA tools. You can also contact <a href="/service/mailto:support@uwa4d.com">UWA staff</a> to provide one-on-one explanation services for real-device test reports or further in-depth optimization services. UWA’s engine technical team will make more detailed diagnosis and suggestions for game projects.</p><h3>5. How to continuously monitor performance</h3><p>After taking the first two steps of performance optimization, many development teams want or take the third step, which is the step of continuously monitoring performance. To this end, some teams have dedicated engine optimizers and try to develop their own DevOps tools. We think this is a manifestation of the “industrialization” trend of game development.</p><p>As the demand for high-quality games in China increases year by year, the game R&amp;D team has a higher and higher demand for the “industrialization” of project R&amp;D. In UWA’s view, the “industrialization” of game development can currently be divided into five dimensions: standardization, normalization, specialization, automation, and customization. In the past 2021, UWA has done a lot of work and accumulated a lot of experience in the above aspects.</p><p>In 2022, at the past 6th UWA DAY Game Development Technology Conference with the theme of game development hosted by UWA, UWA adhered to the theme of “going into the game to practice the industrialization of game development” and led the industry developers to review Excellent R&amp;D concepts and practical experience in the industry and work with industry partners to build an open and win-win technology exchange ecosystem.</p><p>The content of this article is introduced here. For more content, you can go to the UWA Academy to read. The course will discuss some performance problems that often occur in current game projects from three dimensions: memory, CPU, and GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wmvdgeq2oVpnO7DN.png" /></figure><p>That’s all for today’s sharing. Of course, life is boundless but knowing is boundless. In the long development cycle, these problems you see maybe just the tip of the iceberg. We have already prepared more technical topics on the UWA Q&amp;A website, waiting for you to explore and share them together. You are welcome to join us, who love progress. Maybe your method can solve the urgent needs of others, and the “stone” of other mountains can also attack your “jade”.</p><p>YOU MAY ALSO LIKE!!!</p><p>UWA Website: <a href="https://en.uwa4d.com/">https://en.uwa4d.com</a></p><p>UWA Blogs: <a href="https://blog.en.uwa4d.com/">https://blog.en.uwa4d.com</a></p><p>UWA Product: <a href="https://en.uwa4d.com/feature/got">https://en.uwa4d.com/feature/got</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aba39db10e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity Real-time Reflection Effect Optimization]]></title>
            <link>https://medium.com/@uwa4d/unity-real-time-reflection-effect-optimization-fc9b1fdc2d47?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc9b1fdc2d47</guid>
            <category><![CDATA[reflections]]></category>
            <category><![CDATA[game-optimization]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Tue, 15 Nov 2022 07:28:56 GMT</pubDate>
            <atom:updated>2022-11-15T07:29:19.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JpoCpo1fqEIxynVLynztdA.jpeg" /></figure><h3>1. The Result and Cost of the Effect after Optimization</h3><p>Here is the basic background: There are 8 people on the same screen with the highest picture quality, and it takes 1.1ms (Qualcomm Snapdragon 710). Because the project is not released yet, only test figures can be used for related explanations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*yqIyMd84XxCzaaaH.png" /></figure><h3>2. The Original Source Code</h3><ul><li><strong>Source code</strong></li></ul><pre>using UnityEngine;<br>using System.Collections;</pre><pre>[ExecuteInEditMode]<br>public class MirrorReflection : MonoBehaviour<br>{<br>    public Material m_matCopyDepth;<br>    public bool m_DisablePixelLights = true;<br>    public int m_TextureSize = 256;<br>    public float m_ClipPlaneOffset = 0.07f;</pre><pre>    public LayerMask m_ReflectLayers = -1;</pre><pre>    private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -&gt; Camera table</pre><pre>    public RenderTexture m_ReflectionTexture = null;<br>    public RenderTexture m_ReflectionDepthTexture = null;<br>    private int m_OldReflectionTextureSize = 0;</pre><pre>    private static bool s_InsideRendering = false;</pre><pre>    public void OnWillRenderObject()<br>    {<br>        if (!enabled || !GetComponent&lt;Renderer&gt;() || !GetComponent&lt;Renderer&gt;().sharedMaterial || !GetComponent&lt;Renderer&gt;().enabled)<br>            return;</pre><pre>        Camera cam = Camera.current;<br>        if (!cam)<br>            return;</pre><pre>        // Safeguard from recursive reflections.<br>        if (s_InsideRendering)<br>            return;<br>        s_InsideRendering = true;</pre><pre>        Camera reflectionCamera;<br>        CreateMirrorObjects(cam, out reflectionCamera);</pre><pre>        // find out the reflection plane: position and normal in world space<br>        Vector3 pos = transform.position;<br>        Vector3 normal = transform.up;</pre><pre>        // Optionally disable pixel lights for reflection<br>        int oldPixelLightCount = QualitySettings.pixelLightCount;<br>        if (m_DisablePixelLights)<br>            QualitySettings.pixelLightCount = 0;</pre><pre>        UpdateCameraModes(cam, reflectionCamera);</pre><pre>        // Render reflection<br>        // Reflect camera around reflection plane<br>        float d = -Vector3.Dot(normal, pos) - m_ClipPlaneOffset;<br>        Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);</pre><pre>        Matrix4x4 reflection = Matrix4x4.zero;<br>        CalculateReflectionMatrix(ref reflection, reflectionPlane);<br>        Vector3 oldpos = cam.transform.position;<br>        Vector3 newpos = reflection.MultiplyPoint(oldpos);<br>        reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;</pre><pre>        // Setup oblique projection matrix so that near plane is our reflection<br>        // plane. This way we clip everything below/above it for free.<br>        Vector4 clipPlane = CameraSpacePlane(reflectionCamera, pos, normal, 1.0f);<br>        Matrix4x4 projection = cam.projectionMatrix;<br>        CalculateObliqueMatrix(ref projection, clipPlane);<br>        reflectionCamera.projectionMatrix = projection;</pre><pre>        reflectionCamera.cullingMask = ~(1 &lt;&lt; 4) &amp; m_ReflectLayers.value; // never render water layer<br>        reflectionCamera.targetTexture = m_ReflectionTexture;<br>        //GL.SetRevertBackfacing(true);<br>        GL.invertCulling = true;<br>        reflectionCamera.transform.position = newpos;<br>        Vector3 euler = cam.transform.eulerAngles;<br>        reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);<br>        reflectionCamera.depthTextureMode = DepthTextureMode.Depth;<br>        reflectionCamera.Render();</pre><pre>        // copy depth<br>        Graphics.SetRenderTarget(m_ReflectionDepthTexture);<br>        m_matCopyDepth.SetPass(0);<br>        DrawFullscreenQuad();<br>        Graphics.SetRenderTarget(null);<br>        // Graphics.Blit(m_ReflectionTexture, m_ReflectionDepthTexture, m_matCopyDepth);<br></pre><pre>        reflectionCamera.transform.position = oldpos;<br>        //GL.SetRevertBackfacing(false);<br>        GL.invertCulling = false;<br>        Material[] materials = GetComponent&lt;Renderer&gt;().sharedMaterials;<br>        foreach (Material mat in materials)<br>        {<br>            mat.SetTexture(&quot;_ReflectionTex&quot;, m_ReflectionTexture);<br>            mat.SetTexture(&quot;_ReflectionDepthTex&quot;, m_ReflectionDepthTexture);<br>        }</pre><pre>        // // Set matrix on the shader that transforms UVs from object space into screen<br>        // // space. We want to just project reflection texture on screen.<br>        // Matrix4x4 scaleOffset = Matrix4x4.TRS(<br>        //  new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f));<br>        // Vector3 scale = transform.lossyScale;<br>        // Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale(new Vector3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z));<br>        // mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;<br>        // foreach (Material mat in materials)<br>        // {<br>        //  mat.SetMatrix(&quot;_ProjMatrix&quot;, mtx);<br>        // }</pre><pre>        // Restore pixel light count<br>        if (m_DisablePixelLights)<br>            QualitySettings.pixelLightCount = oldPixelLightCount;</pre><pre>        s_InsideRendering = false;<br>    }<br></pre><pre>    // Cleanup all the objects we possibly have created<br>    void OnDisable()<br>    {<br>        if (m_ReflectionTexture)<br>        {<br>            DestroyImmediate(m_ReflectionTexture);<br>            m_ReflectionTexture = null;<br>        }<br>        if (m_ReflectionDepthTexture)<br>        {<br>            DestroyImmediate(m_ReflectionDepthTexture);<br>            m_ReflectionDepthTexture = null;<br>        }<br>        foreach (DictionaryEntry kvp in m_ReflectionCameras)<br>            DestroyImmediate(((Camera)kvp.Value).gameObject);<br>        m_ReflectionCameras.Clear();<br>    }<br></pre><pre>    private void UpdateCameraModes(Camera src, Camera dest)<br>    {<br>        if (dest == null)<br>            return;<br>        // set camera to clear the same way as current camera<br>        dest.clearFlags = src.clearFlags;<br>        dest.backgroundColor = src.backgroundColor;<br>        if (src.clearFlags == CameraClearFlags.Skybox)<br>        {<br>            Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;<br>            Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;<br>            if (!sky || !sky.material)<br>            {<br>                mysky.enabled = false;<br>            }<br>            else<br>            {<br>                mysky.enabled = true;<br>                mysky.material = sky.material;<br>            }<br>        }<br>        // update other values to match current camera.<br>        // even if we are supplying custom camera&amp;projection matrices,<br>        // some of values are used elsewhere (e.g. skybox uses far plane)<br>        dest.farClipPlane = src.farClipPlane;<br>        dest.nearClipPlane = src.nearClipPlane;<br>        dest.orthographic = src.orthographic;<br>        dest.fieldOfView = src.fieldOfView;<br>        dest.aspect = src.aspect;<br>        dest.orthographicSize = src.orthographicSize;<br>    }</pre><pre>    // On-demand create any objects we need<br>    private void CreateMirrorObjects(Camera currentCamera, out Camera reflectionCamera)<br>    {<br>        reflectionCamera = null;</pre><pre>        // Reflection render texture<br>        if (!m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize)<br>        {<br>            if (m_ReflectionTexture)<br>                DestroyImmediate(m_ReflectionTexture);<br>            m_ReflectionTexture = new RenderTexture(m_TextureSize, m_TextureSize, 16);<br>            m_ReflectionTexture.name = &quot;__MirrorReflection&quot; + GetInstanceID();<br>            m_ReflectionTexture.isPowerOfTwo = true;<br>            m_ReflectionTexture.hideFlags = HideFlags.DontSave;<br>            m_ReflectionTexture.filterMode = FilterMode.Bilinear;</pre><pre>            if (m_ReflectionDepthTexture)<br>                DestroyImmediate(m_ReflectionDepthTexture);<br>            m_ReflectionDepthTexture = new RenderTexture(m_TextureSize, m_TextureSize, 0, RenderTextureFormat.RHalf);<br>            // m_ReflectionDepthTexture = new RenderTexture(m_TextureSize, m_TextureSize, 0, RenderTextureFormat.R8);<br>            m_ReflectionDepthTexture.name = &quot;__MirrorReflectionDepth&quot; + GetInstanceID();<br>            m_ReflectionDepthTexture.isPowerOfTwo = true;<br>            m_ReflectionDepthTexture.hideFlags = HideFlags.DontSave;<br>            m_ReflectionDepthTexture.filterMode = FilterMode.Bilinear;</pre><pre>            m_OldReflectionTextureSize = m_TextureSize;<br>        }</pre><pre>        // Camera for reflection<br>        reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;<br>        if (!reflectionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO<br>        {<br>            GameObject go = new GameObject(&quot;Mirror Refl Camera id&quot; + GetInstanceID() + &quot; for &quot; + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox));<br>            reflectionCamera = go.GetComponent&lt;Camera&gt;();<br>            reflectionCamera.enabled = false;<br>            reflectionCamera.transform.position = transform.position;<br>            reflectionCamera.transform.rotation = transform.rotation;<br>            reflectionCamera.gameObject.AddComponent&lt;FlareLayer&gt;();<br>            go.hideFlags = HideFlags.HideAndDontSave;<br>            m_ReflectionCameras[currentCamera] = reflectionCamera;<br>        }<br>    }</pre><pre>    // Extended sign: returns -1, 0 or 1 based on sign of a<br>    private static float sgn(float a)<br>    {<br>        if (a &gt; 0.0f) return 1.0f;<br>        if (a &lt; 0.0f) return -1.0f;<br>        return 0.0f;<br>    }</pre><pre>    // Given position/normal of the plane, calculates plane in camera space.<br>    private Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign)<br>    {<br>        Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;<br>        Matrix4x4 m = cam.worldToCameraMatrix;<br>        Vector3 cpos = m.MultiplyPoint(offsetPos);<br>        Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign;<br>        return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal));<br>    }</pre><pre>    // Adjusts the given projection matrix so that near plane is the given clipPlane<br>    // clipPlane is given in camera space. See article in Game Programming Gems 5 and<br>    // <a href="http://aras-p.info/texts/obliqueortho.html">http://aras-p.info/texts/obliqueortho.html</a><br>    private static void CalculateObliqueMatrix(ref Matrix4x4 projection, Vector4 clipPlane)<br>    {<br>        Vector4 q = projection.inverse * new Vector4(<br>            sgn(clipPlane.x),<br>            sgn(clipPlane.y),<br>            1.0f,<br>            1.0f<br>        );<br>        Vector4 c = clipPlane * (2.0F / (Vector4.Dot(clipPlane, q)));<br>        // third row = clip plane - fourth row<br>        projection[2] = c.x - projection[3];<br>        projection[6] = c.y - projection[7];<br>        projection[10] = c.z - projection[11];<br>        projection[14] = c.w - projection[15];<br>    }</pre><pre>    // Calculates reflection matrix around the given plane<br>    private static void CalculateReflectionMatrix(ref Matrix4x4 reflectionMat, Vector4 plane)<br>    {<br>        reflectionMat.m00 = (1F - 2F * plane[0] * plane[0]);<br>        reflectionMat.m01 = (-2F * plane[0] * plane[1]);<br>        reflectionMat.m02 = (-2F * plane[0] * plane[2]);<br>        reflectionMat.m03 = (-2F * plane[3] * plane[0]);</pre><pre>        reflectionMat.m10 = (-2F * plane[1] * plane[0]);<br>        reflectionMat.m11 = (1F - 2F * plane[1] * plane[1]);<br>        reflectionMat.m12 = (-2F * plane[1] * plane[2]);<br>        reflectionMat.m13 = (-2F * plane[3] * plane[1]);</pre><pre>        reflectionMat.m20 = (-2F * plane[2] * plane[0]);<br>        reflectionMat.m21 = (-2F * plane[2] * plane[1]);<br>        reflectionMat.m22 = (1F - 2F * plane[2] * plane[2]);<br>        reflectionMat.m23 = (-2F * plane[3] * plane[2]);</pre><pre>        reflectionMat.m30 = 0F;<br>        reflectionMat.m31 = 0F;<br>        reflectionMat.m32 = 0F;<br>        reflectionMat.m33 = 1F;<br>    }</pre><pre>    static public void DrawFullscreenQuad(float z = 1.0f)<br>    {<br>        GL.Begin(GL.QUADS);<br>        GL.Vertex3(-1.0f, -1.0f, z);<br>        GL.Vertex3(1.0f, -1.0f, z);<br>        GL.Vertex3(1.0f, 1.0f, z);<br>        GL.Vertex3(-1.0f, 1.0f, z);</pre><pre>        GL.Vertex3(-1.0f, 1.0f, z);<br>        GL.Vertex3(1.0f, 1.0f, z);<br>        GL.Vertex3(1.0f, -1.0f, z);<br>        GL.Vertex3(-1.0f, -1.0f, z);<br>        GL.End();<br>    }<br>}</pre><p>Related Contents: <br><a href="https://github.com/unity3d-jp/unitychan-crs/blob/master/Assets/UnityChanStage/Visualizer/MirrorReflection.cs">https://github.com/unity3d-jp/unitychan-crs/blob/master/Assets/UnityChanStage/Visualizer/MirrorReflection.cs</a></p><p>Click to see what are the problems with this effect code and how to optimize them: <a href="https://blog.en.uwa4d.com/2022/11/09/unity-real-time-reflection-related-optimization/">https://blog.en.uwa4d.com/2022/11/09/unity-real-time-reflection-related-optimization/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc9b1fdc2d47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Introduction and Implementation of Compute Shader in Unity]]></title>
            <link>https://medium.com/@uwa4d/basic-introduction-and-implementation-of-compute-shader-in-unity-d5cd315e3d4c?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5cd315e3d4c</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[compute-shader]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Mon, 14 Nov 2022 10:46:17 GMT</pubDate>
            <atom:updated>2022-11-14T10:46:17.681Z</atom:updated>
            <content:encoded><![CDATA[<p>Compute Shader is a relatively popular technology today, such as in the previous “Moonlight Blade Mobile Game” and the recently popular “Naraka: Bladepoint”. Unity’s official introduction to Compute Shader is as follows: <a href="https://docs.unity3d.com/Manual/class-ComputeShader.html">https://docs.unity3d.com/Manual/class-ComputeShader.html. </a>The Compute Shader runs on the GPU like other Shaders, but it is <strong>independent of the rendering pipeline</strong>. We can use it to implement <strong>a large number of parallel</strong> GPU algorithms to speed up our games.</p><p>In Unity, we right-click in the Project to create a Compute Shader file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*6NpN6SQW8uB1NX3J.png" /></figure><p>The generated files belong to a kind of Asset file, and all have <strong>.compute</strong> as the file suffix. Let’s take a look at the default content inside:</p><pre>#pragma kernel CSMain<br>RWTexture2D&lt;float4&gt; Result;<br>[numthreads(8,8,1)]<br>void CSMain (uint3 id : SV_DispatchThreadID)<br>{<br>    Result[id.xy] = float4(id.x &amp; id.y, (id.x &amp; 15)/15.0, (id.y &amp; 15)/15.0, 0.0);<br>}</pre><p>The main purpose of this article is to enable new learners to understand the meaning of these lines of code, and only after learning the basics can they read more awesome code.</p><p><a href="https://blog.en.uwa4d.com/2022/10/25/basic-introduction-and-implementation-of-compute-shader-in-unity/">https://blog.en.uwa4d.com/2022/10/25/basic-introduction-and-implementation-of-compute-shader-in-unity/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5cd315e3d4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Screen Post-processing Effects: Real-time Glow and Bloom and Its Implementation]]></title>
            <link>https://medium.com/@uwa4d/screen-post-processing-effects-real-time-glow-and-bloom-and-its-implementation-beabf8774879?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/beabf8774879</guid>
            <category><![CDATA[post-effect]]></category>
            <category><![CDATA[bloom]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 07:28:47 GMT</pubDate>
            <atom:updated>2022-11-04T07:28:47.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FteM9eTK_7i2n6V_5O-U5g.png" /></figure><p>Bloom (Glow) special effects are the most commonly used screen post-processing special effects in games. It is manifested as a highlight object with a floodlight effect, which makes the light and shadow performance of the picture better. Bloom is usually paired with HDR and ToneMapping for better results.</p><p>The general bloom effect is made by blurring the highlighted part of the image through convolution and then superimposing it on the original image. In “Image Blur Algorithm of Screen Post-Processing Effect Series”, we introduced various image blur algorithms and chose to use the most efficient Dual Blur method for blur processing.</p><p><a href="https://blog.en.uwa4d.com/2022/09/08/screen-post-processingeffects-real-time-glow-and-bloom/">https://blog.en.uwa4d.com/2022/09/08/screen-post-processingeffects-real-time-glow-and-bloom/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beabf8774879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dual Blur and Its Implementation in Unity]]></title>
            <link>https://medium.com/@uwa4d/dual-blur-and-its-implementation-in-unity-c2cd77c90771?source=rss-2a1f9609c2cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2cd77c90771</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[blur]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[gamedev]]></category>
            <dc:creator><![CDATA[UWA]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 02:22:26 GMT</pubDate>
            <atom:updated>2022-09-07T02:22:26.219Z</atom:updated>
            <content:encoded><![CDATA[<p>Dual Blur (Dual Filter Blur) is an improved algorithm based on <a href="https://blog.en.uwa4d.com/2022/09/01/screen-post-processing-effects-chapter-4-kawase-blur-and-its-implementation/">Kawase Blur</a>. This algorithm uses Down-Sampling to reduce the image and Up-Sampling to enlarge the image to further reduce the texture reads while making full use of the GPU hardware characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zCpkGDaPhLcUWSjS.png" /></figure><p>First, down-sampling the image, and reduce the length and width of the original image by 1/2 to obtain the target image. As shown in the figure, the pink part represents one pixel of the target image after being stretched to the original size, and each small white square represents one pixel of the original image. When sampling, the selected sampling position is the position represented by the blue circle in the figure, which are: the four corners and the center of each pixel of the target image, the weights are 1/8 and 1/2, and their UV coordinates are substituted into Sampling from the original image. One pixel of the target image is processed, and the texture is read through 5 times, so that 16 pixels of the original image participate in the operation. The number of pixels of the obtained target image is reduced to 1/4 of the original image. Then perform multiple down-sampling, and the target image obtained each time is used as the original image for the next sampling. In this way, the number of pixels that need to be involved in the operation for each down-sampling will be reduced to 1/4.</p><p>Then perform up-sampling (Up-Sampling) of the image, and expand the length and width of the original image by 2 times to obtain the target image. As shown in the figure, the pink part indicates that the target image is reduced to one pixel of the original image size. Each small white square represents a pixel of the original image. When sampling, the selected sampling positions are the positions represented by the blue circles in the figure, which are: the four corners of the corresponding pixel of the original image and the center of the four adjacent pixels, and the weights are 1/6 and 1/12 respectively. One pixel of the target image is processed, and 8 textures are read, so that 16 pixels of the original image participate in the operation. The number of pixels of the obtained target image is expanded to 4 times that of the original image. In this way, the up-sampling operation is repeated until the image is restored to its original size, as shown in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8b8oc2XO80A9BmwL.png" /></figure><h3>Unity Implementation</h3><p>According to the above algorithm, we implement the Dual Blur algorithm on Unity: choose 4 down-sampling and 4 up-sampling for blurring.</p><p>Down-sampling Implementation:</p><blockquote><em>float4 frag_downsample(v2f_img i) :COLOR</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>float4 offset = _MainTex_TexelSize.xyxy*float4(-1,-1,1,1);</em></blockquote><blockquote><em>float4 o = tex2D(_MainTex, i.uv) * 4;</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + offset.xy);</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + offset.xw);</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + offset.zy);</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + offset.zw);</em></blockquote><blockquote><em>return o/8;</em></blockquote><blockquote><em>}</em></blockquote><p>Up-sampling Implementation:</p><blockquote><em>float4 frag_upsample(v2f_img i) :COLOR</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>float4 offset = _MainTex_TexelSize.xyxy*float4(-1,-1,1,1);</em></blockquote><blockquote><em>float4 o = tex2D(_MainTex, i.uv + float2(offset.x, 0));</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + float2(offset.z, 0));</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + float2(0, offset.y));</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + float2(0, offset.w));</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + offset.xy / 2.0) * 2;</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + offset.xw / 2.0) * 2;</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + offset.zy / 2.0) * 2;</em></blockquote><blockquote><em>o += tex2D(_MainTex, i.uv + offset.zw / 2.0) * 2;</em></blockquote><blockquote><em>return o / 12;</em></blockquote><blockquote><em>}</em></blockquote><p>Implement the corresponding pass:</p><blockquote><em>Pass</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>ZTest Always ZWrite Off Cull Off</em></blockquote><blockquote><em>CGPROGRAM</em></blockquote><blockquote><em>#pragma target 3.0</em></blockquote><blockquote><em>#pragma vertex vert_img</em></blockquote><blockquote><em>#pragma fragment frag_downsample</em></blockquote><blockquote><em>ENDCG</em></blockquote><blockquote><em>}</em></blockquote><blockquote><em>Pass</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>ZTest Always ZWrite Off Cull Off</em></blockquote><blockquote><em>CGPROGRAM</em></blockquote><blockquote><em>#pragma target 3.0</em></blockquote><blockquote><em>#pragma vertex vert_img</em></blockquote><blockquote><em>#pragma fragment frag_upsample</em></blockquote><blockquote><em>ENDCG</em></blockquote><blockquote><em>}</em></blockquote><p>Repeat down-sampling and up-sampling in OnRenderImage:</p><blockquote><em>private void OnRenderImage(RenderTexture src, RenderTexture dest)</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>int width = src.width;</em></blockquote><blockquote><em>int height = src.height;</em></blockquote><blockquote><em>var prefilterRend = RenderTexture.GetTemporary(width / 2, height / 2, 0, RenderTextureFormat.Default);</em></blockquote><blockquote><em>Graphics.Blit(src, prefilterRend, m_Material, 0);</em></blockquote><blockquote><em>var last = prefilterRend;</em></blockquote><blockquote><em>for (int level = 0; level &lt; MaxIterations; level++)</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>_blurBuffer1[level] = RenderTexture.GetTemporary(</em></blockquote><blockquote><em>last.width / 2, last.height / 2, 0, RenderTextureFormat.Default</em></blockquote><blockquote><em>);</em></blockquote><blockquote><em>Graphics.Blit(last, _blurBuffer1[level], m_Material, 0);</em></blockquote><blockquote><em>last = _blurBuffer1[level];</em></blockquote><blockquote><em>}</em></blockquote><blockquote><em>for (int level = MaxIterations-1; level &gt;= 0; level–)</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>_blurBuffer2[level] = RenderTexture.GetTemporary(</em></blockquote><blockquote><em>last.width * 2, last.height * 2, 0, RenderTextureFormat.Default</em></blockquote><blockquote><em>);</em></blockquote><blockquote><em>Graphics.Blit(last, _blurBuffer2[level], m_Material, 1);</em></blockquote><blockquote><em>last = _blurBuffer2[level];</em></blockquote><blockquote><em>}</em></blockquote><blockquote><em>Graphics.Blit(last, dest); ;</em></blockquote><blockquote><em>for (var i = 0; i &lt; MaxIterations; i++)</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>if (_blurBuffer1[i] != null)</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>RenderTexture.ReleaseTemporary(_blurBuffer1[i]);</em></blockquote><blockquote><em>_blurBuffer1[i] = null;</em></blockquote><blockquote><em>}</em></blockquote><blockquote><em>if (_blurBuffer2[i] != null)</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>RenderTexture.ReleaseTemporary(_blurBuffer2[i]);</em></blockquote><blockquote><em>_blurBuffer2[i] = null;</em></blockquote><blockquote><em>}</em></blockquote><blockquote><em>}</em></blockquote><blockquote><em>RenderTexture.ReleaseTemporary(prefilterRend);</em></blockquote><blockquote><em>}</em></blockquote><p>Obtaining the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*_2tgeSJPLBivE0z6.png" /></figure><p>You can see the process through FramDebug:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*pPCaDZYopVZH5z4F.png" /></figure><p>(Second Down-Sampling)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*QGwmu9o7zZRGkMC9.png" /></figure><p>(Fourth Down-Sampling)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*9SbEzchhpFlgB1X8.png" /></figure><p>(Second Up-Sampling)</p><h3>Summary</h3><p>The Dual Blur algorithm, based on Kawase Blur, adopts down-sampling to reduce the image and up-sampling to enlarge the image. By reducing the number of pixels of the processed image, the number of texture sampling is further reduced, thereby improving the efficiency.</p><p>The test results in the sharing of the ARM team’s “Bandwidth-Efficient Rendering” are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0-0TCx9NwsA5RY5s.png" /></figure><p>In experiments on mobile devices equipped with Mali-T760 MP8 (such as Samsung Galaxy S6), we can see that the Dual Blur algorithm has the fastest speed and the best performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-TnJ3suFrehZkwZU.png" /></figure><p>There is not much difference in read&amp;write bandwidth between Blur’s improved algorithms.</p><p>In summary, it can be said that the Dual Blur algorithm is the most efficient algorithm to achieve blur effect at this stage.</p><h3>Screen Post Processing Effects Series</h3><p><a href="https://blog.en.uwa4d.com/2022/09/01/screen-post-processing-effects-chapter-4-kawase-blur-and-its-implementation/">Screen Post Processing Effects Chapter 4: Kawase Blur and Its Implementation</a></p><p><a href="https://blog.en.uwa4d.com/2022/08/25/screen-post-processing-effects-chapter-4-box-blur-and-its-implementation/">Screen Post Processing Effects Chapter 4: Box Blur and Its Implementation</a></p><p><a href="https://blog.en.uwa4d.com/2022/08/18/screen-post-processing-effects-chapter-3-algorithm-of-gaussian-blur-and-implementation-using-linear-sampling/">Screen Post Processing Effects Chapter 3: Algorithm of Gaussian Blur and Implementation Using Linear Sampling</a></p><p><a href="https://blog.en.uwa4d.com/2022/08/16/screen-post-processing-effects-chapter-2-two-step-one-dimensional-operation-algorithm-of-gaussian-blur-and-its-implementation/">Screen Post Processing Effects Chapter 2: Two-Step One-Dimensional Operation Algorithm of Gaussian Blur and Its Implementation</a></p><p><a href="https://blog.en.uwa4d.com/2022/08/11/screen-post-processing-effects-chapter-1-basic-algorithm-of-gaussian-blur-and-its-implementation/">Screen Post Processing Effects Chapter 1 — Basic Algorithm of Gaussian Blur and Its Implementation</a></p><p>That’s all for today’s sharing. Of course, life is boundless but knowing is boundless. In the long development cycle, these problems you see maybe just the tip of the iceberg. We have already prepared more technical topics on the UWA Q&amp;A website, waiting for you to explore and share them together. You are welcome to join us, who love progress. Maybe your method can solve the urgent needs of others, and the “stone” of other mountains can also attack your “jade”.</p><p>YOU MAY ALSO LIKE!!!</p><p>UWA Website: <a href="https://en.uwa4d.com/">https://en.uwa4d.com</a></p><p>UWA Blogs: <a href="https://blog.en.uwa4d.com/">https://blog.en.uwa4d.com</a></p><p>UWA Product: <a href="https://en.uwa4d.com/feature/got">https://en.uwa4d.com/feature/got</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2cd77c90771" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>