Memories of Indexed-Color Textures: The Good Old Palette

Hello. I'm Hirayama from the Technology Department.
This article is about implementing indexed color, of all things, in this day and age. While researching texture compression I came across an article on the SEGA TECH BLOG and wanted to try it myself.
I'll give away the conclusion up front: "Isn't ETC2 good enough?" Feel free to treat everything from here on as a hobby project.
History
Once upon a time there was an image format called "indexed color". In an age without decent compression algorithms, to avoid spending 32 bits on every pixel, you prepared a table like "number 0 is #ffee88, number 1 is #8530ee, ..." (a Color Lookup Table, CLUT for short, or a "palette"), and stored only the color number in each pixel. With a 256-entry table each pixel takes 8 bits (1/4); with a 16-entry table, 4 bits (1/8); and if the table had only 2 entries, 1 bit (1/32). Sorry to sound like an old man reminiscing, but when I was a new hire (2002), the market was ruled by a machine on which "nothing but 16-color palettes is really usable", which was painful even back then, and all sorts of things were drawn in 16 colors.
After that, though, DXT (DirectX Texture Compression; the same thing as S3TC) became commonly available on many machines, and for most images DXT turned out to look better, and run faster, than forcing the color count down to fit a palette. DXT1 (a.k.a. BC1) could represent images without translucency reasonably well at 4 bits per pixel, and DXT5 (a.k.a. BC3) could represent even images with translucency reasonably well at 8 bits per pixel.
Time moved on into the smartphone era, and formats newer than DXT appeared, such as PVRTC, ETC and ASTC. ETC2 support became mandatory in GLES 3.0, and ASTC support mandatory in GLES 3.2. The newer the format, the more advanced it is, and in most cases it achieves better image quality at a smaller size.
So, if you can ignore machines that can't run GLES 3.0, a sensible approach would be "compress with ETC2 for now, and think about it separately if it looks bad". Plain ETC2 represents opaque images at 4 bits per pixel, and ETC2+EAC can represent even translucent ones at 8 bits per pixel.
Advantages of using a palette
In this day and age, a palette is pretty much useless, but it does have a few advantages:
- No block noise
- Fast compression
- You can see the compressed result before putting it into Unity
- Works even with only GLES2 support
Let's look at them one by one.
No block noise
Formats like DXT, ETC, ASTC and PVRTC don't store information pixel by pixel; they compress in chunks of a certain size. DXT, for example, prepares a palette of 2 colors for each 4x4 block of 16 pixels, and records "the blend ratio of the 2 palette colors" for each of the 16 pixels. There are 4 possible ratios, so that's 2 bits.
So a 4x4 block can hold only 4 colors, and 2 of those are interpolated. Even when "there's red, blue and green in there", only two of them make it in. The result is ugly noise along every 4x4 block boundary. This is called block noise. Newer formats go to great lengths to make it less noticeable.
A palette, on the other hand, doesn't process in blocks, so there is no block noise.
Fast compression
Usually, the newer the compression format, the more elaborate it is, so compression takes time. With large images it's not unusual for it to take minutes, and you can't get by without parallelizing or using the GPU. But if there's no way to "compress it yourself and put it into Unity as is", you have no choice but to leave it to Unity, and you're at the mercy of however long Unity takes.
With a palette, the processing after color reduction is simple. You just number the colors and replace the color of every pixel with its number; the importer I prototyped for this article processes a 2048x2048 image in about 1.5 seconds. Running it through a tool written in C++ or similar rather than C# would make it even faster.
You can see the compressed result before putting it into Unity
As far as I know, Unity can't import something that is already compressed. Compression happens at import. If the artist uses Unity, they can see the result of compression at that point, but only for the current platform. Unless you switch platforms, you don't know what it will look like on other devices. Some teams use a setting that holds off compression at import until build time, and in some places the artists don't use Unity at all. I suspect there are many cases where you don't know how much the image has degraded until you build and look.
For artists who want control over image degradation too, that must be infuriating, and artists may even end up never knowing about "degradation from compression" at all. You get things like "On the device, only on iOS, this button looks weirdly fuzzy. What's that? A bug?"
With a palette, color reduction is done on the artist's side, in Photoshop or OPTPiX or whatever, so you can see it before it goes into Unity.
Works even on machines that only run GLES2
In this implementation the texture format is ostensibly Alpha8. That format is supported on every device, so you don't need to worry about OpenGL ES versions or Metal versions. It should run even on quite old machines.
Drawbacks of a palette
On the other hand, a palette has drawbacks you can't do anything about. It can only be used where these drawbacks don't matter.
- Slow
- A hassle
- Works well only for a limited range of images, and results vary wildly depending on which color-reduction tool you use
Slow
Formats like ETC2 are decoded in hardware. They are never slower than uncompressed RGBA32. The smaller size makes transfers faster, so they are usually faster than uncompressed.
If you insist on a palette anyway, there's no hardware support, so the only option is to do it in a shader. The first texture read gets the color number, and the second texture read converts the number into the actual color. Reading twice is naturally slower.
Also, I once saw a machine that was "slow enough to make you cry if the texture coordinates are not determined when the fragment shader starts running". If machines like that are still around, it will be surprisingly slow on them. Since the second texture read uses the color number from the first read as its texture coordinate, the texture coordinate isn't known until the first read finishes.
And worst of all, you can't use the hardware's bilinear interpolation. Normally, if you sample between 4 pixels, the hardware returns a color blended from the 4 pixels. That's true of ETC and ASTC too. With a palette, though, blending the color numbers is no help. If the 4 pixels are numbers 0, 1, 2 and 3, you have to blend color 0, color 1, color 2 and color 3, but leaving it to hardware bilinear interpolation means reading color number (0+1+2+3)/4 = 1.5. No such color exists. Without bilinear interpolation it's practically unusable, so you end up writing bilinear interpolation in the shader, which is long, slow and a pain to write. Nothing good about it.
On top of that, in Unity, draw calls are always split by material. You make a dedicated component that inherits from UnityEngine.UI.Graphic, and if each one gets a different texture, each one ends up with a different material. Palette images can't be put into an atlas, so whatever you do, you get as many draw calls as there are components. It's hard on both the CPU and the GPU.
A hassle
With a compression format like ETC, you change the import settings in the Inspector and it gets imported that way. And compressed or not, you can draw it with an ordinary UnityEngine.UI.Image.
A palette, however, is not a format Unity supports. You can't set it in the Inspector; you always need to write an importer script. And since it uses two textures, the color-number texture and the palette texture holding the colors themselves, and draws with a dedicated shader, the component you use to display it is a different one as well.
In this implementation the import is automated to some extent: if the path contains a folder named "CompressToIndex16" or "CompressToIndex256", the image is imported as a palette image. But the component is a dedicated one, and you have to specify two images in the Inspector. And if you later decide to "drop the palette", you delete the two split textures from Assets and swap out the components too. It's a hassle.
Works well only for some images, and results depend on the tool
It's fine if there are few colors, but images with many colors inevitably run short of colors. On top of that, translucent areas greatly increase the number of colors, which makes it even worse.
And the result differs completely depending on which tool you use for color reduction.

