The PC 2D Blitter Engine: How Hardware Drove Color Compression and RLE
Recently reread a set of domestic 2D end-run engine source codes from the early 2000s (Blitter architecture, DirectDraw drawing) with two modules that I was impressed with: an Occtree colour numerator and an RLE code with Alpha tags. They're not all advanced algorithms, they're all found in textbooks, but... Why do these two algorithms come together in this way? It's only possible to figure out when the clock goes back to that time.
The article begins with a reference to the hardware restrictions, and goes through the history of these two things. All the code in the text is a rewrite of my symmetrical pseudo-code, and it's a restatement of the expression structure.
0, turn first: two 2D drawing lines for the game and PC
Before it goes on, it's worth explaining the fundamental difference between the two-D drawings of the Game Machine and the PC -- the engine that we're talking about here, the latter way.
Graphical chip (PPU / VDP) for games (red and white machine, overmanned, MD generation) There is no frame buffer.. The way it works is... Scanline synthesiser (scanline complexor) Chips are in real time synchronized with CRT electronic beams, and every single scanned moment, the hardware is on-site to synthesize the background, the elves, the window layer by priority, the top colour, the output -- the image is never landed into a frame, and the entire "side-scanning" is done. This structure is extremely friendly to the elves: the elves are essentially "a one-dimensional object belonging to a single scanning line" and the hardware only makes OAM search and superimposes on each line, with zero RAM copies; But the price is also hard -- the maximum of all the elf numbers per line, the co-screen numbers, the elf sizes are all welded to the chips, and there is no transparency, no scaling, no rotation of these freedoms. The game is for certainty with flexibility.: The rate of retrofitting is absolutely stable, and the image structure is broken by the hardware specification.An early image video chip count.and A graphic route selection for home-made retrobus mainframe, not spread here)
PC's going the other way. IBM PC has never given a decent 2D acceleration hardware, VGA just one piece. Writeable linear frame buffer From the 64KB of Mode 13h to the presence of DirectDraw Surface, it's basically the memory of "a piece of you to paint and finish my top screen." No one's going to synthesize your scans. Cover, cut, transparent, mixed. The software is self-counting.: Take the elves as a small rectangle and move them into the frame buffer -- this is the block transfer structure. The word "blitter" is derived from the Blitter chip of Amiga and the Blitterer of Atari ST, which have the two machines to make hardware; PC, it's more about a set of things. Software block load engine One of the main characters in this article is the elf grapher in this engine. The trade-off of the frame buffer route is the opposite: PC is using certainty for flexibility. Without every line of elves, the elves can change as much as they want, as they want to, at the cost of each pixel.
This is about the complete answer of the PC route around 2000: when all pixels have CPU hands, color compression and RLE are the two unlearnable axes.
I. Quote: My game program started with 640 KB
I'm programmed under DOS. It's hard for young people to imagine the memory pattern: x86 in real mode, CPU is looking for a "part address x 16 + offset" address, one largest 64KB, with only 1MB in the whole address space, and this 1MB also has to scratch out the BIOS, the storage map and all the upper memory blocks. Regular Memory for Programs only 640KB- That's where the famous "640K should be enough for anyone" came from.
The first thing to do is fight this 640KB. The material was too much to fit, so there were two options:
- XMS / EMS: Extended memory norms. Load
HIMEM.SYSandEMM386.EXE, you can replace the memory outside 1MB with a "page frame map". Read the cut-off, but at least use the remaining ten MBs in the machine; - DOS Extension (DOS Expresser): More thorough programmes. After the application is started, cut to 32-bit protection mode, which is directly flat to the entire physical memory of the site. It's almost the industry label -- Doom uses DOS/4GW, and the little "DOS/4GW developed Mode Run-time" line in the live video is a common memory of a generation.
It's just as tight here. The opening ceremony for graphic programming is to cut Mode 13h:
// 切到 320x200、256 色的 VGA Mode 13h
void set_mode_13h() {
__asm {
mov ax, 0x13
int 0x10
}
}
// 然后直接往 0xA0000 写字节,一个字节就是一个像素
unsigned char far *vram = (unsigned char far *)0xA0000000L;
vram[y * 320 + x] = color_index; // 写的就是"调色板索引"
Mode 13h's beauty is simple: 64KB linear display, one byte pixels, and it goes up on screen immediately after writing. And it's the curse: There are 256 colors on one screen.. All colours come from a hardware palette (VGA DAC, each RGB, each 6 bit) of 256 items, and each byte you write is only an index to this table. Want to change the color? Write table entries to port 0x3C8/0x3C9; You want to do the fade-out? The whole watch evolved -- the full-screen "respiration" effect, but no pixel was painted, all playing with the palette.
Then Windows 95/98 became popular, and DirectDraw took over all of this, showing that the pattern also moved to the 16-bit colour of 640 x 480/ 800 x 600. The two skills of the Dos era - Palette Thinking and Obstinue to every byte– It's a new engine that's been put in place, and it's exactly the basis of the thinking of the two main players.
The atmosphere of self-study of the 2D engine in the country was also worth mentioning. The 2D engine, the spirit, was developed and opened during the university since 1999, and used by many companies and groups — the bottom of the Web-Live-West Swimming was built on the spirit, and it was invited into the Net Eym (2001) itself, and it was only then that the greatness of the Big Word 2 and the Dream West Swimming became known.Windy interviews.). Interestingly, the resource format of the Wind and Spirit is a perfect use of the two main players in this paper: "WAS Animation for Big Word 2 "The Dream West Travel" is "256 Colour palette + RLE Process Compression" with 256 palettes, each 16-bit 565 colours (see below). WAS File Format Analysisand Wastools Manual) — Same as the "8-bit Index + 16-bit Objective" programme to be discussed in section VI of this paper.
The resource packs of Daewoo's "Shin Swordsman's Legend (1995)" are the same: the objects chart (BALL.MKF) and the figure (RGM.MKF) are "The Palette Number + RLE Compression" and the battle animations are then compressed with one of their own YJ_1 (for details, see the format).Xianjian Data StationOpen Source Re-achievement SDLPAL in which you can read the full code decode. The same applies to overseas: the SHP elf format used in Westwood's Commands and Conquests series (from 1995), with only 8-bit colour palette index in the file, all colours being external .PAL In the file, the pixel flow is done by the scan line RLE. SHP Format Document for ModingWikiEven the "Segregation of Charts and Tables" approach is the same as the GRP in the post-Stellar Contest. So this combination is not the only solution to the team, it's the common answer that the 2D engine has grown in the face of the same hardware constraints. This is the engine that's going to be talking about, and that's what's coming out of that circle.
II. First count: Why must we compress?
In June 2000, the Sword Man's Loves, located in Mount Kinsan, came on the market — a 45-degree angle, an ARPG for instant combat. One of the most technical words in the official campaign is: "Real-time mapping engines can process more than 1,000 games at the same time, and players can experience a hundred-person battle without a 3-D acceleration card." The back of this ad is the entire hardware constraint that the 2D engine has to face:

