BLOG

Notes from the KAYAC hyper-casual team

Bloom Effects Even on Cheap GLES2 Phones

Takashi Hirayama

Bloom effect demo

Hello. I'm Hirayama from the Technology Department.

In this article I'll talk about how I implemented a bloom effect on phones. The code is on GitHub, and I've also prepared a unityPackage for convenience, but it hasn't been used in production yet. Please think of it strictly as a sample.

Note: on October 3, 2019, I made a backward-incompatible update. The relevant parts of the article have been revised.

What did I make?

A post-process bloom effect that spreads the color of bright areas into their surroundings to give a sort of "dazzling" feel. It's implemented using only what GLES2 offers, so it can also run in WebGL. Of course, you can also download the sample project from GitHub and run it. The Unity version used is 2018.3.9 2018.4.8.

Note that the sample still has some half-finished debug features left in, and most of the buttons don't work. The upper slider changes the animation speed, and the lower slider changes the size of the objects.

Performance

Now, the seasoned pros among you will say "show me the performance and the quality first, then we'll talk", so I'll cover that up front.

It takes roughly 5.6 milliseconds on a Kyocera S2 at 1280x720.

For other devices, please compare benchmarks and make a ballpark estimate along the lines of "this device is 10 times faster than the S2, so maybe 0.56 milliseconds?" We also have an in-house benchmark and its result data, so please make use of them. The load here is almost entirely in the fragment shader, so if you estimate from GPU-side figures like "CoherentTexture" and "HeavyCalculation", I don't think you'll be far off.

I haven't actually checked, but it's probably something like 5 times the S2 for a Nexus 5, 40 times for an iPhone X and about 15 times for an iPhone SE. iPhones were already faster than the S2 as of the iPhone 5, so I think it'll run without problems on any iOS device.

Keep in mind that the processing time is proportional to the resolution. For example, 1920x1080 has 2,073,600 pixels and 1280x720 has 921,600, so the load roughly doubles. Conversely, the iPhone 5 is 1136x640, a lower resolution than the S2, and also faster, so I'd expect it to run in 3 to 4 milliseconds.

By the way, in the editor on a MacBook Pro Mid 2014, it seemed to take 60% of the processing time of the Bloom in PostProcessingStack V2. For some reason PostProcessingStack takes about 300 ms on the S2, but maybe that's because the S2 isn't a device PostProcessingStack was designed for.

Setup

First, import the unityPackage into your project, and add the LightPostProcessor component to the gameObject of the camera you want to apply the effect to.

Next, fill in the required settings in the Inspector.

LightPostProcessor in the Inspector

The required part is setting references to the various shaders. Put each shader in the package into the slot with the matching name. I'd like this to happen automatically, but I haven't come up with a good way. I've prepared a ScriptableObject at Assets/Kayac/LightPostProcessor/LightPostProcessorAsset, so please set it as the Asset.

Once it starts running and Update starts being called, the effect kicks in. Note that for some reason the effect isn't applied on the first frame, when MonoBehaviour.Start() is called; it only kicks in from the next frame. I'd like to track down the cause and fix it.

Tuning parameters

Basically, play with these two:

  • Bloom Pixel Thredshold
    • 0 to 1. Only pixels brighter than this leak into their surroundings.
  • Bloom Strength
    • 0 or more. The larger, the stronger the leak.

Of course you can also change them from a script, and that's probably the better way. Post-processing really shines when you animate it, and you can do much more by driving it from code.

There's also simple color correction as a bonus feature.

  • Saturation: converts to YUV and multiplies U and V by this value. 0 gives a black-and-white image, and above 1 the colors get deeper.
  • Color Scale: multiplies RGB by the value given here
  • Color Offset: adds the value given here to RGB

It's intended for things like "tint the screen red the instant you take damage and slowly fade it back" or "make the screen sepia in a flashback scene". It's computed alongside the effect, adding only a tiny load (three dot products). Press the "ColorVfx" button in the sample to see what it's like.

The ColorVfx color correction demo

Of course, if these three parameters are at their defaults (Offset 0, Scale and Saturation 1), the feature is switched off and costs nothing.

I recommend touching the remaining parameters only once you understand the implementation. Depending on the nature of the product, you may be able to strike a better balance between performance and quality.

Motivation

Long ago, around the transition from the PS2 to the PS3, "next-generation console" was the buzzword of the day, and I wondered "what makes an image feel next-gen?" I tried lots of things back then, and the conclusion I came to was "dazzle".

And by "dazzling" I mean "making you perceive a color brighter than white". A white circle and a light bulb glowing white look completely different. That's what we want to express.

These days HDR (High Dynamic Range) monitors, which "really can display colors brighter than white", are becoming common, and on such devices it may be enough to just send colors brighter than white to the monitor, but unfortunately phones don't work that way.

Even if you put a white circle on a black screen,

A white circle on a black background

it just looks like a white circle.

But if you let the white bleed softly into the black background, it suddenly feels dazzling.

The white circle bleeding into the background

The color in the middle is the same white, unchanged, yet strangely it looks dazzling. "When the color bleeds, it dazzles."

Why do it as post-processing

If white bleeding faintly into its surroundings makes it dazzling, the simplest approach is to draw an image like that and overlay it. In a 2D game with only a few glowing things, that works fine, and it's cheap too.

But when things move around, deform, disappear and reappear, or there are lots of them, simply overlaying semi-transparent images gets tough. It falls apart on several fronts: the effort of managing them, CPU load that grows with their number, and GPU load from the area painted. For a river surface glittering in the sunset, or a Christmas tree covered in light bulbs, it just can't keep up.

That's why the post-processing method was developed.

Post-processing means "processing the finished image". You process it afterwards (post), hence the name. Once all the drawing is done, you intercept the finished image before it reaches the screen and apply some processing to it. In this case, you find the glowing spots after the fact and make their colors bleed into the surroundings.

The advantages of this method are:

  • The processing time is fixed no matter how many glowing things there are
  • Anything bright that's drawn glows automatically, so it takes little effort

Of course there are disadvantages too.

  • It processes the whole screen, so it's heavy
  • It doesn't get any lighter at all even when nothing is glowing
  • You need some trick to identify the glowing spots after the fact

In short, making things dazzle with post-processing is "heavy, but consistently heavy, and things glow automatically so it takes no effort". From 2006 on (that is, from the PS3 on), it became more or less standard practice.

Yet even though it's almost 2019, it doesn't feel like it has become standard on phones. So I decided to give it a try.

Note that Unity provides PostProcessingStack as the standard solution, and adding it lets you do the same thing easily. If that works for you, use it. It's the standard. It just happened not to run properly on my own phone, so I had no choice but to try making one myself.

Method

I based this implementation on the method proposed by Masaki Kawase.

Wikipedia has an entry called Kawase's bloom filter, but it's not that one. It's the method presented at GDC 2004 that applies Gaussian blur at multiple resolutions. See Practical Implementation of High Dynamic Range Rendering", GDC 2004.

It's a very well-known method, and I've implemented it several times before, but this time, partly because I was writing it up for the tech blog, I made a point of properly figuring out the parts I'd never really understood, and I made improvements with Unity's characteristics and the performance of cheap phones in mind. I think it turned out better than the ones I've made before.

The theory, briefly

To look dazzling, the glowing parts just need to bleed into the non-glowing parts. "Bleed" is vague, but put another way, they just need to be blurred.

But blurring isn't simple either. To implement "a blur where the color spreads up to 10 pixels away", you'd write fragment shader code that fetches the colors of all the pixels in a circle of radius 21 pixels and adds them up. A shader with 300 tex2D calls is practically unusable, especially since we're dealing with an underpowered phone.

And even after all that effort, at a screen resolution of 1280x720, 10 pixels is only 1/72 of the height. If it only bleeds that little, the result will feel very underwhelming.

Let's take a photo of a light.

A photo of a fluorescent light taken with a phone camera

This is a fluorescent light shot with a phone camera, and the white part looks quite thick. But the actual tube is much thinner; the white is bleeding out by about 200 pixels. So unless the glow spreads about that far, it doesn't look right. What's more, the higher the screen resolution, the more pixels that distance covers. That's quite a nuisance.

Separable filters

First, let's think about how to speed up a blur with a radius of 10 pixels. An amateur can't come up with that kind of thing alone, so we turn to mathematics for help.

Let's use the normal distribution. It's also called the Gaussian distribution, and a blur based on it is called a Gaussian blur. Amazingly, it lets you do a calculation that would need 441 tex2D calls with just 42.

The normal distribution function has the form exp(-(x^2+y^2)). exp(a+b)=exp(a)*exp(b): an addition inside an exponential is the same as multiplying two exponentials. So it can be written as exp(-x^2)*exp(-y^2). That means if you first compute with a shader that multiplies by exp(-x^2), and then with a shader that multiplies by exp(-y^2), you get the same result. Blurring in the x direction takes 21 tex2D calls, and the same again for y, so 42 in total. That's about 10 times faster.

Any distribution function that's a product of a function of x alone and a function of y alone allows the same speed-up, but as far as I know, the only one that also produces a round blur is the normal distribution. In a setting like a game, where "you can only spend a few milliseconds on the calculation", if you want a wide blur, I think Gaussian blur is practically the only option (blurring with a Fourier transform is a possibility, but I've never tried it). So that's what I used here too.

Approximating by shrinking

So now a blur with a radius of 10 pixels takes about 40 tex2D calls, but that's still far too heavy. At 1280x720, doing 40 tex2D calls for every pixel would by itself push a cheap phone below 30 fps, and the game would be unplayable. And a radius of 10 isn't enough anyway. We need a way to boost efficiency dramatically.

The answer is "using downscaled buffers", as described in Kawase's material. When the texture read with tex2D is small, the GPU automatically applies a bilinear filter and upscales it. In other words, upscaling is practically free.

So first you shrink the screen, apply the Gaussian blur at that size, and scale it back up. Lowering the resolution degrades the image, but since you're blurring it anyway, a bit of degradation won't be noticeable.

For example, if you shrink to 1/2, a 10-pixel radius in the shrunken image becomes 20 pixels when scaled back to the original resolution. You get the equivalent of a 20-pixel-radius blur for (1/2)×(1/2), that is 1/4, of the computation.

By default, this implementation applies the Gaussian blur after shrinking to 1/4. The radius is 7, which works out to a radius of 28 at the original resolution.

Combining multiple resolutions

Still, a radius of 28 isn't enough. We want a radius in the hundreds, so let's shrink further. For example, a radius of 7 pixels at 1/32 becomes 7×32, a whopping 224 pixels, when scaled back up. You get a 224-pixel-radius blur at 1/1024 of the load. Wonderful.

But on its own, this gives a so-so result.

The image blurred at 1/32 added to the original

I shrank the original image to 1/32, applied a Gaussian blur and added the result to the original. Can you see that it doesn't quite look like it's glowing? The light does bleed far out, but it isn't bright enough close to the object, so the "dazzle" is weak.

So, as Kawase proposes, we use the trick of "blurring at multiple resolutions and adding them".

Gaussian blurs at 1/4, 1/8, 1/16 and 1/32 added together

Here a Gaussian blur was applied at each of four levels, 1/4, 1/8, 1/16 and 1/32, and the results were all added together. Adding four Gaussian blurs with radii of 28, 56, 112 and 224 gives a nice blur that's bright up close and fades with distance. How much of each resolution to mix in is adjustable, but Kawase's material gave an example where each halving of the resolution doubles the weight, so this implementation uses that as the default. If the 1/4 blur is added at 0.1, then 1/8 at 0.2, 1/16 at 0.4, and so on.

Implementation

That's the theory in brief, but there are a few things to watch out for when implementing it, and even more if you want it to be fast.

Also, the rough reasoning above isn't enough to actually implement it. From here on, let's go through the implementation in considerable detail.

Overview of the processing

First, here's a diagram of how the processing is structured.

Diagram of the processing steps

If you're not familiar with this field it may not make much sense yet, but I'll explain it in detail below.

The problem of brightness extraction

Earlier, "adding the blurred image" may have made it sound like the original image is blurred directly, but in this implementation there's a step before blurring that "extracts only the bright parts".

That said, this is only needed because the rendering result in the frame buffer ranges from 0 to 1; if the frame buffer could hold values like 100 or 1000, it wouldn't be necessary. I do it only because I have to.

In the real world, something that merely looks white and something glowing like a light bulb can differ in brightness by a factor of about 100. In other words, unless the frame buffer can hold values around 100, you can't express the brightness of a light bulb. If it could, you could just use a Gaussian blur "with coefficients such that nothing leaks into the surroundings unless the value is around 100". For example, if the coefficient multiplied with the tex2D value is "0.01 at a distance of 1 pixel", a plain white pixel, that is, one with brightness 1, only leaks 0.01 into the next pixel, and the leak is hardly visible. But with a brightness of 100, even at 1/100 it's still 1, pure white. That gives a difference between white and a light bulb.

But if you stay within OpenGL ES 2, what's written to the frame buffer is in the range 0 to 1, with 1 fixed as white and 0 as black. Even if you want to express "a color brighter than white", the frame buffer can't hold anything above 1 in the first place.

So the first idea is "don't make white 1". For example, decide that 0.5 is white, and 1 is "a color twice as bright as white". Then you can tell "white" from "brighter than white".

In other words, you draw everything at half brightness to begin with, with textures, light settings and so on scaled accordingly, do all your processing, and then double the values at the end before sending them to the screen. If white is drawn in the frame buffer as (0.5, 0.5, 0.5) and a glowing light bulb as (1,1,1), then at the blurring stage the bulb is twice as bright, so there's a difference.

But that's still only twice. What we really want is 100 times. If you made white 0.25, you could go up to 4, but then the color precision drops too much. What used to be 255 steps from black to white becomes only 64, and the image quality becomes unbearable. So we need a trick that "amplifies values above a certain level".

The simplest way to do that is to "subtract a fixed value before blurring". For example, if you subtract 0.4 before blurring, a pixel with brightness 0.5 bleeds 0.1, and a pixel with brightness 1 bleeds 0.6. Plain white and a light bulb now bleed by amounts that differ by a factor of 6.

In this implementation, I add a step that divides by (1-k) after subtracting k, to make effective use of the 8-bit precision. For example, if you subtract 0.9, you divide by 1-0.9, that is 0.1, multiplying by 10. If you didn't do this, the result of brightness extraction would be in the range 0 to 0.1, which in 8 bits is 0 to 25. Having only 26 steps to work with in the following calculations would be bad, so it's multiplied by 10 to stretch it up to 250.

There are more elaborate ways to amplify the difference, but they're painful if you need to run within GLES2 on cheap phones, so I didn't even try them here. Storing the brightness in the alpha channel is another well-known method, but I also wanted this to "drop into an existing product with minimal changes", so I avoided anything that requires changing the shaders that do the drawing (if I were using it in a product I was starting from scratch, I would consider it).

Implementing brightness extraction

So in this implementation, the very first thing done to the rendered frame buffer is brightness extraction, performed while copying into a 1/4 buffer.

fixed4 col = tex2D(_MainTex, i.uv);
col.xyz *= _ColorTransform.x;
col.xyz += _ColorTransform.y;

The fragment shader code is just three lines. The underlying operation is "subtract a fixed value k, then divide by 1-k", but writing it literally seemed likely to be slow, so the formula is rearranged on the CPU side.

y = (x - k) / (1 - k)

can be rearranged as

y = ((1 / (1 - k)) * x) + (-k / (1 - k))

Many GPUs can do "multiply then add" (multiply-accumulate) quickly, so I rearranged it into this form. _ColorTransform.x gets 1 / (1-k) and _ColorTransform.y gets -k / (1 - k). Today's shader compilers may be smart enough to make this unnecessary.

The brightness extraction shader only runs on 1/16 as many pixels as the original resolution, so its load is rarely a problem. Shrinking straight to 1/4 lowers the image quality quite a bit, but since it's going to be blurred anyway, I decided not to worry about it. If it bothers you, you could add an intermediate step that shrinks to 1/2 first.

Gaussian blur in detail

A Gaussian blur calls tex2D several times, multiplies each result by a coefficient from the normal distribution formula, and adds them all up.

c = tex2D(_MainTex, i.sample0.xy) * i.sample0.z;
c += tex2D(_MainTex, i.sample1.xy) * i.sample1.z;
c += tex2D(_MainTex, i.sample2.xy) * i.sample2.z;
c += tex2D(_MainTex, i.sample3.xy) * i.sample3.z;
c += tex2D(_MainTex, i.sample4.xy) * i.sample4.z;
c += tex2D(_MainTex, i.sample5.xy) * i.sample5.z;
c += tex2D(_MainTex, i.sample6.xy) * i.sample6.z;
c += tex2D(_MainTex, i.sample7.xy) * i.sample7.z;

It looks something like this. sample0 to 7, passed from the vertex shader, hold the uv for tex2D in xy and the weight from the normal distribution formula in z. You could put the uvs in the vertex data, but as of Unity 2018.3.9 a vertex seems to hold only four uvs, so it's better to generate the uvs in the vertex shader.

The normal distribution coefficients can be computed like this.

float Gauss(float sigma, float x)
{
    float sigma2 = sigma * sigma;
    return Mathf.Exp(-(x * x) / (2f * sigma2));
}

It's just the formula exp(-(x*x) / (2*sigma)) translated directly into code. With it, if you want, say, the coefficients of a normal distribution with a radius of 3 pixels and a standard deviation of 1 pixel, you can compute them like this:

float sum = 0f;
for (int i = 0; i < 7; i++)
{
    weights[i] = Gauss(sigma: 1f, x: (float)(i - 3));
    sum += weights[i];
}
for (int i = 0; i < 7; i++)
{
    weights[i] /= sum;
}

I compute the sum and divide every coefficient by it because I want them to "add up to 1". If the coefficients add up to 1, running the shader doesn't change the overall brightness. If blurring a pure white image turned it gray, or an even brighter white, it would cause all sorts of trouble.

