Software Sprites in GRAPHICS 7: Pre-Shifted, Masked and Double-Buffered

GRAPHICS 7 screen with blue diagonal stripes and two columns of white blocks, eight round yellow-green balls scattered over them, and a blue text window reading SPRITES: 00008 and 256 UPDATES IN 00256 FRAMES

The Atari's four players and four missiles are wonderful, but there are only eight of them, each is a single colour, and they are a vertical strip, not a shape you can put anywhere. When a game needs more objects, or objects that are part of the picture, it draws them into screen memory itself. These are software sprites (also called bitmap or "soft" sprites), and the technique is the same one used on machines that have no sprite hardware at all.

This guide builds a complete software-sprite engine for GRAPHICS 7 (ANTIC mode D) in assembly language. It moves eight multicoloured balls over a patterned background, cleanly and at a full 60 updates a second.

What you'll learn: how pixels are packed in the four-colour bitmap modes, why sprites are stored pre-shifted, how an AND mask and OR image draw a shape without a box around it, how to erase it again with a save-under buffer, why a single screen flickers, and how double buffering cures that. The program also measures its own speed.

What you need: MADS and an emulator, and some 6502 experience (see Getting Started with 6502 Assembly). For the BASIC side of the graphics modes, see Graphics in Atari BASIC. The example was assembled with MADS and run in atari800 (NTSC, XL/XE mode with its built-in AltirraOS). Character-mode "soft sprites" are a different technique, covered in Character Set Animation.

1. Four pixels to a byte

GRAPHICS 7 is 160 × 96 pixels in four colours. With a text window, as in the example, it is 160 × 80. Each pixel takes 2 bits, so a byte holds four pixels and a row is 40 bytes. The leftmost pixel is in the top two bits:

Pixel value Bits Colour register (shadow)
0 00 background, COLBK (COLOR4, 712)
1 01 COLPF0 (COLOR0, 708)
2 10 COLPF1 (COLOR1, 709)
3 11 COLPF2 (COLOR2, 710)

The example's ball is 8 pixels wide and 8 rows high, so each row is two bytes. Written out as pixel values, the rows are ..1111.., .122111., 12211111 and so on, colour 1 for the ball and colour 2 for a highlight.

2. Why pre-shift?

A sprite whose left edge falls on a byte boundary (x = 0, 4, 8 …) can be copied two bytes at a time. Any other x position puts the shape partway into a byte, so every row has to be shifted right by 2, 4 or 6 bits, spilling into a third byte. Doing that shifting for every row, every frame, is slow.

The usual answer is to shift it once, at start-up. The program keeps four copies of the shape, shifted by 0, 1, 2 and 3 pixels, each three bytes wide. To draw at x, it uses byte column x / 4 and copy number x AND 3. That costs 4 × 24 = 96 bytes instead of 16. In GRAPHICS 8 (two colours, eight pixels per byte) you would need eight copies, which is why games often choose mode D or E for software sprites.

The preshift routine builds the copies by shifting each source row through three bytes with LSR/ROR, two bits per pixel of offset.

3. Masks: drawing without a box

If you simply store the sprite's bytes on the screen, the transparent corners (pixel value 0) wipe out the background around the ball. The fix is a mask: a second copy of each byte with 00 wherever the sprite has a pixel and 11 wherever it is transparent. Each screen byte is then updated in three steps:

  1. Read the screen byte.
  2. AND it with the mask, which clears just the pixels the sprite covers.
  3. OR in the sprite byte, which fills them in.

The neighbouring pixels in the same byte survive. The mkmask routine makes the masks from the shifted images automatically, testing each two-bit pair. A consequence is that colour 0 means "transparent" in this engine. A sprite can't contain solid background-coloured pixels unless you draw the mask by hand.

4. Erasing: the save-under buffer

To move a sprite, you must remove it from its old position and put back whatever was there. Redrawing the background would be slow and complicated, so the draw routine saves each screen byte it is about to change, 24 bytes per sprite, and the restore routine copies them back.

