| 1 |
// Copyright (c) 1993-2011 PrBoom developers (see AUTHORS) |
| 2 |
// Licence: GPLv2 or later (see COPYING) |
| 3 |
|
| 4 |
// Chained hash lookup to convert rgb triples to palette indices |
| 5 |
|
| 6 |
#include "rd_palette.h" |
| 7 |
|
| 8 |
#include <string.h> |
| 9 |
|
| 10 |
#include "rd_util.h" |
| 11 |
|
| 12 |
static unsigned char *palette_data; |
| 13 |
|
| 14 |
#define PAL_SIZE 256 |
| 15 |
|
| 16 |
static struct { |
| 17 |
unsigned char rgb[3]; |
| 18 |
int first, next; |
| 19 |
} hash[PAL_SIZE]; |
| 20 |
|
| 21 |
#define HASH(c) ((int)((c)[0])+(int)((c)[1])+(int)((c)[2])) |
| 22 |
|
| 23 |
// |
| 24 |
// make_hash |
| 25 |
// |
| 26 |
// killough-style chained hash |
| 27 |
// |
| 28 |
|
| 29 |
static void make_hash(void) |
| 30 |
{ |
| 31 |
int i; |
| 32 |
unsigned char *rgb; |
| 33 |
|
| 34 |
for (i = PAL_SIZE, rgb = &palette_data[3*i]; rgb -= 3, --i >= 0; ) |
| 35 |
{ |
| 36 |
memmove(hash[i].rgb, rgb, 3); |
| 37 |
hash[i].next = hash[i].first = PAL_SIZE; |
| 38 |
} |
| 39 |
|
| 40 |
for (i = PAL_SIZE, rgb = &palette_data[3*i]; rgb -= 3, --i >= 0; ) |
| 41 |
{ |
| 42 |
int h = HASH(rgb) % PAL_SIZE; |
| 43 |
hash[i].next = hash[h].first; |
| 44 |
hash[h].first = i; |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
// |
| 49 |
// loadpal |
| 50 |
// |
| 51 |
|
| 52 |
static void loadpal(const char *filename) |
| 53 |
{ |
| 54 |
void *data = NULL; |
| 55 |
size_t size = read_or_die(&data, filename); |
| 56 |
|
| 57 |
if (size != 3*PAL_SIZE) |
| 58 |
die("Bad palette: %s\n", filename); |
| 59 |
|
| 60 |
palette_data = data; |
| 61 |
} |
| 62 |
|
| 63 |
// |
| 64 |
// palette_init |
| 65 |
// |
| 66 |
|
| 67 |
void palette_init(const char *filename) |
| 68 |
{ |
| 69 |
loadpal(filename); |
| 70 |
make_hash(); |
| 71 |
} |
| 72 |
|
| 73 |
// |
| 74 |
// palette_getindex |
| 75 |
// |
| 76 |
|
| 77 |
int palette_getindex(const unsigned char *rgb) |
| 78 |
{ |
| 79 |
int i; |
| 80 |
|
| 81 |
if (!palette_data) |
| 82 |
die("No palette loaded - please specify one with -palette\n"); |
| 83 |
|
| 84 |
i = hash[HASH(rgb) % PAL_SIZE].first; |
| 85 |
|
| 86 |
while (i < PAL_SIZE && memcmp(hash[i].rgb, rgb, 3) != 0) |
| 87 |
i = hash[i].next; |
| 88 |
|
| 89 |
return i < PAL_SIZE ? i : -1; |
| 90 |
} |