The normal distribution formula usually has sqrt(2*pi*sigma^2) in the denominator, so that "summing over the whole domain gives 1". If you computed over a wide enough range at fine enough intervals (say from -100 to 100 in steps of 0.01), this denominator would make the total 1, and you wouldn't need to compute the sum and divide, but we're nowhere near that here. You have to normalize the total to 1 yourself. That's why Gauss() above doesn't divide by sqrt(2*pi*sigma^2).

Choosing the standard deviation

So how large should the standard deviation be?

The standard deviation describes how widely the curve spreads, and about three standard deviations from the center the value is nearly 0.

If you make the standard deviation large, the value is still fairly large at the edge of the radius, so you get a hard boundary, and the blur no longer comes out round as the theory says it should. The property "blur in X, then in Y, and you get a round blur" only holds for "a normal distribution that extends infinitely"; it doesn't hold for approximations that cut it off arbitrarily or sample it at only a few points.

Conversely, if the standard deviation is small, you end up with situations like "there are 7 points, but the outer 4 are almost zero and pointless", and there are few samples in the central region where the value changes the most, which also introduces error. The render textures used here are 8-bit, so a value below 1/255 is 0. In other words, once a coefficient falls below 1/255 = 0.003922, it's meaningless. And even if the coefficient is exactly 1/255, the value only becomes 1 when the pixel is pure white, so it contributes very little. It's better for the edge coefficients to have some weight.

In this implementation the default standard deviation is 3 pixels. The blur radius is 7 pixels, so that's a bit under half. The edge coefficient is 0.027, roughly 7/255. The result looked fine to me, so I left it there, but better tuning may be possible. Try changing "Bloom Sigma In Pixel" in the inspector.

I want fewer Graphics.SetRenderTarget() calls

In this case, the Gaussian blur shader runs 8 times: twice, X and Y, for each of the 1/4, 1/8, 1/6 and 1/32 buffers. If each of these frame buffers were separate, you'd need 8 Graphics.SetRenderTarget() calls and 8 Material.SetPass() calls.

On top of that, shrinking the original image is a hassle in itself: if you shrink the original buffer to 1/4, then 1/8, then 1/16, then 1/32, you need 4 Graphics.SetRenderTarget() calls and 4 Material.SetPass() calls.

But on some devices, Graphics.SetRenderTarget() can be expensive. Some GPUs can't draw directly into a RenderTexture's memory, so an extra copy may be needed.

Dedicated rendering memory

Say you draw into a RenderTexture. If it's 1024x1024, 4 MB of memory is allocated and the rendering result is stored there.

But on some devices you can't draw there directly. Every so often you come across devices that can only draw into "dedicated rendering memory". Because of alpha blending and Z testing, drawing performs poorly unless the memory is quite fast, but fast memory is expensive, so you don't want much of it. Having a small amount of fast dedicated rendering memory on the side and doing all drawing there gets you performance at low cost. The Adreno 306 in the S2, the Xbox 360 and the Xbox One are built like this.

With such GPUs, once drawing is finished, the result is copied into the RenderTexture's own memory (the resolve step).

Drawing into dedicated memory and copying out (resolve)

If you do a lot of alpha blending and Z testing, everything except the final copy gets faster, enough to make up for the copy time, but for uses like this one that need neither alpha blending nor Z testing, there's no benefit. It just adds an extra copy.

Avoiding restore

Also, on GPUs built this way, drawing into one RenderTexture in two separate passes is very wasteful.

The first pass is drawn into the dedicated memory and copied (resolved) into the RenderTexture. Then, after drawing to a different RenderTexture, if you want to resume drawing into the original one, you need a copy in the opposite direction, from the RenderTexture back into the dedicated memory (the restore step). If you're also doing Z testing at that point, you need to copy the Z buffer too, so the resolve also copies the Z buffer, and it eats extra memory.

Copying back from the RenderTexture into dedicated memory (restore)

If you draw everything in one go, the Z buffer only needs to exist temporarily in the dedicated memory, so you don't even need to allocate one in main memory. And even if you think you're drawing in one go, if you leave the previous frame's contents in place, a restore will still happen. You need to either explicitly declare that "the contents are no longer needed" or clear it.

Personally I think "if a restore happens, you've lost", and the rendering library I built back in my C++ days was designed so that "a restore can never happen". In its interface, "the contents become undefined the moment a RenderTexture is made active", so you couldn't pick up drawing where you left off. Unity, unlike me, is nice and hides these details from you, but that means performance can drop without you knowing. So:

  • Before Graphics.SetRenderTarget(), call RenderTexture.DiscardContents() on the RenderTexture about to be set.
    • This signals that the RenderTexture about to be used will be completely overwritten, so there's no need to copy (restore) the data in main memory into the dedicated memory.
  • Clear with GL.Clear right after SetRenderTarget()
    • Actually overwriting all of it shows that no copy (restore) is needed.

I've set up the processing like this, which should eliminate restores, but I don't actually know whether they're really gone, because the manual doesn't document the behavior. Give me a break.

How to actually reduce SetRenderTarget changes

So switching render targets with SetRenderTarget tends to be slow, and the fewer switches the better. There can be other reasons it gets slow, too.

So how do we reduce them?

Using mipmaps for shrinking

