The Screen Memory Layout
On a bitmap Z80 system (like the ZX Spectrum), the screen is a large array of memory where each byte controls a group of 8 horizontal pixels. To plot a single pixel at coordinate (X, Y), you need two things:
- Memory Address: The 16-bit address of the byte that contains the pixel.
- Bit Mask: A byte with a single bit set (
10000000B
,01000000B
, etc.) to isolate the target pixel within that byte.
Step 1: Calculating the Byte Address
The calculation for the byte address is highly complex and specific to each system’s memory layout. It typically involves combining the Y-coordinate (row) and the X-coordinate (column).
Generic Address Calculation:
; Assume X (0-255) is in L, Y (0-191) is in H.
; This code block is usually a complex series of shifts and additions.
; At the end of the calculation, HL holds the address of the byte
; that contains the pixel (X, Y).
Step 2: Calculating the Bit Mask
Once you have the memory address, you need to isolate the exact pixel within that byte. Since the byte controls 8 horizontal pixels, the X-coordinate determines the bit position (0-7).
The Principle: The bit mask is typically 10000000B
rotated right by the remainder of X / 8
.
LD A, L ; Use the L register (which holds the X-coordinate)
AND 07H ; A ← X modulo 8 (Gives the bit position 0-7)
LD B, A ; B = number of shifts required
LD A, 10000000B ; Start with the highest bit
SLA A ; Use rotation instruction (RLC, RRC) or shift (SLA, SRA)
DJNZ ADDRESS_LOOP ; Loop B times to position the bit mask correctly.
; A now holds the final, perfect 8-bit mask for the pixel.
Step 3: Plotting the Pixel (The Bitwise Magic)
To turn a pixel ON, you use the OR
logic instruction. To turn it OFF, you use the AND
logic instruction with an inverted mask.
Goal | Instruction Sequence | Notes |
---|---|---|
Plot ON | OR A, (HL) |
Sets the target bit to 1 without affecting the other 7 bits. |
Plot OFF | LD B, A; CPL; AND B, (HL) |
Inverts the mask (CPL ), then uses AND to force the target bit to 0. |
The Final Step: After applying the logic operation, you must write the modified byte back to memory: LD (HL), A
.