- Memory: Mainstream 32-64MB, operating systems and game logic first ate;
- Visibility: 2-8MB is normal, AGP 4x is just popular, and the primary bandwidth is valuable;
- CPU: Ben Ten II / Saiyan 300 ~ 500 MHz, using x86 generic commands when no SIMD is available;
- Storage: CD-ROM 650MB appears to be large, but players have small hard disk space and downloads are more luxurious.
Look at the material on this side. In a game like "Swordman's Loves" the characters, enemies, and martial power are all 2D elves made in frame by frame: a 64x64 role frame, if 32-bit is true, 16KB; One character has eight directions x over a dozen actions x ten frames per action, a thousand frames easy, a dozen MBs -- A character.. It is not possible to have a single, single-screened collection of dozens of units, hundreds of monsters, plus maps, UIs, special effects.
So compression is necessary. The point is: **What dimensions does compression occur at? ** 2D data redundancy of elves happens to have two cross-cutting dimensions:
- Colour dimensions: A pixel with 24/32 bit is too luxurious. Pixie charts are hand-drawn-coloured styles, with a frame often actually using fewer than 256 colours;
- Space dimension: Pixie maps have a large number of pixels in a transparent background, and the solid parts often have a smog of the same color.
The standard answer to the two dimensions of that generation is: Colour dimension presses Quantification to 8-bit palette index, space dimension presses over and over again with RLE (Run-Length Encoding). A pipe "How big is every pixel" and a pipe "How many pixels are worth saving." We'll take it apart.
iii. Colour compression: Plug in to 256 colour palettes
3.1 Palettes are not restrictions, they are assets
Today's people can easily interpret "256 Colors" as a graphic compromise, but in the era of palettes, it's first of all one. Performance assets: 1 byte per pixel, memory, disk, bus bandwidth, all fractures; And the special effects of "fading off, day and night, poisoning to green" are from palettes.
So the question is never "Do you want the palette" but: **The art brings in 24/32-bit real colours. How do you choose the 256 colors that make the image the least lost? ** That's the color quantification problem.
3.2 Octree: Tilt the RGB cube to the point of eight.
Around 2000, the most common quantitative algorithm in the offline tool chain was Quantification of Octree (eight fork tree)(Gervautz & Purgathofer, 1988). The idea is as beautiful as magic: the RGB three channels take 1 bit each, encoded as a 3-bit serial number (0-7) and as a sub-node of a layer of the fork tree; Step down (from the top to the bottom) and go 5-8 floors, each leaf represents a small piece of colour in the RGB cube.

