AppStars

Real-time 3D on a 16 MHz handheld with no 3D hardware

How we hand-wrote a textured 3D engine in ARM assembly for the Game Boy Advance: computed jumps, reciprocal tables, IWRAM placement, DMA and hardware-timer profiling.

In 2001 the Game Boy Advance arrived with no 3D hardware at all. Inside was a 16.78 MHz ARM7TDMI, 32 KB of fast on-chip memory, 256 KB of slower work RAM and a 240×160 screen. To win publisher deals, a studio had to show that full 3D games could run on it, at speeds comparable to the PlayStation.

We set out to show it. Between 2001 and 2003 we wrote a complete 3D engine for it, almost entirely in hand-written ARM assembly: about 14,500 lines across 27 assembly files, with the game code in C on top. Halfbrick Studios used it for technology demos it pitched to Activision, THQ and EA, including recreations of Starfox and Croc levels and our own monster-truck game, CloudKarts.

The constraint

At 16.78 MHz and 60 frames a second, you have about 280,000 cycles per frame for everything: game logic, transforming every vertex, sorting polygons and filling every pixel. The ARM7 has no floating point and no divide instruction. A textbook texture mapper wants a divide per pixel.

Memory was just as tight. Code running from the cartridge sits on a 16-bit bus with wait states. The 32 KB of internal work RAM (IWRAM) is 32 bits wide and has none. Anything hot had to live in those 32 KB, alongside the stack.

Architecture

A classic software pipeline, each stage in assembly:

 game (C): actors, state machines, levels
   |  world.object[] meshes, 16.16 fixed-point vertices
   v
 ViewAlign    transform vertices by the view matrix
 IsView       back-face cull, z-clip, off-screen reject, depth -> polylist[]
 Radix_Sort32 sort visible polygons by depth
 ProcPolyList2  per polygon: texture-mapped, flat or sprite fill
   v
 Mode 4 back buffer (8-bit paletted)  ->  page flip on vblank
  • Fixed point everywhere. Vertices in 16.16, sine and cosine from lookup tables, no floats.
  • Painter's algorithm. No z-buffer (there wasn't memory for one); polygons were sorted far to near and drawn in order.

The engineering

Jumping into the middle of 120 instructions

The innermost loop draws one horizontal span of a triangle, and a normal loop costs a compare and a branch per pixel. So we wrote the span body out 120 times and jumped into the middle of it. The GBA screen is 240 pixels wide, and the fast path drew two pixels per step, so 120 copies covers the whole screen. For a span of n pixel pairs, the code skips the first 120 − n copies by adding a computed offset straight to the program counter:

    movs    r4, r4, lsr #0x1        @ pixels -> pairs, odd pixel -> carry
    rsb    r4, r4, #120            @ pairs to skip
    mov    r11, r4, lsl #4         @ x16
    add    r11, r11, r4, lsl #3    @ +x8 = 24 bytes per pair
    add    pc, pc, r11             @ jump into the block
    nop                             @ pc reads 8 bytes ahead
    .REPT    120
    and    r11, r2, #0xff00        @ v (row) from packed uv
    add    r11, r11, r2, lsr #24   @ + u (column)
    ldrb    r4, [r1, r11]           @ fetch the texel
    add    r2, r2, r3, lsl #0x1    @ step uv by two pixels
    orr    r4, r4, r4, lsl #8      @ texel into both bytes
    strh    r4, [r8], #2            @ one store, two pixels
    .ENDR

Each copy is six instructions, 24 bytes, so the skip is the pair count times 24, built from two shifts and an add. On ARM, reading pc gives the address two instructions ahead, which is why a nop sits after the jump: a skip of zero lands on the first copy. The odd pixel, if there is one, was shifted into the carry flag on the first line and drawn after the block with a single conditional branch.

Two more tricks are packed in. First, textures were limited to 256×256, so the u and v coordinates, each with 8 bits of fraction, fit in one register: one add steps both, and two instructions turn it into a texel offset. Second, Mode 4 video memory only takes 16-bit writes, so this fast path writes each texel to both bytes of a halfword. That halves the horizontal texture detail in exchange for half the work. The source keeps the more accurate one-texel-per-pixel version beside it, commented out, under the note "This version is less accurate but faster".