GPUs have a feature for generating mipmaps (whether it really exists or just sets up a shader and draws internally, I don't know). It's not a Unity feature but one of the underlying OpenGL, so in many cases there's probably dedicated support for it. If so, it should be fast. No reason not to use it.

First, make a RenderTexture at 1/4 of the original resolution with mipmaps enabled.

var renderTexture = new RenderTexture(w/4, h/4, 0);
renderTexture.useMipMap = true;

That's the simple version, but in reality quite a few GPUs "can't generate mipmaps unless the size is a power of two", so to support them, I round the size up to a power of two. For example, 1280x720 at 1/4 is 320x160, which becomes 512x256. The leftover space is wasted, but let's not worry about it.

Then copy the original image into it. As I said, brightness extraction has to happen somewhere, and in this implementation it happens during this copy.

The image is copied into the center of the texture. For example, when placing 320x160 in 512x256, leave (512-320)/2 = 96 pixels on the left and right, and (256-160)/2 = 48 pixels above and below. If the image touches the edge of the texture, nasty things happen during the Gaussian blur.

If TextureWrapMode is clamp, the edge pixels get sampled many times during the Gaussian blur. If there's a bright pixel there, the edge becomes ridiculously bright, and since it only happens on one side, the result looks quite odd. Note that if the original resolution is already a power of two, there's no margin left, but I haven't handled that case here. Going from 512x256 to 1024x512 seems too wasteful, so I think it's safer to avoid the issue by adjusting the original resolution.

The drawing here isn't full-screen, so you can't use Graphics.Blit(). Draw using things like Begin(), Vertex3(), Texcoord() and End() of the GL class. It would also be fine to make a Mesh and draw it with Graphics.DrawMeshNow(). I haven't checked which is faster.

Mipmaps are generated automatically

When you draw into a RenderTexture whose RenderTexture.useMipMap is true, its mipmaps are updated automatically, so you just draw into the largest mipmap level and you're done.

However, mipmaps are generated all the way down to the smallest, 1x1. Only four are used here, 1/4, 1/8, 1/16 and 1/32, so the smaller ones aren't needed, but generating them costs next to nothing, so there's no need to worry. If you prepared separate RenderTextures for 1/4, 1/8, 1/16 and 1/32 and drew them yourself, there'd be no such waste, but you'd have to call SetRenderTarget() many times, which would probably end up slower.

And so the shrinking takes one DrawCall and one SetPass(). Internally, mipmap generation might amount to the same thing as calling SetRenderTarget and drawing with a shader, so it's possible this isn't any faster at all, or is even slower, but let's go with it for now.

People say "measure before you optimize", but in phone development your code has to run even on devices you can't measure on. Of course I do measure, but that's just a sample. You don't know whether it's fast on other devices, and in the worst case you don't even know whether it runs. PostProcessingStack v2 being sickeningly slow on my phone is a good example. It's the standard, so I'd assume it's been tested on a huge number of devices, yet there are still devices like mine where it doesn't run properly.

In situations like this, a bit of knowledge helps. If you know what GPU designs are out there and what's expensive to build into a chip, you can make guesses like "this is a cheap one, so it's probably weak here". That probably makes things at least a little better.

Reducing SetRenderTarget() for the Gaussian blur

Next is the Gaussian blur. Let's cut down the SetRenderTarget() calls here too. The trick isn't much different from the one used for shrinking. Separate RenderTextures for 1/4, 1/8, 1/16 and 1/32 drive up the count, so we just need to stop keeping them separate and put them in one.

This is even simpler than the shrinking step. There's no need for anything fancy like mipmaps; you just lay them out on one texture.

The four resolutions laid out on one texture

It looks like this. Normally the gaps between the images are filled with black, but here they're painted red to make them easier to see. The rectangles are spaced 16 pixels apart so that images at different resolutions don't mix during the Gaussian blur, and they're also inset 16 pixels from the edge of the texture so that nothing goes wrong at the screen edges.

Using the shrunken, mipmapped RenderTexture from before as input, draw into each rectangle of this texture with the horizontal Gaussian blur shader. There are four rectangles, so 8 triangles will do. Or you could specify GL.QUADS and call GL.Begin(). It's not full-screen, so you can't use Blit().

There's only one RenderTexture, so no switching is needed, and there's only one input texture too (albeit with mipmaps), so the Material parameters can stay the same. One SetPass(). You just draw 4 vertices per rectangle, 16 vertices in total, in a single DrawCall.

Then do the same thing once more with the vertical Gaussian blur. Prepare another RenderTexture with the same rectangle layout, call SetRenderTarget() again, call setPass() on the Material again, and draw 16 vertices with GL.

And that completes the Gaussian blur.

Reducing tex2D

Whether it's brightness extraction, the Gaussian blur or the final composite, most of each shader's work is tex2D. All they really do is fetch input with tex2D, multiply it by something and add it up. The number of tex2D calls translates directly into how heavy the shader is.

At the start, to show how hard blurring is, I said a blur with a radius of 10 pixels needs 441 tex2D calls. Separating it into vertical and horizontal passes with a Gaussian blur brings that to 21x2 = 42.

So how many is it in the current implementation?

In this implementation, the blur radius is 7 pixels. That's 15 pixels across, so doing it twice, vertically and horizontally, means 30 tex2D calls. But the resolution is 1/4, so divide that by 16: 30/16 is less than 2 per pixel at the original resolution. And for that you get a blur with a radius of not just 10 pixels but over 100. Impressive. I could never have come up with that myself.

There are also the 1/8, 1/16 and 1/32 resolutions, but their load is negligible: 1/64, 1/256 and 1/1024 respectively, barely registering. Halving the resolution cuts the pixel count to 1/4, and the load to roughly 1/4 too. Used well, this can make rendering that would normally be heavy surprisingly fast. As for the image quality lost to the error from shrinking, Kawase has again examined it in detail, but I haven't done anything about it here.

Using the bilinear filter

Every GPU today has hardware bilinear filtering. If you call tex2D with a UV at the center of four pixels, you get the four pixels mixed at 25% each. No reason not to take advantage of that.

Here the blur is done horizontally first, then vertically, so each pass only looks along one axis, mixing two pixels at a time. If you specify a UV halfway between two pixels, one tex2D fetches both. This way, 7 tex2D calls can do a blur with a radius of 6, that is 13 pixels across. The center tex2D takes just one pixel, and the other 6 each fetch two.

Fetching two pixels per tex2D with the bilinear filter

But with a Gaussian blur, the proportions in which pixels are mixed have to follow the normal distribution function. If you call tex2D at the UV halfway between two pixels, they're mixed 50/50, and it's no longer a normal distribution. What should we do?

Simple: shift the UV a little off-center.

Suppose the normal distribution coefficient of the pixel at distance 4 is 0.2, and that of the pixel at distance 5 is 0.1. Done naively, you'd call tex2D at the UV for distance 4 and multiply by 0.2, call tex2D at the UV for distance 5 and multiply by 0.1, and add them. But we want the same result from a single tex2D. To get it, sample at a UV where the distance-4 pixel is mixed in twice as much as the distance-5 pixel: just put the UV at distance 4.33. It's 0.33.. away from the distance-4 pixel and 0.66.. away from the distance-5 pixel, so the distance-4 pixel is half as far away and gets twice the weight. Then multiply the value from tex2D by the sum of the coefficients, 0.2+0.1 = 0.3, and you get the same result. In code-like form:

uvOffset = w1 / (w0 + w1);

w0 is the normal distribution coefficient of the nearer pixel, 0.2 for the distance-4 pixel in this example. w1 is the coefficient of the farther pixel, 0.1 for the distance-5 pixel. With the sum of the coefficients as the denominator and the farther coefficient as the numerator, uvOffset is 0.1/0.3 = 0.333. Add this to the nearer UV: 4 becomes 4.333.

In this implementation, I increased tex2D to 8 calls and made the radius 15. The center pixel gets sampled by two tex2D calls, which would double its weight, so I applied the technique above and shifted those UVs away from the center so the two calls together give exactly the right weight. Like this:

The sample positions of the 8 tex2D calls

The two central coordinates are at 0.65, closer to 1 (the neighboring pixel) than to 0 (the center pixel). This lowers the center pixel's share so that sampling it twice comes out just right.

Reducing Material.SetPass()

So the tex2D count has been halved, but as things stand, SetPass and DrawCalls don't go down.

To sample with tex2D and sum the results weighted by the normal distribution, each sample point needs 3 floats: 2 for the uv and 1 for the weight. But current Unity seems to allow only four texture coordinates per vertex, and passing 4 or 5 as the first argument of GL.MultiTexCooord3() was simply ignored.

So I have no choice but to send the data as Material properties, but then each resolution's rectangle needs different parameters, which means more DrawCalls and SetPass calls.

DrawCalls are expensive. On a cheap phone, a single DrawCall can take nearly 0.1 milliseconds, so 8 DrawCalls is 0.8 milliseconds. A 60 FPS game has to fit everything into 16.6 milliseconds, and losing 0.8 milliseconds of that to DrawCalls is pretty infuriating.

So let's reduce them. To do that, we have to stop putting per-rectangle constants on the Material. We need to make as many parameters as possible shared across all rectangles and set only those on the Material. Everything else can go in the vertex data. GL.MultiTexCoord3() can send up to four values, with 3 floats each.

First, halve the data by exploiting the symmetry of the UVs. The UVs of the four tex2D calls on the left and the four on the right are naturally symmetric: if you know the central UV, you just mirror around it. Extending the line from the first point to the next point in the opposite direction by some multiple gets you to the first point on the other side, and only that "some multiple" is set on the Material. It's the same at every resolution. The relevant part of the vertex shader looks like this.

o.sample4.xy = v.sample0.xy + ((v.sample0.xy - v.sample1.xy) * _InvertOffsetScale01);
o.sample5.xy = o.sample4.xy + (v.sample0.xy - v.sample1.xy);
o.sample6.xy = o.sample5.xy + (v.sample1.xy - v.sample2.xy);
o.sample7.xy = o.sample6.xy + (v.sample2.xy - v.sample3.xy);

The vertices sent to the shader only contain the uvs for the four pixels to the right of the center. Number 0 is the one closest to the center, number 1 is the next one to the right, and so on. Take the difference between number 0 and number 1, multiply it by the value set on the Material ("how many steps it takes to reach the innermost position on the other side"), and you get the position on the other side.

And so all four rectangles can be drawn with a single Material.SetPass(). The Gaussian blur takes one DrawCall each for horizontal and vertical, two in total.

Pre-combining the blurs

The final composite shader combines the four Gaussian-blurred images with the original image. It draws at the original resolution, so it has to call tex2D 5 times for every pixel at the original resolution. That's quite heavy. On a shrunken buffer, tex2D calls hardly add up to anything, but on a full-resolution buffer, even one extra tex2D makes a noticeable difference.

So let's add up just the blurred parts in advance.

The largest blurred image is 1/4, so first add all the blurs together into a 1/4-size image. That's 4 tex2D calls on a 1/4 buffer, which has 1/16 of the pixels, so the summing costs 1/4 of what one tex2D per full-resolution pixel would.

With that, the final composite shader drops from 5 tex2D calls to 2, quite an improvement.

That said, it adds one SetRenderTarget(), one SetPass() and one DrawCall, so in some cases it might end up slower. Also, the size of the largest blur (1/4) is adjustable, and you can blur at 1/1 if you want, so this pre-combining can itself be turned off. In fact, on a MacBook Pro (Intel i7 integrated GPU), which probably doesn't use dedicated memory, my impression is that it makes no difference, or even slows things down. Ideally, I'd detect whether a device uses the dedicated memory approach and switch methods accordingly.

Reducing tex2D even more

To cut tex2D calls even further, this could be done in multiple stages.

  • Add 1/16 and 1/32 together at 1/16 size (call this A)
  • Add 1/8 and A together at 1/8 size (call this B)
  • Add 1/4 and B together at 1/4 size

Doing it in one go takes 4 tex2D calls at 1/4 size, but split up like this, it's 2 tex2D calls at 1/16 size, 2 at 1/8 size and 2 at 1/4 size, which comes to 2.6 tex2D calls in 1/4-size terms, so it's faster.

Alpha blending offers another speed-up. If you combine 1/16 and 1/32 by setting 1/16 as the render target and drawing 1/32 scaled up with additive blending, each stage needs only one tex2D and no extra memory, and if you can ignore the cost of alpha blending, it's twice as fast.

But I didn't do that here. I don't want more SetRenderTarget() calls, and even going that far, the gain is tiny; remember that we're already at 1/4 size. Also, when adding with alpha blending, unless you have a high-precision float buffer, the values may overflow 8 bits, and on devices that draw into dedicated memory, a restore happens.

If you knew a device didn't use dedicated rendering memory, that would be fine, but there's currently no way to find that out at runtime, so you can't switch. You have no choice but to target the dedicated memory approach, common on slow, cheap devices, and accept pointless overhead on expensive, fast ones. I believe the basic rule of supporting many devices is "push the overhead onto the fast machines".

Improving quality

When you implement this kind of effect with low-precision, 8-bit buffers, precision becomes a real problem.

For example, say there's an image with a single white pixel surrounded by black. If you pass it straight to the Gaussian blur without subtracting anything during brightness extraction, how far does the light spread?

At 1/4, the brightness is already down to 1/16, because one pixel is spread over 16. 255/16 rounds to 16, so the brightness in the 1/4 image is only 16 (15 if truncated). Shrinking to 1/8 cuts it by another factor of 4, to 4. At 1/16 it's 1, and at 1/32 it's 0. In other words, this pixel isn't reflected at all in the Gaussian blur result at 1/32 resolution. A blur with radius 7 at 1/32 resolution spreads light over 200 pixels, but because of the lack of precision, in practice it never gets that far.

And even in the 1/16 buffer it's only 1, so the Gaussian blur will probably turn it all to 0. Even at 1/18 the original is 4, so it's doubtful any value survives.

In practice, a single white pixel leaks almost no color. Even in the 1/4 buffer, blurring 16 vertically and horizontally leaves at most 1 or 2, which you can't see. Even if you force it to show by raising the additive coefficient in the final composite shader, multiplying something with only three levels, 0, 1 or 2, by 100 and adding it gives a blocky, unusable image.

In other words, in reality "it won't look dazzling unless the bright area is large". With enough precision, even a small original value would spread far, so you could make it glow by using a large coefficient in the final composite.

Floating-point formats like RGB111110Float or ARGBHalf would greatly reduce this problem, but they aren't available in GLES2. ARGBHalf doubles memory consumption and lowers performance, so it's questionable, but if RGB111110Float is available, it seems worth using. However, it only works on devices that run GLES3, and you need to enable GLES3 in the build settings (I haven't tried it, but Metal is probably fine too). You could just enable GLES3 alongside GLES2, but you might take on hassles like "bugs that only occur on GLES3 devices". If you can't drop GLES2 anyway, going GLES2-only is also a rational choice (if anything, that's where I lean).

Note that RGB111110Float has precision issues of its own and may be tricky to work with. Blue has a different number of bits, so grays can pick up a strange tint, and you might even need dithering. To be honest, I've never used it, and I plan to experiment with it at some point.

ARGB2101010, on the other hand, has no such side effects and simply quadruples the precision of RGB, so it's probably easy to use. 1.0 is 1023 instead of 255, so values are that much less likely to drop to 0 when thinned out by blurring. However, it also needs GLES3.

By the way, SystemInfo.SupportsRenderTextureFormat seems to return true whenever the hardware supports a format, even in a GLES2 build. For example, my Kyocera S2 supports ARGB2101010 in hardware and returns true, but if you use it in a GLES2 build, nothing gets drawn at all. If you write logic like "use it if it's supported", note that you need to give GLES3 priority in the build settings.

Here I've stuck to GLES2 more than necessary, but for a product releasing now I think going GLES3-first is fine, and dropping GLES2 would cost you hardly any players. Assuming GLES3 makes many things simpler, so for a new title I think that's the way to go. "Making it run even on old devices" is just my hobby.

About measuring performance on the GPU side

This is a bit of a digression, but I'll also explain how I measured performance. Whenever you make something, you have to measure its performance, so there's no getting around the question of how.

This actually reuses the method from the Konch Bench I wrote about before, but I didn't explain it in that article, so I'll do so here.

Why measuring GPU performance is a pain

First, let me explain why measuring performance on the GPU side is tricky.

Normally, the GPU sends the rendered image to the screen 60 times a second. The chance to send it comes around 60 times a second, and if drawing finishes early, the GPU sleeps until the next one. So no matter how light the drawing is, you can't get more than 60 FPS. Once you're at 60 fps, any further savings don't show up in the FPS.

On some devices you can turn this waiting off, and then the FPS can go up to 100 or 200. But if the CPU-side processing is heavy, that becomes the ceiling. For example, if the CPU side takes 4 milliseconds, no matter how light the GPU work is, it won't go above 250 fps. And on phones and WebGL, it seems you can't change this setting anyway.

Slowdowns are tricky too. If a frame's processing fits in 1/60 of a second, it renders at 60 fps, but if it misses 1/60 of a second by even a little, it suddenly drops to 30 fps, because it waits for the next screen refresh. If processing runs slightly past 1/60 of a second (16.667 milliseconds) and takes 17 milliseconds, it sleeps for 16-odd milliseconds until the screen refresh at 33.33 milliseconds. So if you want a game that holds a steady 60 fps, it's best to assume you only have 13 to 14 milliseconds.

For these reasons, detecting something like "this change made it 2 milliseconds slower" isn't easy. If processing takes 15 milliseconds, you observe 16.667 milliseconds, that is 60 fps; add 2 milliseconds to make it 17, and you observe 33.333 milliseconds, that is 30 fps. As a result, processing that's only 2 milliseconds slower looks 16.667 milliseconds slower.

The method I used

So what can we do?

I measured the GPU load with the following procedure.

  • Prepare an operation with a fair amount of GPU load. Here, it's copying a texture full-screen into a 1024x1024 RenderTexture.
  • Prepare a mechanism that can repeat it many times with very little CPU load.
    • Adding just 4 vertices to a Mesh makes the GPU fill a whole screen. I built this as FillRenderer.
  • (A) With the post-effect on, measure how many fills it can do before the average frame time reaches 25 milliseconds.
  • (B) With the post-effect on, measure how many fills it takes for the average frame time to reach 41.67 milliseconds.
  • (C) With the post-effect off, measure how many fills it can do before the average frame time reaches 25 milliseconds.

25 milliseconds is exactly halfway between 60 fps and 30 fps: 60 fps is 16.67 milliseconds and 30 fps is 33.33 milliseconds. When it misses 60 fps half the time and waits for the next drawing opportunity, that's the point where the GPU load averages 16.67 milliseconds. At that point it waits an extra 16.66 seconds half the time, so the apparent average is 25 milliseconds. First, measure how many 1024x1024 fills it can do before reaching that point. Call it A.

41.67 milliseconds is exactly halfway between 30 fps and 20 fps: 30 fps is 33.33 milliseconds and 20 fps is 50 milliseconds. When it misses 30 fps half the time and waits for the next drawing opportunity, the GPU load should average 33.33 milliseconds, and the apparent average is 41.67 milliseconds. Say it manages B 1024x1024 fills at that point.

From these two tests, we know it can do (B-A) 1024x1024 fills in 33.33-16.67 = 16.66 milliseconds. So on this device, one 1024x1024 fill takes 16.66/(B-A) milliseconds.

Next, disable the post-effect and measure how many 1024x1024 fills it takes for the average to reach 25 milliseconds. Call this C. With the post-effect enabled it was A, and disabling it raised it to C, so the difference is C-A. We know the milliseconds per fill, so multiplying by that tells us how many milliseconds the post-effect costs.

For example, the measurements on the Kyocera S2 are as follows.

  • With the effect off, it reaches 25 ms at 12.6 fills
  • With the effect off, it reaches 41.67 ms at 30.6 fills
  • With the effect on, it reaches 25 ms at 7.40 fills

From the first two lines, we know it can do (30.6-12.6) = 18 fills in (41.67-25) = 16.66 milliseconds, or 1.08 milliseconds per fill. And from the first and third lines, post-processing on versus off differs by (12.6-7.4) = 5.2 fills, and 5.2 fills times 1.08 milliseconds gives 5.616 milliseconds.

The counts have decimals because FillRenderer accepts fractional counts (an improvement over Konch Bench). For example, for 2.5, it draws 2 full fills and one more at half size.

This isn't a precise measurement, but for something like this, a rough figure is fine. I think you should assume benchmarks are only good to two significant figures anyway. If you want precise measurements, you're better off with the profiling tools from the GPU vendors, but they're hardware-specific, and given the effort of installing them and so on, I'm not keen. On home consoles, where the hardware is fixed, it's a different story, but in phone development I think it's fine to stick to methods that work on any device.

By the way, on a MacBook Pro Mid 2014, it took about 2.7 milliseconds at roughly 1600x900. Many high-end phones outperform this machine, so even at high resolutions it should take around 5 milliseconds. That's a practical speed, isn't it?

Also, PostProcessingStack v2 measured about 4.3 ms in a PC build, which looked slower than mine (the measurement is imprecise, so I can't say for sure). However, quality and ease of use probably matter more, and I don't know how it does on other devices. If the load is bearable, I think you're better off with the standard one than with something of unknown pedigree like this.

A digression: measurement and heat

This is a complete digression, but heat becomes a problem when measuring performance. Running the GPU flat out generates heat, and when cooling can't keep up, the device forcibly lowers performance to keep from overheating. On the MacBook Pro Mid 2014, performance had dropped to around 60% about three minutes in. Naturally the same thing happens on phones. The smaller the device, the worse its heat dissipation and the more vulnerable it is to heat damage, so it has no choice but to throttle like this. People like me wonder what good performance is if you can only use it for a few minutes, and I think you need to take benchmark scores with a grain of salt. It's doubtful you can really get that performance in practice.

By the way, my S2 didn't get very hot even at full load, and didn't seem to lose performance. That's another advantage of cheap devices. The S2 in particular is shockproof and waterproof, which makes heat dissipation terribly difficult, so presumably it can't use a high-performance chip that runs hot. As a result its performance tends to be stable, which is very handy for testing what you've made.

What's left to do

There are still things that could be improved.

Sometimes the result looks ugly

I'm not sure why, but depending on the original resolution, the blur at the low resolutions comes out oddly ugly. It seems to go wrong when the X-direction Gaussian blur is applied at an odd width, but I haven't looked into it yet.

The X-direction blur reads data from the mipmaps, so the problem may lie there. It might be fixable by, say, requiring GLES3 or higher and using tex2dlod(). That's a job for later.

If anyone has advice, please send it to https://twitter.com/hirasho.

Wasted memory

It actually wastes some memory. In this implementation I allocate a separate RenderTexture for pre-combining the blurs, but the RenderTexture used for the X-direction blur could be reused, since it's no longer needed by then.

But during debugging I needed to dump textures, so I set up a separate texture for convenience, and it's stayed that way. After all, this is at the "it worked yesterday!" stage and hasn't been tested in production at all, so I'd like to fix it once it's been battle-tested in a real product.

By the way, I debug by saving textures to files and sending them to Slack, using a modified version of the sample code from this article I wrote before. It has more files, so it's more of a hassle to set up, but it has more features. Feel free to use it.

It makes too little physical sense

Here I simply blurred and added. The implementation is fairly involved for performance reasons, but all it does is "blur and add". If you want to get reasonably close to how light actually "leaks" in reality, that kind of sloppiness only gets you so far. As game graphics become more realistic, effects have to become correspondingly realistic, or the image looks wrong.

In reality, bright light appears to leak because of diffraction and scattering. Diffraction and scattering don't change the total amount of light; it may decrease, but it never increases. Yet when this effect is enabled, the overall brightness goes up, which is a flat-out violation of physics. So I think it would be good to at least add a mechanism so that "raising the effect strength doesn't increase the total amount of light".

However, because of the precision problem mentioned above, more of the energy is lost than in reality, so if you naively implement energy conservation, it may end up too dark. It may be better to wait until high-precision buffers are something you can take for granted.

In closing

This was the first rendering-type code I'd written in several years. Since it had been so long, and since there's a standard solution in PostProcessingStack, I kept thinking things like "can I even still do this?", "making my own is pointless" and "come on, this is 15-year-old technology", but I got comments from colleagues like "I want that" and "if you'd made it six months earlier I'd have used it", which cheered me up a bit.

I really wanted to put it into Tokyo Prison , but throughout development we always had bigger problems, and there was no time to play around writing shaders. And a 2.5D game doesn't need post-processing much anyway...

I'm sorry it's unclear who this article is for. It mixes explanations for people who don't normally do rendering, like "what is bloom?", with explanations only people who've written code for home consoles with the hardware design in mind will follow. If there's demand for this kind of thing, I'd like to consider writing more thorough articles.

If I do something with rendering next, it'll probably be "something that runs even on phones", but what? Something like DOF (depth of field)? I did that about 13 years ago too...

References