lcd: prevent from using a scale level that isn't actually supported
[rofl0r-gnuboy.git] / palette.c
blob0ef8da8daed06e4c13efe79bb8ef0622f6c14088
1 #include <stdlib.h>
3 #include "defs.h"
4 #include "fb.h"
5 #include "sys.h"
7 static byte palmap[32768];
8 static byte pallock[256];
9 static int palrev[256];
11 /* Course color mapping, for when palette is exhausted. */
12 static byte crsmap[4][32768];
13 static int crsrev[4][256];
14 static const int crsmask[4] = { 0x7BDE, 0x739C, 0x6318, 0x4210 };
16 enum plstatus
18 pl_unused = 0,
19 pl_linger,
20 pl_active,
21 pl_locked
25 static byte bestmatch(int c)
27 byte n, best;
28 int r, g, b;
29 int r2, g2, b2, c2;
30 int err, besterr;
32 r = (c & 0x001F) << 3;
33 g = (c & 0x03E0) >> 2;
34 b = (c & 0x7C00) >> 7;
36 best = 0;
37 besterr = 1024;
38 for (n = 1; n; n++)
40 c2 = palrev[n];
41 r2 = (c2 & 0x001F) << 3;
42 g2 = (c2 & 0x03E0) >> 2;
43 b2 = (c2 & 0x7C00) >> 7;
44 err = abs(r-r2) + abs(b-b2) + abs(g-g2);
45 if (err < besterr)
47 besterr = err;
48 best = n;
51 return best;
54 static void makecourse(int c, byte n)
56 int i;
57 for (i = 0; i < 4; i++)
59 c &= crsmask[i];
60 crsmap[i][c] = n;
61 crsrev[i][n] = c;
65 static byte findcourse(int c)
67 int i;
68 byte n;
69 for (i = 0; i < 4; i++)
71 c &= crsmask[i];
72 n = crsmap[i][c];
73 if (crsrev[i][n] == c)
74 return n;
76 return 0;
80 void pal_lock(byte n)
82 if (!n) return;
83 if (pallock[n] >= pl_locked)
84 pallock[n]++;
85 else pallock[n] = pl_locked;
88 byte pal_getcolor(int c, int r, int g, int b)
90 byte n;
91 static byte l;
92 n = palmap[c];
93 if (n && pallock[n] && palrev[n] == c)
95 pal_lock(n);
96 return n;
98 for (n = l+1; n != l; n++)
100 if (!n || pallock[n] /* || n < 16 */) continue;
101 pal_lock(n);
102 palmap[c] = n;
103 palrev[n] = c;
104 makecourse(c, n);
105 vid_setpal(n, r, g, b);
106 return (l = n);
108 n = findcourse(c);
109 pal_lock(n);
110 return n;
113 void pal_release(byte n)
115 if (pallock[n] >= pl_locked)
116 pallock[n]--;
120 void pal_expire()
122 int i;
123 for (i = 0; i < 256; i++)
124 if (pallock[i] && pallock[i] < pl_locked)
125 pallock[i]--;
129 void pal_set332()
131 int i, r, g, b;
133 fb.indexed = 0;
134 fb.cc[0].r = 5;
135 fb.cc[1].r = 5;
136 fb.cc[2].r = 6;
137 fb.cc[0].l = 0;
138 fb.cc[1].l = 3;
139 fb.cc[2].l = 6;
141 i = 0;
142 for (b = 0; b < 4; b++) for (g = 0; g < 8; g++) for (r = 0; r < 8; r++)
143 vid_setpal(i++, (r<<5)|(r<<2)|(r>>1),
144 (g<<5)|(g<<2)|(g>>1), (b<<6)|(b<<4)|(b<<2)|b);