No divides: reciprocal tables

Setting up a triangle needs edge slopes, which means dividing by the triangle's height. We replaced every divide with a table lookup and a multiply. A small console program generated 32,742 entries of 1/i in 16.16 fixed point, which the assembler pulled straight in:

    ldr    r11, [lr, r11, lsl #2]  @ divtmp = PrjTable[height]
    mov    r11, r11, lsr #8
    rsb    r3, r12, r4, asl #16    @ (x3<<16) - right_x
    mov    r3, r3, asr #10
    mul    r3, r11, r3             @ * 1/height
    mov    r3, r3, asr #6          @ dx_right

The shifts keep the product inside 32 bits. The mapper's header also records the road not taken: a lookup table inside the inner loop was tried and dropped as not accurate enough for its setup cost.

Choosing where every byte lives

The fastest code is useless if it runs from the slow bus. We gave every file a naming rule, *.text.iwram.s for code that must run from IWRAM and *.all.rodata.c for tables that stay in cartridge ROM, and wrote the linker script to honour it. In C, two macros did the same job for data:

#define IN_IWRAM __attribute__ ((section (".iwram")))
#define IN_EWRAM __attribute__ ((section (".ewram")))

The big buffers (world, polygon lists, clipping) went to the larger, slower work RAM. The transform, cull, sort and fill routines went to IWRAM.

The polygon sort shows how far this went. It was a radix sort written in assembly, one pass per byte of depth with 256 counters. Instead of a loop to zero the counters, it pushed eight zeroed registers onto the stack 32 times, building all 256 counters in 32 instructions. The C caller carries a warning in capitals not to feed it too many polygons, because the counters live on that small stack.

DMA for everything that just moves data

The GBA's DMA channels copy memory without the CPU. We used them for anything that was pure movement: clearing memory at boot, palettes, title screens and a queue of sprite updates. Animated models in the archived code worked the same way: each frame of a walk or a jump was a pre-baked set of vertices in ROM, DMA-copied into place. (A later version of the engine, which isn't in our archive, added skeletal animation.)

Measure, don't guess

Every claim about speed was measured. We wrote a small timing library on the GBA's hardware timers, wrapped each pipeline stage with it and recorded each round of optimisation in the comments, in timer ticks:

StageFirst versionOptimisation rounds
Cull and project (per object)1,7701,490
Radix sort9,1583,360 → 3,212 → 2,808 → 2,470
Polygon processing and fill24,40014,090 → 9,280 → 9,060 → 8,880 → 8,510 → 8,422

That's about 3.7 times faster on the sort and 2.9 times on the fill, earned one change at a time. The archive also holds test builds named after the technique being tried (IWRAM against work RAM, lookup tables against divides, different texture mappers) and around 30 numbered snapshot archives of CloudKarts. The discipline: try one thing, measure it, keep the numbers.

Where AI fits

CloudKarts ran three computer-driven trucks, each a state machine; we cover them in Game AI before "AI".

The bigger link is to what we build now. Running a model on a phone, a pair of glasses or a field device is the same problem in a new form: a fixed budget of cycles, memory and power. Quantised integer weights are fixed point by another name. Choosing which layers stay in fast memory is the IWRAM decision. Profiling each stage before touching it is exactly what those comments record.

What it taught us

Hand-tuning assembly teaches honesty about trade-offs. The fast mapper says it's less accurate; the sort warns you how to break it; rejected ideas are written down with the reason. Recording the trade-off where the next engineer will see it is a habit we bring to every codebase.

Why it still matters

Most software never has to care about cycles. Some does: apps that must feel instant on a five-year-old phone, IoT devices on a battery, and AI models that have to run on the device because the data can't leave it. That's where low-level engineering pays for itself. If you have a product like that, see our wearables and edge AI work, or the Game Boy Advance case study for the demos themselves.

Bring us the hard problem.

A 45-minute discovery call with the engineer who'll build it.