Friday, February 7, 2014

NES Palette

Traditionally, one writes a hello world program when they first start learning a new language or platform. Unfortunately, there is a lot of graphics related material that one must understand before they can write Hello World for the NES, so the next few NES articles will cover the PPU. I will start in higher level concepts then finish by writing a hello world program in 6502 Assembly Language.

Before I begin, I should point out that today the term bitmap is incorrectly used to indicate a raster graphics image. Technically speaking a bitmap is a two-color image with each pixel of the image being a bit. I am using the term to represent a grid of pixels that form an image. This is the common usage of the word, even if it technically is not the correct usage.

Today it is fairly simple to create and manipulate images.  When writing code to manipulate bitmaps most the time you are dealing with pixels in the RGBA (Red Green Blue Alpha) format. This means that each color component is a byte an each pixel requires 32 bits. As today memory is so much cheaper than it was a couple of decades ago, this is not that big of issue. This is a fairly inefficient way of storing graphics as not every color available is used. Older graphic cards/chips reduced the total number of colors available to a small number of colors. Instead of specifying the color in RGBA format, bitmaps would just hold a number indicating what palette index to use. The NES has a 64 color palette as shown below. As you can see, 8 colors are not actually available and there are a couple of colors that are almost identical, so the palette is not really64 colors.




Using only 6 bits per pixel is certainly a drastic reduction from using 32 bits per pixel, but this can be taken even further. If we make the image a grid of 8x8 pixels and give each tile in this grid it's own 4-color palette taken from the 64 color palette.  To reduce things even further, we don't really need a palette per tile, instead lets have four palettes that the tiles can use. Sprites can also have their own separate set of palettes for a total of 8 possible palettes.

This is very simple. Simply to set the palette you simply send 32 bytes to the PPU, with each byte being what color from the 64-color palette to use. Of course, things are not quite that easy. The first color in the first palette represents the background color. This will be the same color for the other 7 palettes so the first of the four colors is always the background color. Due to the way the PPU is set up, writing a color into the first sprite-palettes first color will also set the background color so when putting together the palettes you need to keep the background color in mind.

This now leads to the tiles. Having every tile uniquely programmable would take a lot of memory. Instead, lets limit the tiles to 256 different tiles and call this a character set. Character Sets will be discussed next.

No comments: