INightmare's Blog

(x86 Assembly) Graphics Part II - Palette

(This tutorial was originally written in 2004 and featured in http://asm.inightmare.org/)

This is my second tutorial on Graphics programming and now we’re going to see how palette is programmed.

When operating in video mode 13h or even 12h it’s sometimes necessary to adjust palette colors. For example to adjust to match colors of image being displayed or different scenery of a computer game, this way it is possible to show more colors than the mode actually supports.

There are two ways to do this: 1) by using direct access to video ports; 2) using BIOS interrupts (preferred)

Now lets looks how palette color management using Video BIOS looks like:

mov ax,1010h ; Video BIOS function to change palette color
mov bx,0 ; color number 0 (usually background, black)
mov dh,60 ; red color value (0-63, not 0-255!)
mov ch, 0 ; green color component (0-63)
mov cl,30 ; blue color component (0-63)
int 10h ; Video BIOS interrupt

Easy like that. OK now lets read the palette.

mov ax,1015h
mov bx,0 ; color number
int 10h

Return values are: dh = red color component; ch = green color component; cl = blue color component.

Now lets try this using direct access to video card ports, I don’t recommend doing this unless really needed (for pmode OSes).

Ports: 3C8h is used to set color (output color index), 3C7h is used for reading palette values (output color index), and 3C9h is used to output color component data in RGB.

mov al,0 ; set to 0 for color 0
mov dx,3C8h ; port...
out dx,al ; now we output al (0) to color write port
mov bl,63 ; red color component
mov cl.0 ; green
mov ch,32 ; blue
mov dx,3C9h ; data port
out dx,cl ; red
out dx,cl ; green
out dx,ch ; blue

Now reading works like this:

mov dx,3C7h ; palette data read port
mov ax,0 ; color index 0
out dx,ax ; outputing the data
mov dx,3C9h ; we set dx to data port
in bl,dx ; red color to bl
in cl,dx ; green color to cl
in ch,dx ; blue color to ch

That’s it. I hope I helped. And always use interrupts if possible, because data port way sometimes has errors and red color component is not always set. Good luck!