Inserts only the pixels in the leaves and the sum of the RGBs. After plugging in the whole pixel, if the leaves exceed 256 slices, then... Repeatedly merge the smallest-weight leaves back to the father's node(Paternity inherits its pixels and colours, and turns into new leaves) until there are only 256 pieces left. Each leaf's "spectrums and pixels" is one of the palettes, and the leaf's number is the index. Symptom code:
struct OctreeNode {
uint64_t pixelCount = 0; // 落入该色域的像素数
uint64_t sumR = 0, sumG = 0, sumB = 0; // 分量累加和(取均值用)
int paletteIndex = -1; // 量化完成后分配的调色板索引
OctreeNode* child[8] = {}; // 8 个子节点
};
void Insert(OctreeNode* node, RGB c, int layer) {
if (layer == MAX_LAYER) { // 到达叶子:统计即可
node->pixelCount++;
node->sumR += c.r; node->sumG += c.g; node->sumB += c.b;
return;
}
int bit = 7 - layer; // 本层取第几个 bit
int slot = ((c.r >> bit) & 1) << 2
| ((c.g >> bit) & 1) << 1
| ((c.b >> bit) & 1);
if (!node->child[slot]) node->child[slot] = new OctreeNode;
Insert(node->child[slot], c, layer + 1);
}
// 量化:不断合并"最不重要"的叶子,直到只剩 K 片
void Reduce(Octree* tree, int K) {
while (tree->leafCount > K) {
OctreeNode* victim = LeastSignificantLeaf(tree); // 像素少、层级浅者优先
OctreeNode* parent = victim->parent;
parent->pixelCount += victim->pixelCount; // 统计量上卷
parent->sumR += victim->sumR; /* G、B 同理 */
delete victim; // 父节点变成叶子
}
}
"Weight = Pixels + Level Punishment" is the essence of the classic Octree: Colors that appear less often, and leaves that are located on the shallows (i.e. very different from other colours, but unsuspecting) are sacrificed first.. Intuitively, it's "no one's color is given to someone."
The selection of Octree instead of the Median Cut, k-means and so on was a very reasonable engineering decision of the time: the insertion was O(N), each pixel had only a few bits to calculate, the memory was only a valid path, and hundreds of lines C++ could be completed -- the difference between minutes and hours was the speed and the slowness of packing thousands of elves.
3.3 This is decompression. Where is the loss?
It must be clear that:- Octree's quantification is damaging.. The 24-bit colour space has 1.67 million colours, pressing to 256 palettes, which are essentially multiple-to-one maps, and the original RGB will never be found. And it lost something and RLE exactly two dimensions:
| Means | Throw what? | Nature |
|---|---|---|
| Octree / Median Cut / Wu | Colour Precision | It's damaged. Color space is down. |
| JPEG | Space HF detail | Damaged, frequency quantification |
| RLE / LZW | Nothing. | No damage, space redundancy. |
| Dithering | Almost. | Noise for precision |
It is because of the positive trade that two layers can be linked: first quantifying into index maps, then making RLEs of index charts, without interference.
Quantified losses will appear in two types of images. The first one is... Large-colour gradient— Sky, water, fog: 256 colours spread over smooth gradients, with visible faults (banding) between adjacent colour steps. The antidote is... Shake The classic is the Floyd-Steinberg error spread: when a pixel is quantified, the error spreads to the right, bottom left, bottom right and bottom four untreated neighbours, and the chromosomal fault becomes a finely pelvis sense.