Order matters when sprites overlap. If ball A is drawn and then ball B on top of it, B's saved bytes include part of A. Restoring A first and then B would put that piece of A back on the screen. So the program restores in the reverse order of drawing (last drawn, first restored), which always unwinds the screen correctly. The main loop is:

  1. Restore all sprites, last to first.
  2. Move them.
  3. Save and draw all sprites, first to last.

5. The problem with one screen

Our first version did exactly that on the single screen the OS had opened, starting each update just after the vertical blank. It looked bad. Restoring and redrawing eight balls takes most of a frame, so the TV beam keeps catching sprites in the gap between being erased and being redrawn. In captured frames from that version, only two to four of the eight balls were visible, and one was half drawn. On screen they flickered.

A colour test shows why. Setting the background colour register COLBK ($D01A) to red at the start of the work and back to black at the end (the SHOWTIME option in the listing) turned almost the whole screen red with eight sprites: the drawing ran across nearly every visible scan line.

6. Double buffering

The cure is to draw where the viewer can't see. The program keeps two screens: A, the one the OS opened, and B, a copy at $6000. While A is on display, all the restoring and drawing happens on B. At the next vertical blank, the program changes the display list's LMS address (bytes 4 and 5 of the OS's GRAPHICS 7 display list) to point at B, and starts working on A. The viewer only ever sees finished frames. (Page Flipping covers the LMS trick itself.)

Each screen needs its own save buffers and its own record of where each sprite was drawn, because the sprites on screen A are where they were two updates ago. The listing keeps two sets of everything, selected by the variable hidden. The row-address table has 160 entries, the first 80 for screen A and the next 80 for screen B, so the drawing code just adds 80 to the row number when it works on B.

Two rules for the second screen: put it where nothing else lives, and keep its 3,200 bytes inside one 4K block, because ANTIC's memory counter can't cross a 4K boundary without a new LMS instruction. $6000–$6C7F is safe here.

7. Making the inner loop cheap

Each byte of the sprite needs a screen pointer, a shape byte, a mask byte and a save slot. The listing keeps all four in zero-page pointers and uses one index register for all of them: Y runs from 0 to 23 through the shape, mask and save areas. For each row, rowptr sets the screen pointer to the row address plus the byte column minus the current Y, so that (PTR),Y lands on the right screen byte too. The three bytes of a row are unrolled with MADS's .rept:

        lda (PTR),y         ; old screen byte
        sta (SAV),y         ; keep it for the restore
        and (MSK),y         ; clear where the sprite is solid
        ora (SHP),y         ; put in the sprite's pixels
        sta (PTR),y
        iny

An earlier version advanced each pointer by 3 with a subroutine call after every row. Removing those calls was the difference between 8 sprites at 30 updates a second and 8 sprites at 60.

8. The program

After 256 updates, the program prints how many frames they took in the text window and carries on animating. At 60 updates per second, 256 updates take 256 frames.

; Software sprites in GRAPHICS 7: pre-shifted, masked shapes drawn
; over a background with save-under erase, double buffered. MADS.
RTCLOK  = $12
SAVMSC  = $58
SDLSTL  = $0230             ; display list pointer (shadow)
COLOR0  = $02C4             ; shadows of COLPF0..COLPF2 and COLBK
COLOR1  = $02C5
COLOR2  = $02C6
COLOR4  = $02C8
COLBK   = $D01A
ICCOM   = $0342
ICBAL   = $0344
ICBLL   = $0348
ICAX1   = $034A
ICAX2   = $034B
CIOV    = $E456
PTR     = $CB               ; screen pointer
SHP     = $CD               ; shape data pointer
MSK     = $CF               ; mask pointer
SAV     = $D1               ; save-buffer pointer
TMP     = $D3
NSPR    = 8                 ; number of sprites (up to 10)
ROWS    = 80                ; GRAPHICS 7 with a text window
MAXX    = 148               ; 8-pixel sprite, 3 bytes wide when shifted
MAXY    = ROWS-8
SCREENB = $6000             ; second screen, 3200 bytes, inside one 4K block
SHOWTIME = 0                ; 1 = colour the background while working

        org $3000
start   ldx #$60            ; GRAPHICS 7 with text window on IOCB 6
        lda #12
        sta ICCOM,x
        jsr CIOV
        ldx #$60
        lda #3
        sta ICCOM,x
        lda #<sname
        sta ICBAL,x
        lda #>sname
        sta ICBAL+1,x
        lda #28             ; 12 = read/write, +16 = text window
        sta ICAX1,x
        lda #7
        sta ICAX2,x
        jsr CIOV
        lda #$1A            ; colour 1: yellow
        sta COLOR0
        lda #$0E            ; colour 2: white
        sta COLOR1
        lda #$84            ; colour 3: blue
        sta COLOR2
        lda #$00
        sta COLOR4
        jsr rowtab
        jsr backgr          ; background on screen A, copied to B
        jsr preshift
        lda #1              ; we show A (0) and draw on B (1) first
        sta hidden
        jsr drawall         ; first frame on B: nothing to restore
        jsr flip
        jsr drawall         ; and on A
        jsr flip
        lda RTCLOK+2        ; start the clock
        sta j0
        lda RTCLOK+1
        sta j0+1

; ---- main loop: build the hidden screen, then show it ----
frame   .if SHOWTIME
        lda #$34
        sta COLBK
        .endif
        ldx #NSPR-1         ; 1. restore backgrounds, LAST sprite first
r0      stx cur
        jsr restore
        ldx cur
        dex
        bpl r0
        jsr move            ; 2. move everything
        jsr drawall         ; 3. save and draw, FIRST sprite first
        .if SHOWTIME
        lda #0
        sta COLBK
        .endif
        jsr flip            ; 4. show what we drew
        inc frames
        bne frame
        lda shown           ; after 256 frames, report once
        bne frame
        inc shown
        sec                 ; frames taken = jiffies since the start
        lda RTCLOK+2
        sbc j0
        sta njif
        lda RTCLOK+1
        sbc j0+1
        sta njif+1
        jsr say
        dta $9B,c'SPRITES: ',0
        lda #NSPR
        ldx #0
        jsr dec5
        jsr say
        dta $9B,c'256 UPDATES IN ',0
        lda njif
        ldx njif+1
        jsr dec5
        jsr say
        dta c' FRAMES',0
        jmp frame

; ---- wait for vertical blank, then show the hidden screen ----
flip    lda RTCLOK+2
fl1     cmp RTCLOK+2
        beq fl1
        lda SDLSTL          ; LMS address is at bytes 4-5 of the OS list
        sta TMP
        lda SDLSTL+1
        sta TMP+1
        ldy #4
        ldx hidden
        lda scrlo,x
        sta (TMP),y
        iny
        lda scrhi,x
        sta (TMP),y
        txa                 ; now draw on the other one
        eor #1
        sta hidden
        rts

; ---- save and draw every sprite ----
drawall ldx #0
d0      stx cur
        jsr draw
        ldx cur
        inx
        cpx #NSPR
        bne d0
        rts

; ---- SAV = save area of sprite 'cur' on the hidden screen ----
; ---- X = slot for its remembered position (hidden*16 + cur) ----
setsav  lda hidden          ; save area = savbuf + hidden*240 + cur*24
        tay
        clc
        lda cur
        tax
        lda mul24,x
        adc bufoff,y
        sta SAV
        lda #>savbuf
        adc #0
        sta SAV+1
        clc
        lda SAV
        adc #<savbuf
        sta SAV
        bcc ss1
        inc SAV+1
ss1     tya                 ; slot for remembered position
        asl
        asl
        asl
        asl
        ora cur
        tax                 ; X = hidden*16 + cur
        rts

; ---- restore the bytes under sprite 'cur' on the hidden screen ----
restore jsr setsav
        lda savy,x
        sta ry
        lda savcol,x
        sta rcol
        lda #8
        sta cnt
        lda #0
        sta k0
rs1     jsr rowptr          ; PTR = row start + column - k0
        ldy k0
        .rept 3
        lda (SAV),y
        sta (PTR),y
        iny
        .endr
        sty k0
        inc ry
        dec cnt
        bne rs1
        rts

; ---- PTR = address of row ry, column rcol, minus k0 ----
; (so that (PTR),Y with Y = k0..k0+2 reaches the three bytes, while
; the same Y also steps through the 24-byte shape, mask and save areas)
rowptr  ldy ry
        clc
        lda rowlo,y
        adc rcol
        tax
        lda rowhi,y
        adc #0
        sta PTR+1
        txa
        sec
        sbc k0
        sta PTR
        bcs rp1
        dec PTR+1
rp1     rts

; ---- save the background under sprite 'cur', then draw it ----
draw    ldy cur
        lda spry,y
        ldx hidden          ; screen B rows are entries 80-159
        beq dw0
        clc
        adc #ROWS
dw0     sta ry
        jsr setsav          ; SAV = save area, X = slot
        lda ry              ; remember where we drew, for restore
        sta savy,x
        ldy cur
        lda sprx,y          ; byte column = x / 4, shift = x AND 3
        lsr
        lsr
        sta rcol
        sta savcol,x
        lda sprx,y
        and #3
        tay
        clc                 ; shape and mask for this shift
        lda #<shdata
        adc mul24,y
        sta SHP
        lda #>shdata
        adc #0
        sta SHP+1
        clc
        lda #<shmask
        adc mul24,y
        sta MSK
        lda #>shmask
        adc #0
        sta MSK+1
        lda #8
        sta cnt
        lda #0
        sta k0
dr1     jsr rowptr
        ldy k0
        .rept 3
        lda (PTR),y         ; old screen byte
        sta (SAV),y         ; keep it for the restore
        and (MSK),y         ; clear where the sprite is solid
        ora (SHP),y         ; put in the sprite's pixels
        sta (PTR),y
        iny
        .endr
        sty k0
        inc ry
        dec cnt
        bne dr1
        rts

; ---- move all sprites, bouncing off the edges ----
move    ldx #NSPR-1
mv1     clc
        lda sprx,x
        adc sprdx,x
        sta sprx,x
        beq mvxf            ; hit 0: turn round
        cmp #MAXX
        bcc mvy
mvxf    lda sprdx,x
        eor #$FF
        clc
        adc #1
        sta sprdx,x
mvy     clc
        lda spry,x
        adc sprdy,x
        sta spry,x
        beq mvyf
        cmp #MAXY
        bcc mvn
mvyf    lda sprdy,x
        eor #$FF
        clc
        adc #1
        sta sprdy,x
mvn     dex
        bpl mv1
        rts

; ---- build 4 shifted copies of the shape, and their masks ----
preshift ldx #0             ; X = output index (shift*24 + row*3)
        lda #0
        sta sh
ps1     ldy #0              ; Y = source index (row*2)
ps2     lda shape,y
        sta t0
        lda shape+1,y
        sta t1
        lda #0
        sta t2
        lda sh              ; shift right 2 bits per pixel step
        asl
        beq ps4
        sta TMP
ps3     lsr t0
        ror t1
        ror t2
        dec TMP
        bne ps3
ps4     lda t0
        sta shdata,x
        jsr mkmask
        sta shmask,x
        lda t1
        sta shdata+1,x
        jsr mkmask
        sta shmask+1,x
        lda t2
        sta shdata+2,x
        jsr mkmask
        sta shmask+2,x
        inx
        inx
        inx
        iny
        iny
        cpy #16
        bne ps2
        inc sh
        lda sh
        cmp #4
        bne ps1
        rts
mkmask  sta TMP             ; A = pixel byte -> AND mask (0 where solid)
        txa
        pha
        lda #$FF
        sta TMP+1
        ldx #3
mk1     lda TMP
        and pairs,x
        beq mk2
        lda TMP+1
        eor pairs,x         ; solid pixel: clear its two bits
        sta TMP+1
mk2     dex
        bpl mk1
        pla
        tax
        lda TMP+1
        rts
pairs   dta $C0,$30,$0C,$03

; ---- row address tables: 0-79 screen A, 80-159 screen B ----
rowtab  lda SAVMSC
        sta scrlo
        sta PTR
        lda SAVMSC+1
        sta scrhi
        sta PTR+1
        ldy #0
        jsr rt0
        lda #<SCREENB
        sta PTR
        lda #>SCREENB
        sta PTR+1
rt0     ldx #ROWS
rt1     lda PTR
        sta rowlo,y
        lda PTR+1
        sta rowhi,y
        clc
        lda PTR
        adc #40
        sta PTR
        bcc rt2
        inc PTR+1
rt2     iny
        dex
        bne rt1
        rts

; ---- background: diagonal stripes in colour 3, white boxes ----
backgr  ldy #0
bg1     sty TMP             ; row number
        lda rowlo,y
        sta PTR
        lda rowhi,y
        sta PTR+1
        tya
        lsr
        lsr
        and #3
        tax
        lda stripe,x        ; pattern shifts every 4 rows
        ldy #39
bg2     sta (PTR),y
        dey
        bpl bg2
        lda TMP             ; a white box every 16 rows
        and #15
        cmp #8
        bcs bg3
        ldy #10
        lda #$AA
bg4     sta (PTR),y
        iny
        cpy #14
        bne bg4
        ldy #26
bg5     sta (PTR),y
        iny
        cpy #30
        bne bg5
bg3     ldy TMP
        iny
        cpy #ROWS
        bne bg1
        lda SAVMSC          ; copy screen A to screen B (3200 bytes)
        sta PTR
        lda SAVMSC+1
        sta PTR+1
        lda #<SCREENB
        sta SHP
        lda #>SCREENB
        sta SHP+1
        ldx #13             ; 13 pages covers 3200 bytes
        ldy #0
cp1     lda (PTR),y
        sta (SHP),y
        iny
        bne cp1
        inc PTR+1
        inc SHP+1
        dex
        bne cp1
        rts
stripe  dta $C0,$30,$0C,$03

; ---- text output through E: (IOCB 0) ----
say     pla
        sta PTR
        pla
        sta PTR+1
sy1     inc PTR
        bne sy2
        inc PTR+1
sy2     ldy #0
        lda (PTR),y
        beq sy3
        jsr putc
        jmp sy1
sy3     lda PTR+1
        pha
        lda PTR
        pha
        rts
putc    ldx #0
        stx ICBLL
        stx ICBLL+1
        pha
        lda #11
        sta ICCOM
        pla
        jmp CIOV
dec5    sta n16             ; A/X as 5 decimal digits
        stx n16+1
        ldx #0
d51     lda #'0'
        sta digit
d52     lda n16
        sec
        sbc p10lo,x
        tay
        lda n16+1
        sbc p10hi,x
        bcc d53
        sta n16+1
        sty n16
        inc digit
        bne d52
d53     stx savx
        lda digit
        jsr putc
        ldx savx
        inx
        cpx #5
        bne d51
        rts
p10lo   dta <10000,<1000,<100,<10,<1
p10hi   dta >10000,>1000,>100,>10,>1
n16     dta a(0)

sname   dta c'S:',$9B
shape   dta %00000101,%01010000     ; ..1111..
        dta %00011010,%01010100     ; .122111.
        dta %01101001,%01010101     ; 12211111
        dta %01100101,%01010101     ; 12111111
        dta %01010101,%01010101     ; 11111111
        dta %01010101,%01010101     ; 11111111
        dta %00010101,%01010100     ; .111111.
        dta %00000101,%01010000     ; ..1111..
mul24   dta 0,24,48,72,96,120,144,168,192,216
bufoff  dta 0,240
sprx    dta 4,30,60,90,120,140,20,100,70,10
spry    dta 4,40,12,60,30,8,66,50,30,50
sprdx   dta 1,1,$FF,1,$FF,$FF,1,$FF,1,$FF
sprdy   dta 1,$FF,1,$FF,1,1,$FF,1,$FF,$FF
scrlo   dta 0,<SCREENB
scrhi   dta 0,>SCREENB
hidden  dta 0
cur     dta 0
rcol    dta 0
ry      dta 0
cnt     dta 0
k0      dta 0
sh      dta 0
t0      dta 0
t1      dta 0
t2      dta 0
frames  dta 0
shown   dta 0
j0      dta a(0)
njif    dta a(0)
digit   dta 0
savx    dta 0
savcol  .ds 32
savy    .ds 32
shdata  .ds 96
shmask  .ds 96
savbuf  .ds 480
rowlo   .ds ROWS*2
rowhi   .ds ROWS*2
        run start

9. Results

Measured on NTSC in atari800, changing only NSPR:

Sprites 256 updates took Updates per second
4 256 frames 60
8 256 frames 60
10 512 frames 30

With ten balls the work no longer fits between two vertical blanks, so each update waits for the next one and the speed halves. It doesn't flicker, though: double buffering degrades gracefully to a lower frame rate. A game would normally pick a fixed rate (30 updates a second is common for software sprites) and budget the work to fit it. On PAL machines a frame is longer, so the same work fits more easily, but there are only 50 of them a second.

Where the time goes, per sprite: 24 read-mask-write steps for the draw, 24 copies for the restore, and eight row-address calculations for each. Ideas we have not measured here:

  • Skip the mask where it isn't needed. Bytes that are fully solid can be stored directly, and fully empty bytes can be skipped. A compiled sprite (code generated for one particular shape) does this automatically.
  • Restore only what changed. For a background of plain colour, an erase can simply clear bytes instead of copying them back.
  • Use a cheaper mode. GRAPHICS 7 with a text window uses 3,200 bytes per screen. ANTIC mode E (GRAPHICS 15 on XL/XE machines) doubles the vertical resolution and the cost of every sprite.
  • Mix hardware and software sprites. Many games put the player in a player/missile sprite and use software sprites for the many enemies.

Troubleshooting

  • Coloured boxes round the sprites: the mask is missing or inverted. A mask byte must be 00 where the sprite has pixels.
  • Sprites leave trails: the restore uses different coordinates from the draw. Save the byte column and row with each draw, as the listing does, and restore from those.
  • Fragments of other sprites left behind after overlaps: restore in reverse order of drawing.
  • The sprite jumps four pixels at a time: the shift copy isn't being chosen from x AND 3.
  • Flicker or half-drawn sprites: you are drawing on the visible screen. Double buffer, or at least finish all drawing during the vertical blank.
  • Garbage on part of screen B: it crosses a 4K boundary, or overlaps your program or another buffer.
  • Corrupted bytes at the right edge: a shifted sprite is three bytes wide. With an 8-pixel sprite, x must stay at 148 or less on a 160-pixel row.

Further reading

  • De Re Atari, chapter 2 (ANTIC and display lists: LMS and the 4K boundary).
  • Ian Chadwick, Mapping the Atari: SAVMSC (88–89), SDLSTL (560–561), COLBK (53274) and RTCLOK (18–20).
  • On this site: Page Flipping: Instant Screens and Full-Screen Animation, Fast Line Drawing in Assembly: Bresenham's Algorithm in GRAPHICS 7, Player/Missile Graphics in Assembly, Character Set Animation, ANTIC DMA and Cycle Timing.

Credits