Thursday, April 17, 2014

NES Sprites

When programmers talk about sprites they are not usually talking about the mythical variant. They are referring to a special graphical object that has transparent parts and floats above the display without altering what is behind it. This seemingly magical behaviour is likely why programmers started referring to these objects as sprites. In fact, on the 2600, they were referred to as Player Missile Graphics. Sprite Graphics clearly rolls off the tongue better.

Not all graphics hardware supports sprites, and even when they do the specifications for the sprite can vary wildly. When emulating sprites in software, the software needs to be able to preserve what is behind the sprites and then draw the sprites over the display. With multiple overlapping sprites this can be complex, especially if speed is important. Thankfully the NES supports hardware sprites so we don't need to get into display lists and dirty rectangles here.

The NES supports 64 sprites on the screen at the same time, though the hardware is limited to displaying 8 sprites on a single scan line. To get around these limitations games that need more sprites or more than 8 sprites on a scan line can shuffle sprites around so the visible sprites change from frame to frame. This has the downside of causing a noticeable flickering effect. Some emulators do not emulate the 8 sprites per scan line limitation so will only flicker if you use more than 64 sprites. I prefer emulators that keep hardware limitations and bugs as that makes it much more likely that whatever I create using the emulator will run fine on real hardware.

Each of the 64 NES sprites take 4 bytes of memory. The layout of this data may seem rather haphazard but is actually very logical from a hardware perspective. Sprite data is set up as follows:

Byte 0 holds the Y coordinate. To know if it needs to draw a sprite on the current scan line this value is used making it the first piece of sprite information needed.
Byte 1 is the character to draw. Hardware needs to know this to grab the data from the pattern table.
Byte 2 is the display flags that alter how the sprite is displayed so is obviously the next piece of information the hardware needs. The bits are set up as follows:
        Bit 0 and 1 indicate the palette to use
        Bits 2 though 4 are not used
        Bit 5 When set puts the sprite behind the background image.
        Bit 6 Flips sprite horizontally when set
        Bit 7 Flips sprite vertically when set
Byte 3 holds the X coordinate. Once the hardware knows what it is drawing it needs to know where on the line it is going to be drawn.

We now know enough about sprites to create a demo, which will be next.

No comments: