Skip to content

Commit 901813a

Browse files
committed
Refactor gbcpal.c
1 parent e59624d commit 901813a

File tree

1 file changed

+10
-15
lines changed

1 file changed

+10
-15
lines changed

tools/gbcpal.c

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,19 @@ struct Color unpack_color(uint16_t gbc_color) {
4444
};
4545
}
4646

47+
bool same_color(struct Color color1, struct Color color2) {
48+
return color1.r == color2.r && color1.g == color2.g && color1.b == color2.b;
49+
}
50+
4751
double luminance(struct Color color) {
4852
return 0.299 * color.r + 0.587 * color.g + 0.114 * color.b;
4953
}
5054

51-
int compare_colors(const void *color1, const void *color2) {
55+
int compare_luminance(const void *color1, const void *color2) {
5256
double lum1 = luminance(*(const struct Color *)color1);
5357
double lum2 = luminance(*(const struct Color *)color2);
5458
// sort lightest to darkest, or darkest to lightest if reversed
55-
return reverse ? (lum1 > lum2) - (lum1 < lum2) : (lum1 < lum2) - (lum1 > lum2);
59+
return ((lum1 < lum2) - (lum1 > lum2)) * (reverse ? -1 : 1);
5660
}
5761

5862
void read_gbcpal(const char *filename, struct Color **colors, size_t *num_colors) {
@@ -81,19 +85,10 @@ void filter_colors(struct Color *colors, size_t *num_colors) {
8185
// filter out black, white, and duplicate colors
8286
for (size_t i = 0; i < *num_colors; i++) {
8387
struct Color color = colors[i];
84-
if (color.r == BLACK.r && color.g == BLACK.g && color.b == BLACK.b) {
85-
continue;
86-
}
87-
if (color.r == WHITE.r && color.g == WHITE.g && color.b == WHITE.b) {
88-
continue;
89-
}
90-
if (num_filtered > 0) {
91-
struct Color last = colors[num_filtered - 1];
92-
if (color.r == last.r && color.g == last.g && color.b == last.b) {
93-
continue;
94-
}
88+
if (!same_color(color, BLACK) && !same_color(color, WHITE) &&
89+
(num_filtered == 0 || !same_color(color, colors[num_filtered - 1]))) {
90+
colors[num_filtered++] = color;
9591
}
96-
colors[num_filtered++] = color;
9792
}
9893
*num_colors = num_filtered;
9994
}
@@ -115,7 +110,7 @@ int main(int argc, char *argv[]) {
115110
read_gbcpal(argv[i], &colors, &num_colors);
116111
}
117112

118-
qsort(colors, num_colors, sizeof(*colors), compare_colors);
113+
qsort(colors, num_colors, sizeof(*colors), compare_luminance);
119114
filter_colors(colors, &num_colors);
120115

121116
struct Color pal_colors[4] = {

0 commit comments

Comments
 (0)