Top left is the original image, top right is reduced by OPTPiX, bottom left by ImageMagick, and bottom right by GIMP. OPTPiX looks pretty clean, but ImageMagick is noticeably worse, and GIMP is out of the question (GIMP probably doesn't build the palette including the alpha channel).
To sum up, the images where palettizing pays off are those with "few colors, where block noise is unacceptable". And images where "block noise is unacceptable" are, in most cases, images with crisp outlines. For example, "only the colors of a purple-to-white gradient, with high-resolution curves drawn in it" or "a strangely high-resolution black-and-white image that's mostly line art" seem like they might have potential. On top of that, a smart color-reduction tool is a prerequisite. I could only test OPTPiX because its beta happened to be free to try; otherwise I might have given up before even writing this article.
By the way, color reduction with ImageMagick can be done with the following command.
convert hoge_in.png -dither FloydSteinberg -colors 256 hoge_out.png
Tweaking the options might make it a little better. ImageMagick comes in handy now and then, so it's good to keep it as an option.
Implementation
By this point I've pretty much lost any desire to use it, but I did go and implement it, so let me show you. I've built a working version with WebGL and put it up. The source code is here.

Here's what it looks like running. The top three are palettized to 256 colors, and the bottom three were made black where transparent, converted to black and white, and palettized to 16 colors. I couldn't imagine 16-color versions of normally colored images being usable, so I limited the test to black and white, where I could at least think "maybe there's a use for it?!". Monochrome manga-style images, for example, might work.
In both rows, the left is the original image before palettizing (already color-reduced) on a UnityEngine.UI.Image, and the center and right are palettized. The difference between center and right is whether bilinear interpolation is on. The center has interpolation, so it holds up to scaling to some extent. The right has none, so scaling it produces aliasing noise. Unless you're firmly committed to "always displaying it pixel-perfect (never scaled up or down)", it won't be usable without interpolation. Smartphone resolutions are all over the place, and you can't count on a fixed one.
Structure
What I built consists of the following:
- An importer (IndexedColorImageImporter)
- A dedicated RawImage-like component (IndexedRawImage)
- Four dedicated shaders
- A shader holder class (IndexedRawImageShaderHolder)
Besides these, there's the sample's main script, Sample.cs, and prefabs and images for it. You don't need these to use it in your own project.
Importer
The importer inherits from UnityEditor.AssetPostprocessor and processes image files whose path contains a specific string. Going around tweaking each image's import settings in the Inspector is a pain and a source of mistakes, so on our Tokyo Prison we switched the compression type based on the path. I've done it the same way here, but this is something each product will need to set up to suit its own circumstances.
PreProcess
First, if the file is a target, OnPreprocessTexture() does the following:
importer.alphaIsTransparency = false; // avoid having it altered behind our back
importer.isReadable = true; // can't do anything if we can't read it
importer.textureCompression = TextureImporterCompression.Uncompressed;
importer.mipmapEnabled = false; // no mipmaps (probably not impossible, but for now)
If alphaIsTransparency is true the image gets altered, which is a nuisance, so I set it to false, and I set isReadable to true so the pixels can be read. I think it's possible to make a version with mipmaps, but it's not easy. It's too much hassle, so I left them out this time.
Also, if the import target is an already-processed number texture (index), the format is set to Alpha8, cutting the size to 1/4.
var settings = new TextureImporterPlatformSettings();
settings.format = TextureImporterFormat.Alpha8;
Then the settings made this way are copied and applied for four platforms: Standalone, Android, iOS and WebGL. Standalone builds are handy for debugging and measurement, and WebGL builds are handy for letting people try small samples like this, so it doesn't hurt to cover them.
PostProcess
Next, the conversion itself. It runs after the import finishes, so I implement OnPostprocessTexture(). For 256 colors, for example, it looks like this:
bool TryCompressToIndexed256(Texture2D texture, string path)
{
// build the color dictionary
var srcPixels = texture.GetPixels32();
var map = MakeColorMap(srcPixels, 256);
if (map == null)
{
return false;
}
var tableTexture = MakeTableTexture(map, 256);
var indexTexture = MakeIndexTexture256(map, srcPixels, texture.width, texture.height);
var lastPeriodPos = path.LastIndexOf('.');
var outPathTrunk = path.Substring(0, lastPeriodPos); // remove the period and after
Save(tableTexture, outPathTrunk + "_table256.png");
Save(indexTexture, outPathTrunk + "_index256.png");
return true;
}
- Get the pixel array with Texture2D.GetPixels32().
- Count the colors and build a table of which color is which number (MakeColorMap())
- Generate the palette texture (MakeTableTexture())
- Generate the number texture (MakeIndexTexture256())
- Decide the file names and write them out
That's the flow. The details aren't hard, so I think you can just read the code, but there are a few small tricks, so I'll describe them briefly.
First, building the color-to-number table: the standard Dictionary is slow, so I wrote my own hash table using open addressing to speed it up. With the standard one, generating a 2048x2048 image took about 9 seconds; with my own it dropped to about 1.5 seconds. If you don't need deletion, the keys are ints, and you can estimate the maximum count, you can implement a hash table in under 100 lines, so if speed is bothering you, it's worth a try.
The palette texture is generated as a long, thin RGBA32 texture, 256 wide and 1 high. It just lines up the colors in number order.
The number texture just replaces each pixel with its number and writes it into the alpha channel, but SetPixels32() can only be used for ARGB32 or RGBA32 with 8 bits per channel, so I call SetPixel once per pixel.
Here are the results.



On the left is the original image, in the center the number texture with the numbers written into alpha, and on the right the palette. The total size went from 273.1 KB down to 68.3 KB + 1 KB.
About 16 colors
Finally, the 16-color palette texture: there's no such format as Alpha4, so two pixels are stored in one Alpha8 pixel.
var composedIndex = (index0 << 4) | index1;
Because of this, the horizontal resolution is halved.


If the original width is odd, drawing every pixel exactly looks like a pain (I haven't even properly thought about whether it's possible at all), so keeping it even is the safe choice.
Dedicated component
The Inspector of the dedicated component, IndexedRawImage, looks like this.

There are slots for the two textures, a setting to enable or disable bilinear interpolation, and then, as with an ordinary UnityEngine.UI.Graphic, the RaycastTarget toggle and the SetNativeSize button.
Internally it generates a material dynamically, and switches the shader depending on whether the palette texture's width is 256 or 16 and whether bilinear interpolation is enabled.
To customize how the Inspector looks, I made a class inheriting from UnityEditor.Editor and implemented OnInspectorGUI. When a texture or the like is set in the Inspector, the shader may change, so the material is rebuilt; but OnValidate isn't called when items you added to the Inspector yourself change, so you have to detect changes yourself in OnInspectorGUI(). Like this, for example:
EditorGUILayout.BeginHorizontal();
GUILayout.Label("IndexTexture");
var newIndexTexture = (Texture2D)EditorGUILayout.ObjectField(self._indexTexture, typeof(Texture2D), false);
if (newIndexTexture != self._indexTexture) // with a custom editor, OnValidate is not called automatically
{
self._indexTexture = newIndexTexture;
self.OnTextureChange();
self.SetMaterialDirty();
}
EditorGUILayout.EndHorizontal();
It's a hassle, but there's no way around it.
Where to keep the shaders
Since the material is created dynamically with new and the shader is set on it, the shaders have to be kept somewhere. Here, I place a component called IndexedRawImageShaderHolder somewhere in advance and set the shaders in its Inspector.

Pretty gross, right? Since the shaders are under Assets, you could just find them with Shader.Find() and pass them to the Material constructor, but that only works in the editor. Without an explicit reference they aren't included in the build, and you end up with the "it renders purple in the build!!" accident.
This happened during the development of Tokyo Prison too, and it made me very angry. You can also explicitly specify shaders to include in the build, and that's what we did in Tokyo Prison, but I want the editor and the build to go through the same path as much as possible, so this time, hassle though it is, I chose to put an object that actually holds the references in the scene.
Putting them in Resources and loading them is another option. That feels cleaner, but as things pile up under Resources, unused assets accumulate and it gets terrible (it did). Since things may be loaded with dynamically generated paths, establishing that something "isn't used" is quite hard. Partly for that reason, I personally would rather not put much under Resources.
Shaders
There are four shaders:
- 256 colors, point sampling
- 256 colors, bilinear sampling
- 16 colors, point sampling
- 16 colors, bilinear sampling
The most basic is 256-color point sampling.
Shader "UI/Indexed256"
{
Properties
{
_MainTex ("MainTexture", 2D) = "white" {}
_TableTex ("TableTexture", 2D) = "white" {}
}
SubShader
{
Tags { "Queue"="Transparent" }
LOD 100
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _TableTex;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
half index = tex2D(_MainTex, i.uv).a;
fixed4 col = tex2D(_TableTex, index);
return col;
}
ENDCG
}
}
}
It defines the two textures to set on the material, sets the Queue to Transparent in the SubShader, configures alpha blending in the Pass, and the rest is the body of the fragment shader.
The fragment shader is simple: the first tex2D looks at the number texture (_MainTex) to get the color number stored in alpha, and that is used as the texture coordinate to get the color from the palette texture (_TableTex). Two lines and done.
Bilinear
The bilinear shader is a real pain. The fragment shader looks like this:
// determine UVs
half2 texcoord = i.uv * _MainTex_TexelSize.zw; // convert to pixel coordinates
texcoord -= 0.5; // i.uv is at the pixel center, so in integer units it carries 0.5. Subtract it
half2 texcoordFrac = frac(texcoord);
half2 uv00 = (texcoord - texcoordFrac + 0.5) * _MainTex_TexelSize.xy; // add back the 0.5 subtracted earlier
half2 uv11 = half2(
uv00.x + _MainTex_TexelSize.x,
uv00.y + _MainTex_TexelSize.y); // add one pixel's worth of UV
half2 uv01 = half2(uv00.x, uv11.y);
half2 uv10 = half2(uv11.x, uv00.y);
// get indices
half index00 = tex2D(_MainTex, uv00).a;
half index01 = tex2D(_MainTex, uv01).a;
half index10 = tex2D(_MainTex, uv10).a;
half index11 = tex2D(_MainTex, uv11).a;
// get colors
fixed4 col00 = tex2D(_TableTex, index00.xx);
fixed4 col01 = tex2D(_TableTex, index01.xx);
fixed4 col10 = tex2D(_TableTex, index10.xx);
fixed4 col11 = tex2D(_TableTex, index11.xx);
// bilinear
fixed4 col00_01 = lerp(col00, col01, texcoordFrac.y);
fixed4 col10_11 = lerp(col10, col11, texcoordFrac.y);
fixed4 col = lerp(col00_01, col10_11, texcoordFrac.x);
return col;
It does a separate tex2D on the number texture for each of the 4 surrounding pixels, a separate tex2D on the palette texture for each, and then blends them with 3 lerps, applying a bilinear filter by hand. A detailed explanation could fill a blog post on its own, so I'll skip it here.
Supporting 16 colors
With a 16-color palette, one pixel holds the numbers of two pixels, so you have to separate them. Newer machines can do integer arithmetic in shaders, so you can pull them out easily with bit operations, but old machines can only handle floats. Like this, for example:
half indexEncoded = tex2D(_MainTex, i.uv).a * (255.01 / 16); // integer part is the left pixel, fractional part the right pixel. The .01 guards against error.
half indexRight = frac(indexEncoded);
half indexLeft = (indexEncoded - indexRight) / 16;
The alpha holds a value from 0 to 1; first multiply it by 255.01. Why not 255? Because when the texture width is something awkward like 239, rounding errors appear. If (1/239)*239 came out as 238.9999, it would become 238 when converted to an integer. This avoids that. Then divide by 16. For 239, say, the integer part then holds the left pixel's number and the fractional part the right pixel's number. Applying frac extracts the right pixel's number, and subtracting that from the original and dividing by 16 extracts the left pixel's number.
Then you determine whether the pixel you're about to paint is the left or the right pixel.
half texcoordX = i.uv.x * _MainTex_TexelSize.z; // convert to pixel coordinates (in the half-width texture)
// double it to get the "original width", then halve it: frac 0.5 means right, 0 means left. Doubling then halving leaves it as is.
half index = (frac(texcoordX) < 0.49) ? indexLeft : indexRight; // be a little lenient in case of error with non-power-of-2 textures
Multiply uv.x by _MainTex_TexelSize.z, which Unity provides and which holds the texture width. This puts the texture coordinate in pixel units. The 16-color texture is half the width, so if the original is 239, the resolution is 120. That gives values from 0 to 120, and the fractional part is 0 if the original was a left pixel and 0.5 if a right pixel. But to allow for rounding errors, it checks whether it's below 0.49.
16-color bilinear is even more of a pain, so if you have time on your hands, try deciphering it. If you find a bug, I'd be delighted to hear from you.
Speed
Now that I've gone and built it, let's measure the speed of this obviously slow-looking thing. Measurements were done on a MacBook Pro Mid 2014 (i7 3GHz), with WebGL on Chrome and with a Standalone build.
Measuring speed on the GPU side is quite tricky: on machines where you can't turn off vertical sync (VSync), the moment it dips slightly below 60fps it drops to 30fps, so you can't compare by fps. So I took the approach of "increasing or decreasing the number of images until it's around 25fps, and using that number as the score". In other words, I looked for the number of images at which it just barely drops below 30fps and bounces between 30fps and 20fps.
Draw calls increase in proportion to the number of images, so on a machine with a very slow CPU there's a concern that CPU load becomes the bottleneck and hides the shader-side speed, but when drawing full screen, the GPU should surely be the bottleneck.
| Ordinary Image | Dummy | 256 | 256Bilinear | 16 | 16Bilinear | |
|---|---|---|---|---|---|---|
| WebGL | 190 | 117 | 120 | 103 | 104 | 73 |
| Standalone | 215 | 157 | 146 | 117 | 156 | 118 |
The ordinary Image is the fastest. Dummy is a shader that just does tex2D on the number texture. It's only one line, so you'd expect it to be the fastest, but it came out quite a bit slower than Image, perhaps affected by having a separate material and more draw calls. If you filled a Mesh with vertices yourself and drew it with a MeshRenderer, the draw calls wouldn't increase and you could see the pure GPU load, but in most cases you'll be using UnityEngine.UI, so I'll call this good enough (someone please do it).
The other thing you can tell is that enabling bilinear makes it slower. Still, it's not even 1.5 times slower, so the difference is smaller than I expected.
Why 256 colors and 16 colors swap places between WebGL and Standalone is a mystery. The 16-color version could be faster since the texture is half the width and puts less load on memory, but the shader side should be heavier because of the extra computation. Maybe that balance differs between WebGL and Standalone. I don't really know. I'd like to see it on actual smartphones too, but building for them is a hassle, so I skipped it this time. I'd be delighted if someone measured it.
Ancient technology: palette animation
Back when palettes were in common use, people used the painstaking trick of "rewriting only the palette while sharing the number texture, to make color variations in very little space".
Even if the image itself was 1024x1024 or 2048x2048, simply preparing multiple palettes let you change the image's colors wholesale. If an ancient game from the PlayStation 2 era or earlier has color-swapped art, chances are it was done this way. Player 1 and player 2 colors, color-swapped enemies in RPGs, that kind of thing.
Parts that blink periodically were also sometimes done by changing the brightness of the palette. Rewriting just 16 or 256 colors is fast, so it's possible to change them on the CPU every frame. You can still do this today if you want to. While I was at it, I added a feature like this to the sample.

Moving the slider changes the colors. The colors in the palette are converted to HSV, the slider value (0 to 360) is added to H (hue), and the result is converted back to RGB and written. Today it would be better to do it on the GPU rather than the CPU, reducing wasteful CPU⇔GPU transfers.
In closing
"It wasn't as slow as I thought, but normally you'd go with ETC2." So the conclusion stays the same.
If you only target GLES3 and above, I think you should try ETC2 first. If it's opaque, you can use ETC1 even on GLES2 (though that's tough unless you're willing to drop old iPhones). Even if you want to cut size further with 16 colors, ETC1/ETC2 without alpha is the same size.
If palettes ever get their turn, it's probably when the image quality is intolerable, or when it has to run on GLES2 machines including old iPhones. And palette animation.
That said, I think I'll keep it in the back of my mind. Compression that takes no time, and artists being able to see the compressed result on their side, are quietly nice features.