You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1450 lines
39 KiB

  1. /*
  2. * libcucul Canvas for ultrafast compositing of Unicode letters
  3. * Copyright (c) 2002-2006 Sam Hocevar <sam@zoy.org>
  4. * All Rights Reserved
  5. *
  6. * $Id$
  7. *
  8. * This library is free software. It comes without any warranty, to
  9. * the extent permitted by applicable law. You can redistribute it
  10. * and/or modify it under the terms of the Do What The Fuck You Want
  11. * To Public License, Version 2, as published by Sam Hocevar. See
  12. * http://sam.zoy.org/wtfpl/COPYING for more details.
  13. */
  14. /*
  15. * This file contains bitmap dithering functions.
  16. */
  17. #include "config.h"
  18. #include "common.h"
  19. #if !defined(__KERNEL__)
  20. # if defined(HAVE_ENDIAN_H)
  21. # include <endian.h>
  22. # endif
  23. # include <stdio.h>
  24. # include <stdlib.h>
  25. # include <limits.h>
  26. # include <string.h>
  27. #endif
  28. #include "cucul.h"
  29. #include "cucul_internals.h"
  30. #define CP437 0
  31. /*
  32. * Local variables
  33. */
  34. #if !defined(_DOXYGEN_SKIP_ME)
  35. # define LOOKUP_VAL 32
  36. # define LOOKUP_SAT 32
  37. # define LOOKUP_HUE 16
  38. #endif
  39. static unsigned char hsv_distances[LOOKUP_VAL][LOOKUP_SAT][LOOKUP_HUE];
  40. static uint16_t lookup_colors[8];
  41. static int lookup_initialised = 0;
  42. static int const hsv_palette[] =
  43. {
  44. /* weight, hue, saturation, value */
  45. 4, 0x0, 0x0, 0x0, /* black */
  46. 5, 0x0, 0x0, 0x5ff, /* 30% */
  47. 5, 0x0, 0x0, 0x9ff, /* 70% */
  48. 4, 0x0, 0x0, 0xfff, /* white */
  49. 3, 0x1000, 0xfff, 0x5ff, /* dark yellow */
  50. 2, 0x1000, 0xfff, 0xfff, /* light yellow */
  51. 3, 0x0, 0xfff, 0x5ff, /* dark red */
  52. 2, 0x0, 0xfff, 0xfff /* light red */
  53. };
  54. /* RGB palette for the new colour picker */
  55. static int const rgb_palette[] =
  56. {
  57. 0x0, 0x0, 0x0,
  58. 0x0, 0x0, 0x7ff,
  59. 0x0, 0x7ff, 0x0,
  60. 0x0, 0x7ff, 0x7ff,
  61. 0x7ff, 0x0, 0x0,
  62. 0x7ff, 0x0, 0x7ff,
  63. 0x7ff, 0x7ff, 0x0,
  64. 0xaaa, 0xaaa, 0xaaa,
  65. 0x555, 0x555, 0x555,
  66. 0x000, 0x000, 0xfff,
  67. 0x000, 0xfff, 0x000,
  68. 0x000, 0xfff, 0xfff,
  69. 0xfff, 0x000, 0x000,
  70. 0xfff, 0x000, 0xfff,
  71. 0xfff, 0xfff, 0x000,
  72. 0xfff, 0xfff, 0xfff,
  73. };
  74. static int const rgb_weight[] =
  75. {
  76. /* 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2 */
  77. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  78. };
  79. /* List of glyphs */
  80. static uint32_t ascii_glyphs[] =
  81. {
  82. ' ', '.', ':', ';', 't', '%', 'S', 'X', '@', '8', '?'
  83. };
  84. static uint32_t shades_glyphs[] =
  85. {
  86. /* ' '. '·', '░', '▒', '?' */
  87. ' ', 0xb7, 0x2591, 0x2592, '?'
  88. };
  89. static uint32_t blocks_glyphs[] =
  90. {
  91. /* ' ', '▘', '▚', '?' */
  92. ' ', 0x2598, 0x259a, '?'
  93. };
  94. #if !defined(_DOXYGEN_SKIP_ME)
  95. enum color_mode
  96. {
  97. COLOR_MODE_MONO,
  98. COLOR_MODE_GRAY,
  99. COLOR_MODE_8,
  100. COLOR_MODE_16,
  101. COLOR_MODE_FULLGRAY,
  102. COLOR_MODE_FULL8,
  103. COLOR_MODE_FULL16
  104. };
  105. struct cucul_dither
  106. {
  107. int bpp, has_palette, has_alpha;
  108. int w, h, pitch;
  109. int rmask, gmask, bmask, amask;
  110. int rright, gright, bright, aright;
  111. int rleft, gleft, bleft, aleft;
  112. void (*get_hsv)(cucul_dither_t *, char *, int, int);
  113. int red[256], green[256], blue[256], alpha[256];
  114. float gamma;
  115. int gammatab[4097];
  116. /* Bitmap features */
  117. int invert, antialias;
  118. /* Colour mode used for rendering */
  119. enum color_mode color_mode;
  120. /* Glyphs used for rendering */
  121. uint32_t const * glyphs;
  122. unsigned glyph_count;
  123. /* Current dithering method */
  124. void (*init_dither) (int);
  125. unsigned int (*get_dither) (void);
  126. void (*increment_dither) (void);
  127. };
  128. #define HSV_XRATIO 6
  129. #define HSV_YRATIO 3
  130. #define HSV_HRATIO 3
  131. #define HSV_DISTANCE(h, s, v, index) \
  132. (hsv_palette[index * 4] \
  133. * ((HSV_XRATIO * ((v) - hsv_palette[index * 4 + 3]) \
  134. * ((v) - hsv_palette[index * 4 + 3])) \
  135. + (hsv_palette[index * 4 + 3] \
  136. ? (HSV_YRATIO * ((s) - hsv_palette[index * 4 + 2]) \
  137. * ((s) - hsv_palette[index * 4 + 2])) \
  138. : 0) \
  139. + (hsv_palette[index * 4 + 2] \
  140. ? (HSV_HRATIO * ((h) - hsv_palette[index * 4 + 1]) \
  141. * ((h) - hsv_palette[index * 4 + 1])) \
  142. : 0)))
  143. #endif
  144. /*
  145. * Local prototypes
  146. */
  147. static void mask2shift(unsigned long int, int *, int *);
  148. static float gammapow(float x, float y);
  149. static void get_rgba_default(cucul_dither_t const *, uint8_t *, int, int,
  150. unsigned int *);
  151. static int init_lookup(void);
  152. /* Dithering methods */
  153. static void init_no_dither(int);
  154. static unsigned int get_no_dither(void);
  155. static void increment_no_dither(void);
  156. static void init_fstein_dither(int);
  157. static unsigned int get_fstein_dither(void);
  158. static void increment_fstein_dither(void);
  159. static void init_ordered2_dither(int);
  160. static unsigned int get_ordered2_dither(void);
  161. static void increment_ordered2_dither(void);
  162. static void init_ordered4_dither(int);
  163. static unsigned int get_ordered4_dither(void);
  164. static void increment_ordered4_dither(void);
  165. static void init_ordered8_dither(int);
  166. static unsigned int get_ordered8_dither(void);
  167. static void increment_ordered8_dither(void);
  168. static void init_random_dither(int);
  169. static unsigned int get_random_dither(void);
  170. static void increment_random_dither(void);
  171. static inline int sq(int x)
  172. {
  173. return x * x;
  174. }
  175. static inline void rgb2hsv_default(int r, int g, int b,
  176. int *hue, int *sat, int *val)
  177. {
  178. int min, max, delta;
  179. min = r; max = r;
  180. if(min > g) min = g; if(max < g) max = g;
  181. if(min > b) min = b; if(max < b) max = b;
  182. delta = max - min; /* 0 - 0xfff */
  183. *val = max; /* 0 - 0xfff */
  184. if(delta)
  185. {
  186. *sat = 0xfff * delta / max; /* 0 - 0xfff */
  187. /* Generate *hue between 0 and 0x5fff */
  188. if( r == max )
  189. *hue = 0x1000 + 0x1000 * (g - b) / delta;
  190. else if( g == max )
  191. *hue = 0x3000 + 0x1000 * (b - r) / delta;
  192. else
  193. *hue = 0x5000 + 0x1000 * (r - g) / delta;
  194. }
  195. else
  196. {
  197. *sat = 0;
  198. *hue = 0;
  199. }
  200. }
  201. /** \brief Create an internal dither object.
  202. *
  203. * Create a dither structure from its coordinates (depth, width, height and
  204. * pitch) and pixel mask values. If the depth is 8 bits per pixel, the mask
  205. * values are ignored and the colour palette should be set using the
  206. * cucul_set_dither_palette() function. For depths greater than 8 bits per
  207. * pixel, a zero alpha mask causes the alpha values to be ignored.
  208. *
  209. * If an error occurs, NULL is returned and \b errno is set accordingly:
  210. * - \c EINVAL Requested width, height, pitch or bits per pixel value was
  211. * invalid.
  212. * - \c ENOMEM Not enough memory to allocate dither structure.
  213. *
  214. * \param bpp Bitmap depth in bits per pixel.
  215. * \param w Bitmap width in pixels.
  216. * \param h Bitmap height in pixels.
  217. * \param pitch Bitmap pitch in bytes.
  218. * \param rmask Bitmask for red values.
  219. * \param gmask Bitmask for green values.
  220. * \param bmask Bitmask for blue values.
  221. * \param amask Bitmask for alpha values.
  222. * \return Dither object upon success, NULL if an error occurred.
  223. */
  224. cucul_dither_t *cucul_create_dither(unsigned int bpp, unsigned int w,
  225. unsigned int h, unsigned int pitch,
  226. unsigned long int rmask,
  227. unsigned long int gmask,
  228. unsigned long int bmask,
  229. unsigned long int amask)
  230. {
  231. cucul_dither_t *d;
  232. int i;
  233. /* Minor sanity test */
  234. if(!w || !h || !pitch || bpp > 32 || bpp < 8)
  235. {
  236. seterrno(EINVAL);
  237. return NULL;
  238. }
  239. d = malloc(sizeof(cucul_dither_t));
  240. if(!d)
  241. {
  242. seterrno(ENOMEM);
  243. return NULL;
  244. }
  245. if(!lookup_initialised)
  246. {
  247. /* XXX: because we do not wish to be thread-safe, there is a slight
  248. * chance that the following code will be executed twice. It is
  249. * totally harmless. */
  250. init_lookup();
  251. lookup_initialised = 1;
  252. }
  253. d->bpp = bpp;
  254. d->has_palette = 0;
  255. d->has_alpha = amask ? 1 : 0;
  256. d->w = w;
  257. d->h = h;
  258. d->pitch = pitch;
  259. d->rmask = rmask;
  260. d->gmask = gmask;
  261. d->bmask = bmask;
  262. d->amask = amask;
  263. /* Load bitmasks */
  264. if(rmask || gmask || bmask || amask)
  265. {
  266. mask2shift(rmask, &d->rright, &d->rleft);
  267. mask2shift(gmask, &d->gright, &d->gleft);
  268. mask2shift(bmask, &d->bright, &d->bleft);
  269. mask2shift(amask, &d->aright, &d->aleft);
  270. }
  271. /* In 8 bpp mode, default to a grayscale palette */
  272. if(bpp == 8)
  273. {
  274. d->has_palette = 1;
  275. d->has_alpha = 0;
  276. for(i = 0; i < 256; i++)
  277. {
  278. d->red[i] = i * 0xfff / 256;
  279. d->green[i] = i * 0xfff / 256;
  280. d->blue[i] = i * 0xfff / 256;
  281. }
  282. }
  283. /* Default features */
  284. d->invert = 0;
  285. d->antialias = 1;
  286. /* Default gamma value */
  287. for(i = 0; i < 4096; i++)
  288. d->gammatab[i] = i;
  289. /* Default colour mode */
  290. d->color_mode = COLOR_MODE_FULL16;
  291. /* Default character set */
  292. d->glyphs = ascii_glyphs;
  293. d->glyph_count = sizeof(ascii_glyphs) / sizeof(*ascii_glyphs);
  294. /* Default dithering mode */
  295. d->init_dither = init_fstein_dither;
  296. d->get_dither = get_fstein_dither;
  297. d->increment_dither = increment_fstein_dither;
  298. return d;
  299. }
  300. /** \brief Set the palette of an 8bpp dither object.
  301. *
  302. * Set the palette of an 8 bits per pixel bitmap. Values should be between
  303. * 0 and 4095 (0xfff).
  304. *
  305. * If an error occurs, -1 is returned and \b errno is set accordingly:
  306. * - \c EINVAL Dither bits per pixel value is not 8, or one of the pixel
  307. * values was outside the range 0 - 4095.
  308. *
  309. * \param d Dither object.
  310. * \param red Array of 256 red values.
  311. * \param green Array of 256 green values.
  312. * \param blue Array of 256 blue values.
  313. * \param alpha Array of 256 alpha values.
  314. * \return 0 in case of success, -1 if an error occurred.
  315. */
  316. int cucul_set_dither_palette(cucul_dither_t *d,
  317. unsigned int red[], unsigned int green[],
  318. unsigned int blue[], unsigned int alpha[])
  319. {
  320. int i, has_alpha = 0;
  321. if(d->bpp != 8)
  322. {
  323. seterrno(EINVAL);
  324. return -1;
  325. }
  326. for(i = 0; i < 256; i++)
  327. {
  328. if((red[i] | green[i] | blue[i] | alpha[i]) >= 0x1000)
  329. {
  330. seterrno(EINVAL);
  331. return -1;
  332. }
  333. }
  334. for(i = 0; i < 256; i++)
  335. {
  336. d->red[i] = red[i];
  337. d->green[i] = green[i];
  338. d->blue[i] = blue[i];
  339. if(alpha[i])
  340. {
  341. d->alpha[i] = alpha[i];
  342. has_alpha = 1;
  343. }
  344. }
  345. d->has_alpha = has_alpha;
  346. return 0;
  347. }
  348. /** \brief Set the brightness of a dither object.
  349. *
  350. * Set the brightness of dither.
  351. *
  352. * If an error occurs, -1 is returned and \b errno is set accordingly:
  353. * - \c EINVAL Brightness value was out of range.
  354. *
  355. * \param d Dither object.
  356. * \param brightness brightness value.
  357. * \return 0 in case of success, -1 if an error occurred.
  358. */
  359. int cucul_set_dither_brightness(cucul_dither_t *d, float brightness)
  360. {
  361. /* FIXME */
  362. return 0;
  363. }
  364. /** \brief Get the brightness of a dither object.
  365. *
  366. * Get the brightness of the given dither object.
  367. *
  368. * This function never fails.
  369. *
  370. * \param d Dither object.
  371. * \return Brightness value.
  372. */
  373. float cucul_get_dither_brightness(cucul_dither_t *d)
  374. {
  375. /* FIXME */
  376. return 0.0;
  377. }
  378. /** \brief Set the gamma of a dither object.
  379. *
  380. * Set the gamma of the given dither object. A negative value causes
  381. * colour inversion.
  382. *
  383. * If an error occurs, -1 is returned and \b errno is set accordingly:
  384. * - \c EINVAL Gamma value was out of range.
  385. *
  386. * \param d Dither object.
  387. * \param gamma Gamma value.
  388. * \return 0 in case of success, -1 if an error occurred.
  389. */
  390. int cucul_set_dither_gamma(cucul_dither_t *d, float gamma)
  391. {
  392. /* FIXME: we don't need 4096 calls to gammapow(), we could just compute
  393. * a few of them and do linear interpolation for the rest. This will
  394. * probably speed up things a lot. */
  395. int i;
  396. if(gamma < 0.0)
  397. {
  398. d->invert = 1;
  399. gamma = -gamma;
  400. }
  401. else if(gamma == 0.0)
  402. {
  403. seterrno(EINVAL);
  404. return -1;
  405. }
  406. d->gamma = gamma;
  407. for(i = 0; i < 4096; i++)
  408. d->gammatab[i] = 4096.0 * gammapow((float)i / 4096.0, 1.0 / gamma);
  409. return 0;
  410. }
  411. /** \brief Get the gamma of a dither object.
  412. *
  413. * Get the gamma of the given dither object.
  414. *
  415. * This function never fails.
  416. *
  417. * \param d Dither object.
  418. * \return Gamma value.
  419. */
  420. float cucul_get_dither_gamma(cucul_dither_t *d)
  421. {
  422. return d->gamma;
  423. }
  424. /** \brief Set the contrast of a dither object.
  425. *
  426. * Set the contrast of dither.
  427. *
  428. * If an error occurs, -1 is returned and \b errno is set accordingly:
  429. * - \c EINVAL Contrast value was out of range.
  430. *
  431. * \param d Dither object.
  432. * \param contrast contrast value.
  433. * \return 0 in case of success, -1 if an error occurred.
  434. */
  435. int cucul_set_dither_contrast(cucul_dither_t *d, float contrast)
  436. {
  437. /* FIXME */
  438. return 0;
  439. }
  440. /** \brief Set dither antialiasing
  441. *
  442. * Tell the renderer whether to antialias the dither. Antialiasing smoothens
  443. * the rendered image and avoids the commonly seen staircase effect.
  444. * - \c "none": no antialiasing.
  445. * - \c "prefilter" or \c "default": simple prefilter antialiasing. This
  446. * is the default value.
  447. *
  448. * If an error occurs, -1 is returned and \b errno is set accordingly:
  449. * - \c EINVAL Invalid antialiasing mode.
  450. *
  451. * \param d Dither object.
  452. * \param str A string describing the antialiasing method that will be used
  453. * for the dithering.
  454. * \return 0 in case of success, -1 if an error occurred.
  455. */
  456. int cucul_set_dither_antialias(cucul_dither_t *d, char const *str)
  457. {
  458. if(!strcasecmp(str, "none"))
  459. d->antialias = 0;
  460. else if(!strcasecmp(str, "prefilter") || !strcasecmp(str, "default"))
  461. d->antialias = 1;
  462. else
  463. {
  464. seterrno(EINVAL);
  465. return -1;
  466. }
  467. return 0;
  468. }
  469. /** \brief Get available antialiasing methods
  470. *
  471. * Return a list of available antialiasing methods for a given dither. The
  472. * list is a NULL-terminated array of strings, interleaving a string
  473. * containing the internal value for the antialiasing method to be used with
  474. * cucul_set_dither_antialias(), and a string containing the natural
  475. * language description for that antialiasing method.
  476. *
  477. * This function never fails.
  478. *
  479. * \param d Dither object.
  480. * \return An array of strings.
  481. */
  482. char const * const *
  483. cucul_get_dither_antialias_list(cucul_dither_t const *d)
  484. {
  485. static char const * const list[] =
  486. {
  487. "none", "No antialiasing",
  488. "prefilter", "Prefilter antialiasing",
  489. NULL, NULL
  490. };
  491. return list;
  492. }
  493. /** \brief Choose colours used for dithering
  494. *
  495. * Tell the renderer which colours should be used to render the
  496. * bitmap. Valid values for \c str are:
  497. * - \c "mono": use light gray on a black background.
  498. * - \c "gray": use white and two shades of gray on a black background.
  499. * - \c "8": use the 8 ANSI colours on a black background.
  500. * - \c "16": use the 16 ANSI colours on a black background.
  501. * - \c "fullgray": use black, white and two shades of gray for both the
  502. * characters and the background.
  503. * - \c "full8": use the 8 ANSI colours for both the characters and the
  504. * background.
  505. * - \c "full16" or \c "default": use the 16 ANSI colours for both the
  506. * characters and the background. This is the default value.
  507. *
  508. * If an error occurs, -1 is returned and \b errno is set accordingly:
  509. * - \c EINVAL Invalid colour set.
  510. *
  511. * \param d Dither object.
  512. * \param str A string describing the colour set that will be used
  513. * for the dithering.
  514. * \return 0 in case of success, -1 if an error occurred.
  515. */
  516. int cucul_set_dither_color(cucul_dither_t *d, char const *str)
  517. {
  518. if(!strcasecmp(str, "mono"))
  519. d->color_mode = COLOR_MODE_MONO;
  520. else if(!strcasecmp(str, "gray"))
  521. d->color_mode = COLOR_MODE_GRAY;
  522. else if(!strcasecmp(str, "8"))
  523. d->color_mode = COLOR_MODE_8;
  524. else if(!strcasecmp(str, "16"))
  525. d->color_mode = COLOR_MODE_16;
  526. else if(!strcasecmp(str, "fullgray"))
  527. d->color_mode = COLOR_MODE_FULLGRAY;
  528. else if(!strcasecmp(str, "full8"))
  529. d->color_mode = COLOR_MODE_FULL8;
  530. else if(!strcasecmp(str, "full16") || !strcasecmp(str, "default"))
  531. d->color_mode = COLOR_MODE_FULL16;
  532. else
  533. {
  534. seterrno(EINVAL);
  535. return -1;
  536. }
  537. return 0;
  538. }
  539. /** \brief Get available colour modes
  540. *
  541. * Return a list of available colour modes for a given dither. The list
  542. * is a NULL-terminated array of strings, interleaving a string containing
  543. * the internal value for the colour mode, to be used with
  544. * cucul_set_dither_color(), and a string containing the natural
  545. * language description for that colour mode.
  546. *
  547. * This function never fails.
  548. *
  549. * \param d Dither object.
  550. * \return An array of strings.
  551. */
  552. char const * const *
  553. cucul_get_dither_color_list(cucul_dither_t const *d)
  554. {
  555. static char const * const list[] =
  556. {
  557. "mono", "white on black",
  558. "gray", "grayscale on black",
  559. "8", "8 colours on black",
  560. "16", "16 colours on black",
  561. "fullgray", "full grayscale",
  562. "full8", "full 8 colours",
  563. "full16", "full 16 colours",
  564. NULL, NULL
  565. };
  566. return list;
  567. }
  568. /** \brief Choose characters used for dithering
  569. *
  570. * Tell the renderer which characters should be used to render the
  571. * dither. Valid values for \c str are:
  572. * - \c "ascii" or \c "default": use only ASCII characters. This is the
  573. * default value.
  574. * - \c "shades": use Unicode characters "U+2591 LIGHT SHADE", "U+2592
  575. * MEDIUM SHADE" and "U+2593 DARK SHADE". These characters are also
  576. * present in the CP437 codepage available on DOS and VGA.
  577. * - \c "blocks": use Unicode quarter-cell block combinations. These
  578. * characters are only found in the Unicode set.
  579. *
  580. * If an error occurs, -1 is returned and \b errno is set accordingly:
  581. * - \c EINVAL Invalid character set.
  582. *
  583. * \param d Dither object.
  584. * \param str A string describing the characters that need to be used
  585. * for the dithering.
  586. * \return 0 in case of success, -1 if an error occurred.
  587. */
  588. int cucul_set_dither_charset(cucul_dither_t *d, char const *str)
  589. {
  590. if(!strcasecmp(str, "shades"))
  591. {
  592. d->glyphs = shades_glyphs;
  593. d->glyph_count = sizeof(shades_glyphs) / sizeof(*shades_glyphs);
  594. }
  595. else if(!strcasecmp(str, "blocks"))
  596. {
  597. d->glyphs = blocks_glyphs;
  598. d->glyph_count = sizeof(blocks_glyphs) / sizeof(*blocks_glyphs);
  599. }
  600. else if(!strcasecmp(str, "ascii") || !strcasecmp(str, "default"))
  601. {
  602. d->glyphs = ascii_glyphs;
  603. d->glyph_count = sizeof(ascii_glyphs) / sizeof(*ascii_glyphs);
  604. }
  605. else
  606. {
  607. seterrno(EINVAL);
  608. return -1;
  609. }
  610. return 0;
  611. }
  612. /** \brief Get available dither character sets
  613. *
  614. * Return a list of available character sets for a given dither. The list
  615. * is a NULL-terminated array of strings, interleaving a string containing
  616. * the internal value for the character set, to be used with
  617. * cucul_set_dither_charset(), and a string containing the natural
  618. * language description for that character set.
  619. *
  620. * This function never fails.
  621. *
  622. * \param d Dither object.
  623. * \return An array of strings.
  624. */
  625. char const * const * cucul_get_dither_charset_list(cucul_dither_t const *d)
  626. {
  627. static char const * const list[] =
  628. {
  629. "ascii", "plain ASCII",
  630. "shades", "CP437 shades",
  631. "blocks", "Unicode blocks",
  632. NULL, NULL
  633. };
  634. return list;
  635. }
  636. /** \brief Set dithering method
  637. *
  638. * Tell the renderer which dithering method should be used. Dithering is
  639. * necessary because the picture being rendered has usually far more colours
  640. * than the available palette. Valid values for \c str are:
  641. * - \c "none": no dithering is used, the nearest matching colour is used.
  642. * - \c "ordered2": use a 2x2 Bayer matrix for dithering.
  643. * - \c "ordered4": use a 4x4 Bayer matrix for dithering.
  644. * - \c "ordered8": use a 8x8 Bayer matrix for dithering.
  645. * - \c "random": use random dithering.
  646. * - \c "fstein": use Floyd-Steinberg dithering. This is the default value.
  647. *
  648. * If an error occurs, -1 is returned and \b errno is set accordingly:
  649. * - \c EINVAL Unknown dithering mode.
  650. *
  651. * \param d Dither object.
  652. * \param str A string describing the method that needs to be used
  653. * for the dithering.
  654. * \return 0 in case of success, -1 if an error occurred.
  655. */
  656. int cucul_set_dither_mode(cucul_dither_t *d, char const *str)
  657. {
  658. if(!strcasecmp(str, "none"))
  659. {
  660. d->init_dither = init_no_dither;
  661. d->get_dither = get_no_dither;
  662. d->increment_dither = increment_no_dither;
  663. }
  664. else if(!strcasecmp(str, "ordered2"))
  665. {
  666. d->init_dither = init_ordered2_dither;
  667. d->get_dither = get_ordered2_dither;
  668. d->increment_dither = increment_ordered2_dither;
  669. }
  670. else if(!strcasecmp(str, "ordered4"))
  671. {
  672. d->init_dither = init_ordered4_dither;
  673. d->get_dither = get_ordered4_dither;
  674. d->increment_dither = increment_ordered4_dither;
  675. }
  676. else if(!strcasecmp(str, "ordered8"))
  677. {
  678. d->init_dither = init_ordered8_dither;
  679. d->get_dither = get_ordered8_dither;
  680. d->increment_dither = increment_ordered8_dither;
  681. }
  682. else if(!strcasecmp(str, "random"))
  683. {
  684. d->init_dither = init_random_dither;
  685. d->get_dither = get_random_dither;
  686. d->increment_dither = increment_random_dither;
  687. }
  688. else if(!strcasecmp(str, "fstein") || !strcasecmp(str, "default"))
  689. {
  690. d->init_dither = init_fstein_dither;
  691. d->get_dither = get_fstein_dither;
  692. d->increment_dither = increment_fstein_dither;
  693. }
  694. else
  695. {
  696. seterrno(EINVAL);
  697. return -1;
  698. }
  699. return 0;
  700. }
  701. /** \brief Get dithering methods
  702. *
  703. * Return a list of available dithering methods for a given dither. The list
  704. * is a NULL-terminated array of strings, interleaving a string containing
  705. * the internal value for the dithering method, to be used with
  706. * cucul_set_dither_dithering(), and a string containing the natural
  707. * language description for that dithering method.
  708. *
  709. * This function never fails.
  710. *
  711. * \param d Dither object.
  712. * \return An array of strings.
  713. */
  714. char const * const * cucul_get_dither_mode_list(cucul_dither_t const *d)
  715. {
  716. static char const * const list[] =
  717. {
  718. "none", "no dithering",
  719. "ordered2", "2x2 ordered dithering",
  720. "ordered4", "4x4 ordered dithering",
  721. "ordered8", "8x8 ordered dithering",
  722. "random", "random dithering",
  723. "fstein", "Floyd-Steinberg dithering",
  724. NULL, NULL
  725. };
  726. return list;
  727. }
  728. /** \brief Dither a bitmap on the canvas.
  729. *
  730. * Dither a bitmap at the given coordinates. The dither can be of any size
  731. * and will be stretched to the text area.
  732. *
  733. * This function never fails.
  734. *
  735. * \param cv A handle to the libcucul canvas.
  736. * \param x X coordinate of the upper-left corner of the drawing area.
  737. * \param y Y coordinate of the upper-left corner of the drawing area.
  738. * \param w Width of the drawing area.
  739. * \param h Height of the drawing area.
  740. * \param d Dither object to be drawn.
  741. * \param pixels Bitmap's pixels.
  742. * \return This function always returns 0.
  743. */
  744. int cucul_dither_bitmap(cucul_canvas_t *cv, int x, int y, int w, int h,
  745. cucul_dither_t const *d, void *pixels)
  746. {
  747. int *floyd_steinberg, *fs_r, *fs_g, *fs_b;
  748. uint32_t savedattr;
  749. int fs_length;
  750. int x1, y1, x2, y2, pitch, deltax, deltay;
  751. unsigned int dchmax;
  752. if(!d || !pixels)
  753. return 0;
  754. savedattr = cucul_get_attr(cv, -1, -1);
  755. x1 = x; x2 = x + w - 1;
  756. y1 = y; y2 = y + h - 1;
  757. /* FIXME: do not overwrite arguments */
  758. w = d->w;
  759. h = d->h;
  760. pitch = d->pitch;
  761. deltax = x2 - x1 + 1;
  762. deltay = y2 - y1 + 1;
  763. dchmax = d->glyph_count;
  764. fs_length = ((int)cv->width <= x2 ? (int)cv->width : x2) + 1;
  765. floyd_steinberg = malloc(3 * (fs_length + 2) * sizeof(int));
  766. memset(floyd_steinberg, 0, 3 * (fs_length + 2) * sizeof(int));
  767. fs_r = floyd_steinberg + 1;
  768. fs_g = fs_r + fs_length + 2;
  769. fs_b = fs_g + fs_length + 2;
  770. for(y = y1 > 0 ? y1 : 0; y <= y2 && y <= (int)cv->height; y++)
  771. {
  772. int remain_r = 0, remain_g = 0, remain_b = 0;
  773. for(x = x1 > 0 ? x1 : 0, d->init_dither(y);
  774. x <= x2 && x <= (int)cv->width;
  775. x++)
  776. {
  777. unsigned int i;
  778. int ch = 0, distmin;
  779. unsigned int rgba[4];
  780. int fg_r = 0, fg_g = 0, fg_b = 0, bg_r, bg_g, bg_b;
  781. int fromx, fromy, tox, toy, myx, myy, dots, dist;
  782. int error[3];
  783. unsigned int outfg = 0, outbg = 0;
  784. uint32_t outch;
  785. rgba[0] = rgba[1] = rgba[2] = rgba[3] = 0;
  786. /* First get RGB */
  787. if(d->antialias)
  788. {
  789. fromx = (x - x1) * w / deltax;
  790. fromy = (y - y1) * h / deltay;
  791. tox = (x - x1 + 1) * w / deltax;
  792. toy = (y - y1 + 1) * h / deltay;
  793. /* We want at least one pixel */
  794. if(tox == fromx) tox++;
  795. if(toy == fromy) toy++;
  796. dots = 0;
  797. for(myx = fromx; myx < tox; myx++)
  798. for(myy = fromy; myy < toy; myy++)
  799. {
  800. dots++;
  801. get_rgba_default(d, pixels, myx, myy, rgba);
  802. }
  803. /* Normalize */
  804. rgba[0] /= dots;
  805. rgba[1] /= dots;
  806. rgba[2] /= dots;
  807. rgba[3] /= dots;
  808. }
  809. else
  810. {
  811. fromx = (x - x1) * w / deltax;
  812. fromy = (y - y1) * h / deltay;
  813. tox = (x - x1 + 1) * w / deltax;
  814. toy = (y - y1 + 1) * h / deltay;
  815. /* tox and toy can overflow the canvas, but they cannot overflow
  816. * when averaged with fromx and fromy because these are guaranteed
  817. * to be within the pixel boundaries. */
  818. myx = (fromx + tox) / 2;
  819. myy = (fromy + toy) / 2;
  820. get_rgba_default(d, pixels, myx, myy, rgba);
  821. }
  822. if(d->has_alpha && rgba[3] < 0x800)
  823. {
  824. remain_r = remain_g = remain_b = 0;
  825. fs_r[x] = 0;
  826. fs_g[x] = 0;
  827. fs_b[x] = 0;
  828. continue;
  829. }
  830. /* XXX: OMG HAX */
  831. if(d->init_dither == init_fstein_dither)
  832. {
  833. rgba[0] += remain_r;
  834. rgba[1] += remain_g;
  835. rgba[2] += remain_b;
  836. }
  837. else
  838. {
  839. rgba[0] += (d->get_dither() - 0x80) * 4;
  840. rgba[1] += (d->get_dither() - 0x80) * 4;
  841. rgba[2] += (d->get_dither() - 0x80) * 4;
  842. }
  843. distmin = INT_MAX;
  844. for(i = 0; i < 16; i++)
  845. {
  846. dist = sq(rgba[0] - rgb_palette[i * 3])
  847. + sq(rgba[1] - rgb_palette[i * 3 + 1])
  848. + sq(rgba[2] - rgb_palette[i * 3 + 2]);
  849. dist *= rgb_weight[i];
  850. if(dist < distmin)
  851. {
  852. outbg = i;
  853. distmin = dist;
  854. }
  855. }
  856. bg_r = rgb_palette[outbg * 3];
  857. bg_g = rgb_palette[outbg * 3 + 1];
  858. bg_b = rgb_palette[outbg * 3 + 2];
  859. /* FIXME: we currently only honour "full16" */
  860. if(d->color_mode == COLOR_MODE_FULL16)
  861. {
  862. distmin = INT_MAX;
  863. for(i = 0; i < 16; i++)
  864. {
  865. if(i == outbg)
  866. continue;
  867. dist = sq(rgba[0] - rgb_palette[i * 3])
  868. + sq(rgba[1] - rgb_palette[i * 3 + 1])
  869. + sq(rgba[2] - rgb_palette[i * 3 + 2]);
  870. dist *= rgb_weight[i];
  871. if(dist < distmin)
  872. {
  873. outfg = i;
  874. distmin = dist;
  875. }
  876. }
  877. fg_r = rgb_palette[outfg * 3];
  878. fg_g = rgb_palette[outfg * 3 + 1];
  879. fg_b = rgb_palette[outfg * 3 + 2];
  880. distmin = INT_MAX;
  881. for(i = 0; i < dchmax - 1; i++)
  882. {
  883. int newr = i * fg_r + ((2*dchmax-1) - i) * bg_r;
  884. int newg = i * fg_g + ((2*dchmax-1) - i) * bg_g;
  885. int newb = i * fg_b + ((2*dchmax-1) - i) * bg_b;
  886. dist = abs(rgba[0] * (2*dchmax-1) - newr)
  887. + abs(rgba[1] * (2*dchmax-1) - newg)
  888. + abs(rgba[2] * (2*dchmax-1) - newb);
  889. if(dist < distmin)
  890. {
  891. ch = i;
  892. distmin = dist;
  893. }
  894. }
  895. outch = d->glyphs[ch];
  896. /* XXX: OMG HAX */
  897. if(d->init_dither == init_fstein_dither)
  898. {
  899. error[0] = rgba[0] - (fg_r * ch + bg_r * ((2*dchmax-1) - ch)) / (2*dchmax-1);
  900. error[1] = rgba[1] - (fg_g * ch + bg_g * ((2*dchmax-1) - ch)) / (2*dchmax-1);
  901. error[2] = rgba[2] - (fg_b * ch + bg_b * ((2*dchmax-1) - ch)) / (2*dchmax-1);
  902. }
  903. }
  904. else
  905. {
  906. unsigned int lum = rgba[0];
  907. if(rgba[1] > lum) lum = rgba[1];
  908. if(rgba[2] > lum) lum = rgba[2];
  909. outfg = outbg;
  910. outbg = CUCUL_BLACK;
  911. ch = lum * dchmax / 0x1000;
  912. if(ch < 0)
  913. ch = 0;
  914. else if(ch > (int)(dchmax - 1))
  915. ch = dchmax - 1;
  916. outch = d->glyphs[ch];
  917. /* XXX: OMG HAX */
  918. if(d->init_dither == init_fstein_dither)
  919. {
  920. error[0] = rgba[0] - bg_r * ch / (dchmax-1);
  921. error[1] = rgba[1] - bg_g * ch / (dchmax-1);
  922. error[2] = rgba[2] - bg_b * ch / (dchmax-1);
  923. }
  924. }
  925. /* XXX: OMG HAX */
  926. if(d->init_dither == init_fstein_dither)
  927. {
  928. remain_r = fs_r[x+1] + 7 * error[0] / 16;
  929. remain_g = fs_g[x+1] + 7 * error[1] / 16;
  930. remain_b = fs_b[x+1] + 7 * error[2] / 16;
  931. fs_r[x-1] += 3 * error[0] / 16;
  932. fs_g[x-1] += 3 * error[1] / 16;
  933. fs_b[x-1] += 3 * error[2] / 16;
  934. fs_r[x] = 5 * error[0] / 16;
  935. fs_g[x] = 5 * error[1] / 16;
  936. fs_b[x] = 5 * error[2] / 16;
  937. fs_r[x+1] = 1 * error[0] / 16;
  938. fs_g[x+1] = 1 * error[1] / 16;
  939. fs_b[x+1] = 1 * error[2] / 16;
  940. }
  941. if(d->invert)
  942. {
  943. outfg = 15 - outfg;
  944. outbg = 15 - outbg;
  945. }
  946. /* Now output the character */
  947. cucul_set_color_ansi(cv, outfg, outbg);
  948. cucul_put_char(cv, x, y, outch);
  949. d->increment_dither();
  950. }
  951. /* end loop */
  952. }
  953. free(floyd_steinberg);
  954. cucul_set_attr(cv, savedattr);
  955. return 0;
  956. }
  957. /** \brief Free the memory associated with a dither.
  958. *
  959. * Free the memory allocated by cucul_create_dither().
  960. *
  961. * This function never fails.
  962. *
  963. * \param d Dither object.
  964. * \return This function always returns 0.
  965. */
  966. int cucul_free_dither(cucul_dither_t *d)
  967. {
  968. if(!d)
  969. return 0;
  970. free(d);
  971. return 0;
  972. }
  973. /*
  974. * XXX: The following functions are local.
  975. */
  976. /* Convert a mask, eg. 0x0000ff00, to shift values, eg. 8 and -4. */
  977. static void mask2shift(unsigned long int mask, int *right, int *left)
  978. {
  979. int rshift = 0, lshift = 0;
  980. if(!mask)
  981. {
  982. *right = *left = 0;
  983. return;
  984. }
  985. while(!(mask & 1))
  986. {
  987. mask >>= 1;
  988. rshift++;
  989. }
  990. *right = rshift;
  991. while(mask & 1)
  992. {
  993. mask >>= 1;
  994. lshift++;
  995. }
  996. *left = 12 - lshift;
  997. }
  998. /* Compute x^y without relying on the math library */
  999. static float gammapow(float x, float y)
  1000. {
  1001. #ifdef HAVE_FLDLN2
  1002. register double logx;
  1003. register long double v, e;
  1004. #else
  1005. register float tmp, t, t2, r;
  1006. int i;
  1007. #endif
  1008. if(x == 0.0)
  1009. return y == 0.0 ? 1.0 : 0.0;
  1010. #ifdef HAVE_FLDLN2
  1011. /* FIXME: this can be optimised by directly calling fyl2x for x and y */
  1012. asm volatile("fldln2; fxch; fyl2x"
  1013. : "=t" (logx) : "0" (x) : "st(1)");
  1014. asm volatile("fldl2e\n\t"
  1015. "fmul %%st(1)\n\t"
  1016. "fst %%st(1)\n\t"
  1017. "frndint\n\t"
  1018. "fxch\n\t"
  1019. "fsub %%st(1)\n\t"
  1020. "f2xm1\n\t"
  1021. : "=t" (v), "=u" (e) : "0" (y * logx));
  1022. v += 1.0;
  1023. asm volatile("fscale"
  1024. : "=t" (v) : "0" (v), "u" (e));
  1025. return v;
  1026. #else
  1027. /* Compute ln(x) for x ∈ ]0,1]
  1028. * ln(x) = 2 * (t + t^3/3 + t^5/5 + ...) with t = (x-1)/(x+1)
  1029. * The convergence is a bit slow, especially when x is near 0. */
  1030. t = (x - 1.0) / (x + 1.0);
  1031. t2 = t * t;
  1032. tmp = r = t;
  1033. for(i = 3; i < 20; i += 2)
  1034. {
  1035. r *= t2;
  1036. tmp += r / i;
  1037. }
  1038. /* Compute -y*ln(x) */
  1039. tmp = - y * 2.0 * tmp;
  1040. /* Compute x^-y as e^t where t = -y*ln(x):
  1041. * e^t = 1 + t/1! + t^2/2! + t^3/3! + t^4/4! + t^5/5! ...
  1042. * The convergence is quite faster here, thanks to the factorial. */
  1043. r = t = tmp;
  1044. tmp = 1.0 + t;
  1045. for(i = 2; i < 16; i++)
  1046. {
  1047. r = r * t / i;
  1048. tmp += r;
  1049. }
  1050. /* Return x^y as 1/(x^-y) */
  1051. return 1.0 / tmp;
  1052. #endif
  1053. }
  1054. static void get_rgba_default(cucul_dither_t const *d, uint8_t *pixels,
  1055. int x, int y, unsigned int *rgba)
  1056. {
  1057. uint32_t bits;
  1058. pixels += (d->bpp / 8) * x + d->pitch * y;
  1059. switch(d->bpp / 8)
  1060. {
  1061. case 4:
  1062. bits = *(uint32_t *)pixels;
  1063. break;
  1064. case 3:
  1065. {
  1066. #if defined(HAVE_ENDIAN_H)
  1067. if(__BYTE_ORDER == __BIG_ENDIAN)
  1068. #else
  1069. /* This is compile-time optimised with at least -O1 or -Os */
  1070. uint32_t const tmp = 0x12345678;
  1071. if(*(uint8_t const *)&tmp == 0x12)
  1072. #endif
  1073. bits = ((uint32_t)pixels[0] << 16) |
  1074. ((uint32_t)pixels[1] << 8) |
  1075. ((uint32_t)pixels[2]);
  1076. else
  1077. bits = ((uint32_t)pixels[2] << 16) |
  1078. ((uint32_t)pixels[1] << 8) |
  1079. ((uint32_t)pixels[0]);
  1080. break;
  1081. }
  1082. case 2:
  1083. bits = *(uint16_t *)pixels;
  1084. break;
  1085. case 1:
  1086. default:
  1087. bits = pixels[0];
  1088. break;
  1089. }
  1090. if(d->has_palette)
  1091. {
  1092. rgba[0] += d->gammatab[d->red[bits]];
  1093. rgba[1] += d->gammatab[d->green[bits]];
  1094. rgba[2] += d->gammatab[d->blue[bits]];
  1095. rgba[3] += d->alpha[bits];
  1096. }
  1097. else
  1098. {
  1099. rgba[0] += d->gammatab[((bits & d->rmask) >> d->rright) << d->rleft];
  1100. rgba[1] += d->gammatab[((bits & d->gmask) >> d->gright) << d->gleft];
  1101. rgba[2] += d->gammatab[((bits & d->bmask) >> d->bright) << d->bleft];
  1102. rgba[3] += ((bits & d->amask) >> d->aright) << d->aleft;
  1103. }
  1104. }
  1105. /*
  1106. * No dithering
  1107. */
  1108. static void init_no_dither(int line)
  1109. {
  1110. ;
  1111. }
  1112. static unsigned int get_no_dither(void)
  1113. {
  1114. return 0x80;
  1115. }
  1116. static void increment_no_dither(void)
  1117. {
  1118. return;
  1119. }
  1120. /*
  1121. * Floyd-Steinberg dithering
  1122. */
  1123. static void init_fstein_dither(int line)
  1124. {
  1125. ;
  1126. }
  1127. static unsigned int get_fstein_dither(void)
  1128. {
  1129. return 0x80;
  1130. }
  1131. static void increment_fstein_dither(void)
  1132. {
  1133. return;
  1134. }
  1135. /*
  1136. * Ordered 2 dithering
  1137. */
  1138. static unsigned int const *ordered2_table;
  1139. static unsigned int ordered2_index;
  1140. static void init_ordered2_dither(int line)
  1141. {
  1142. static unsigned int const dither2x2[] =
  1143. {
  1144. 0x00, 0x80,
  1145. 0xc0, 0x40,
  1146. };
  1147. ordered2_table = dither2x2 + (line % 2) * 2;
  1148. ordered2_index = 0;
  1149. }
  1150. static unsigned int get_ordered2_dither(void)
  1151. {
  1152. return ordered2_table[ordered2_index];
  1153. }
  1154. static void increment_ordered2_dither(void)
  1155. {
  1156. ordered2_index = (ordered2_index + 1) % 2;
  1157. }
  1158. /*
  1159. * Ordered 4 dithering
  1160. */
  1161. /*static int dither4x4[] = { 5, 0, 1, 6,
  1162. -1, -6, -5, 2,
  1163. -2, -7, -8, 3,
  1164. 4, -3, -4, -7};*/
  1165. static unsigned int const *ordered4_table;
  1166. static unsigned int ordered4_index;
  1167. static void init_ordered4_dither(int line)
  1168. {
  1169. static unsigned int const dither4x4[] =
  1170. {
  1171. 0x00, 0x80, 0x20, 0xa0,
  1172. 0xc0, 0x40, 0xe0, 0x60,
  1173. 0x30, 0xb0, 0x10, 0x90,
  1174. 0xf0, 0x70, 0xd0, 0x50
  1175. };
  1176. ordered4_table = dither4x4 + (line % 4) * 4;
  1177. ordered4_index = 0;
  1178. }
  1179. static unsigned int get_ordered4_dither(void)
  1180. {
  1181. return ordered4_table[ordered4_index];
  1182. }
  1183. static void increment_ordered4_dither(void)
  1184. {
  1185. ordered4_index = (ordered4_index + 1) % 4;
  1186. }
  1187. /*
  1188. * Ordered 8 dithering
  1189. */
  1190. static unsigned int const *ordered8_table;
  1191. static unsigned int ordered8_index;
  1192. static void init_ordered8_dither(int line)
  1193. {
  1194. static unsigned int const dither8x8[] =
  1195. {
  1196. 0x00, 0x80, 0x20, 0xa0, 0x08, 0x88, 0x28, 0xa8,
  1197. 0xc0, 0x40, 0xe0, 0x60, 0xc8, 0x48, 0xe8, 0x68,
  1198. 0x30, 0xb0, 0x10, 0x90, 0x38, 0xb8, 0x18, 0x98,
  1199. 0xf0, 0x70, 0xd0, 0x50, 0xf8, 0x78, 0xd8, 0x58,
  1200. 0x0c, 0x8c, 0x2c, 0xac, 0x04, 0x84, 0x24, 0xa4,
  1201. 0xcc, 0x4c, 0xec, 0x6c, 0xc4, 0x44, 0xe4, 0x64,
  1202. 0x3c, 0xbc, 0x1c, 0x9c, 0x34, 0xb4, 0x14, 0x94,
  1203. 0xfc, 0x7c, 0xdc, 0x5c, 0xf4, 0x74, 0xd4, 0x54,
  1204. };
  1205. ordered8_table = dither8x8 + (line % 8) * 8;
  1206. ordered8_index = 0;
  1207. }
  1208. static unsigned int get_ordered8_dither(void)
  1209. {
  1210. return ordered8_table[ordered8_index];
  1211. }
  1212. static void increment_ordered8_dither(void)
  1213. {
  1214. ordered8_index = (ordered8_index + 1) % 8;
  1215. }
  1216. /*
  1217. * Random dithering
  1218. */
  1219. static void init_random_dither(int line)
  1220. {
  1221. ;
  1222. }
  1223. static unsigned int get_random_dither(void)
  1224. {
  1225. return cucul_rand(0x00, 0x100);
  1226. }
  1227. static void increment_random_dither(void)
  1228. {
  1229. return;
  1230. }
  1231. /*
  1232. * Lookup tables
  1233. */
  1234. static int init_lookup(void)
  1235. {
  1236. unsigned int v, s, h;
  1237. /* These ones are constant */
  1238. lookup_colors[0] = CUCUL_BLACK;
  1239. lookup_colors[1] = CUCUL_DARKGRAY;
  1240. lookup_colors[2] = CUCUL_LIGHTGRAY;
  1241. lookup_colors[3] = CUCUL_WHITE;
  1242. /* These ones will be overwritten */
  1243. lookup_colors[4] = CUCUL_MAGENTA;
  1244. lookup_colors[5] = CUCUL_LIGHTMAGENTA;
  1245. lookup_colors[6] = CUCUL_RED;
  1246. lookup_colors[7] = CUCUL_LIGHTRED;
  1247. for(v = 0; v < LOOKUP_VAL; v++)
  1248. for(s = 0; s < LOOKUP_SAT; s++)
  1249. for(h = 0; h < LOOKUP_HUE; h++)
  1250. {
  1251. int i, distbg, distfg, dist;
  1252. int val, sat, hue;
  1253. unsigned char outbg, outfg;
  1254. val = 0xfff * v / (LOOKUP_VAL - 1);
  1255. sat = 0xfff * s / (LOOKUP_SAT - 1);
  1256. hue = 0xfff * h / (LOOKUP_HUE - 1);
  1257. /* Initialise distances to the distance between pure black HSV
  1258. * coordinates and our white colour (3) */
  1259. outbg = outfg = 3;
  1260. distbg = distfg = HSV_DISTANCE(0, 0, 0, 3);
  1261. /* Calculate distances to eight major colour values and store the
  1262. * two nearest points in our lookup table. */
  1263. for(i = 0; i < 8; i++)
  1264. {
  1265. dist = HSV_DISTANCE(hue, sat, val, i);
  1266. if(dist <= distbg)
  1267. {
  1268. outfg = outbg;
  1269. distfg = distbg;
  1270. outbg = i;
  1271. distbg = dist;
  1272. }
  1273. else if(dist <= distfg)
  1274. {
  1275. outfg = i;
  1276. distfg = dist;
  1277. }
  1278. }
  1279. hsv_distances[v][s][h] = (outfg << 4) | outbg;
  1280. }
  1281. return 0;
  1282. }