But take note of a counterintuitive conclusion: Dithering is negative for elves.. The elf map is shaped by hard-side pieces, and the edges of the twitch are broken. So in the current of work that year, the shaking should have been applied only in a gradual context, and the elves remained on the hard side — the principle of “segregation by layer” — and today pixels play is still in place.
Another type of victimization is the image of the extreme colour distribution (e.g., several high-light spots in a pure black background), which Occtree can easily merge, and the equations of the Median Cut or Wu are more stable. This is the boundary that you should know when you're choosing.
3.4 A palette with six faces.
The color palette also has a DOS-era proven dividend: Change the watch and not the chart.. The engine made this bonus extremely -- a one-time pregeneration of six palette variants when each elf was loaded:
| Variable | Purpose | Typical scene |
|---|---|---|
| Original Colour | Draw Normal | Default |
| Highlight | Full highlight. | He was treated, he picked the flash. |
| Greyscale | Color. | Freeze, petrochemical, death. |
| Red dye. | Red | Fireballs hit, violence. |
| Green. | Green. | Poison |
| Blue dye. | Blue | It's freezing. It's power-related. |
The active role is frozen without changing a pixel, and then the palette pointer is drawn inverted to the "grey" hologram. The marginal cost of dye effects is a pointer.. This is a very cost-effective time-for-space: 6 sets x 256 items x 2 bytes, each of which is no more than 3KB, in an age of several hundred elves in a frame.
There's also an easy-to-penetrate engineering pit: A palette must be shared by all frames of animated. If each frame is quantified, "color" becomes index 23 at the 1st frame, and two colors close to the point when they are played, but once the difference between the two indices in the table of variations is magnified, the part is "blinking" on the body. So the pack has to be packed. All frames fed to the same Octree for joint quantification., ensures that the same original colour is mapd to the same index in each frame. This constraint is not going to end up in the running period, but it's the tool chain's self-consciousness — it's the typical "agreements are greater than verification" in that generation of engines.
IV. RLE: A compression of "side-to-side" drawings
4.1 Why not LZW?
If you want to compress, why don't you use a more "real" LZW? Because... The decompressive form is wrong..
The LZW decompression requires the maintenance of a growing dictionary, with the output of "presolation to complete bitmap, then whole." And the core claim of the 2D Blitter engine is that Fluid Drawing: Hundreds of elves on the screen, each of which could be cut half by the edge of the screen and covered by the building, you would never want to "press the whole picture to the temporary bits and then cut the blit" -- that's the same as paying the memory bandwidth for nothing.
RLE The reverse: data are in the order of the scan, run stream, and the decoding device can only maintain the "current line to the canvas and the line to the x" point. Read the compression, write the pixels into the memory., encounters a cutting area and goes straight ahead. Decoding and drawing is the same trip, with a zero-intermediate buffer. No dictionary, very small state, one-way -- that's all about the 2D elf scene.
4.2 Encoding Transparent Pixels as Run
The largest space redundancy of elf maps is in a transparent context. The engine was very well handled: instead of giving the elves a separate mask channel, it was the genie. Transparency is a byte in the run head:
每个 run = [长度 count][alpha][可选的 count 个调色板索引]
alpha = 0 → 透明 run:没有数据字节,共 2 字节
alpha = 255 → 实色 run:头 + count 个索引字节
alpha = 1~254 → 半透明 run:整段共享一个透明度

Encoding end is a simple line-by-line scan:
// 把一行 8-bit 索引图编码成 run 流;transparent 由 ColorKey 或 alpha 通道判定
void EncodeLine(const uint8_t* pixels, int width, ByteStream& out) {
int x = 0;
while (x < width) {
int transparent = CountRun(pixels + x, width - x, IsTransparent);
int opaque = CountRun(pixels + x, width - x, IsOpaque);
if (transparent > 0) {
out.Write(min(transparent, 255)); // 长度(单字节,上限 255)
out.Write(0); // alpha = 0:透明
x += transparent;
} else {
out.Write(min(opaque, 255));
out.Write(255); // alpha = 255:实色
for (int i = 0; i < min(opaque, 255); i++)
out.Write(pixels[x++]); // 照搬 count 个调色板索引
}
}
}
Two details are worth mentioning. One of them, Single run limit 255(One byte) The extra long break into multiple run-outs -- nothing to do with dozens of pixels wide elves, which is a trade-off between "simplistic decoders with a single byte." Second, we'll find non-transparent pixels in the frame before encoded. Minimal Envelope Box, only this section is coded, and the deviation of the original relative map is recorded on the frame - an irregular elf does not have to take the rectangular canvas and save another one.
In experience, this format gets two-to-one to six-to-one compression ratios for elf maps, and the more transparent pixels they get.
4.3 Decoding means drawing
Real kung fu at the decoded end. It's not a depressive function, it's a... A graph that rubs the flow, shears, checks, and mixs the four things together.:
// 流式绘制:src 指向 RLE 流,dst 指向 16-bit 显存当前行位置
void DrawRLE(const uint8_t* src, uint16_t* dst, int visibleWidth,
const uint16_t* palette16, int clipLeft, int clipRight) {
int x = 0;
while (x < visibleWidth) {
int count = *src++;
int alpha = *src++;
if (alpha == 0) {
dst += count; // 透明:只推画布指针,零读写
} else {
// 裁剪:本 run 与 [clipLeft, clipRight] 求交,只画交集
for (int i = 0; i < count; i++, src++) {
int px = x + i;
if (px >= clipLeft && px < clipRight) {
if (alpha == 255)
*dst = palette16[*src]; // 查表,直写
else
*dst = Blend(*dst, palette16[*src], alpha); // 定点混合
}
dst++;
}
}
x += count;
}
}
Note the lethality of the transparent run branch: Two of them jumped over a pixel.— Do not read data, do not check tables and do not write on the display. The 2D game is full of elves, and actually visible pixels are much less than total pixels, and the "jumping costs close to zero" feature is the frame rate itself. This type of grapher is usually written as a whole in x86 (later MMX), and four shearing limits (left/right) are extended into four specific paths, with the register assigned to a single digit cycle. Alpha Mixing is also a fixed number:dst = (src * a + dst * (32 - a)) / 32Two. mul Done, don't touch the floating point.
V. Sampling: Star Trek 1
This "8-bit palette + RLE elve" program is not a charade of an engine, but an industry consensus of the era. The most powerful evidence comes from the snow — Star Contest 1 (1998) is a 640x480, 8-bit palette rendering game, whose elf-format GRP (followed by Monster Contest II, which can even be traced back to the original Monster Contest) is almost all the living fossils discussed above us, and community reverse data (e.g., IronGRP ) made it clear:
- GRP Only Palette Index: One byte per pixel, real RGB outside
.palThe colour palette file (256 items x 3 bytes) is separated from the table and is identical to what we call "index + palette"; - Palette Index 0 is transparency: ColorKey programme, no need for independence;
- RLE Compressed Direct Encoding in Pixels: Control byte distinguishes three commands - "Subject x pixels transparent"; "Subject x pixels homogeneity (one-time index)"; and "Preliminary copy next x pixels". Most units and architecture elves are in RLE compressed storage;
- Color palettes to the extreme: Player colour not by redrawing material, but by using
tselect.pcxThis one. Remix— Pixels in specific index areas on the elves, map to another set of indexes by player number, and a gunman model becomes eight colors for eight players; Fires, explosions, and so on, they're translucent.ofire.pcxSomething like that. A 2-D search table Achieved: Elf Index x Background Index ⁇ New Index, Pure Check Table for pseudo Alpha Mixed.

Put this set on the 1998 Run-II, and each decision points directly to the hardware throat: the 8-bit index halves the memory of the unit of the elves; RLE makes the transparency contours almost free of charge; The color palette remagnating allows for "8 Players x hundreds of units" to change the color zero cost; The matrix is semi-transparent so that the explosive effects are not multiplied. **It's not the snow that chose these technologies, it's the hardware that chose them. **
VI. A misunderstanding: Same screen 256 color?
The most common question to hear about the colour palette index is: "At least 256 colours, dozens of images on the same screen, is it not more than 256 colours? "
This question is confused. Storage Format and Show Format. The PC 2D engine around 2000 shows that the end was cut to 16-bit high colours (RBB 565 / RGB 555, same-screen ceiling 65,536/32,768 colours). The 8-bit index exists only on disks and memory, and the drawings are lost in the instant:
RLE 流里读出一个字节(调色板索引)
│
▼
在 16-bit 调色板里查表:color16 = palette16[index]
│
▼
写进 16-bit DirectDraw Surface(RGB565/555)
Each pixel is a solid 2-byte color in the visible, and it has nothing to do with "share 256 colours on the full screen" -- that's the shackles of the DOS Mode 13h era, and the Direct Draw era has been broken.

Then why do you insist on using the 8-bit index as an intermediate format? Three reasons, all money:
- Halve memory and bandwidth: 1 byte vs 2 byte per pixel, with a direct doubling of the material cache to halve the volume of visible copies;
- RLE Skipping Cheaper: Skip an 8-bit run byte long, transparent run by 2 byte;
- Small pane of variants:6 sets x 256 Divisions x 2 bytes = 3KB/ Elf, dye special effects are available.
This is the three-tiered structure of "Indicator for Disk/Memorial, Visible Color, Middle Checklist Connection", followed by the Standard Draw 2D engine model for the Universal Age of Win98. All the colour losses quantified by Octree occurred during the offline package period. The run-time is a check-up. No more loss of precision..
VII. THE STUDENT: ARE THE TECHNOLOGIES DEAD?
After the GPU era, the software Blitter, the palette, the handwritten compilation plotters were all placed in the museum - today's texture compression was converted to BC/ETC/ATC (the same idea of "detriment, block-scale, random access optimization"), with a transparent mix handed over to the hardware Blend Unit, and no one was able to compile a pixelal drawing cycle.
But a few things didn't actually die. RLE's "run flow + current consumption" idea lives in a variety of column-style storage and thin data structures; Colour Quantification Lives in every PNG Optimization Tool (pngquant Cut + Floyd-Steinberg's combined boxing to date); Space-for-time of "projected variants, run-off schedules", in line with today's LUT monetization, Shader scale; And the difference between "the type of content" -- the elves' hard side is not shaking, the background is twitching -- is the common sense that any compression line is indissociable.
Back then, it wasn't a particular algorithm, it was a particular algorithm. In the stitches of the 64KB segment, 2MB display, 300MHz CPU, each byte and every visit is arranged in a clear and clear manner The engineering conscious. I don't think I'm the only one who's got a problem with this.