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.
 
 
 
 
 
 

1125 lines
32 KiB

  1. #include "config.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <math.h>
  6. #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
  7. #include <CGAL/Delaunay_triangulation_2.h>
  8. #include <CGAL/natural_neighbor_coordinates_2.h>
  9. #include <pipi.h>
  10. #include "../genethumb/mygetopt.h"
  11. /*
  12. * User-definable settings.
  13. */
  14. /* The Unicode characters at disposal - XXX: must be _ordered_ */
  15. static const uint32_t unichars[] =
  16. {
  17. /* Printable ASCII (except space) */
  18. //0x0021, 0x007f,
  19. /* Stupid symbols and Dingbats shit */
  20. //0x25a0, 0x2600, /* Geometric Shapes */
  21. //0x2600, 0x269e, 0x26a0, 0x26bd, 0x26c0, 0x26c4, /* Misc. Symbols */
  22. //0x2701, 0x2705, 0x2706, 0x270a, 0x270c, 0x2728, 0x2729, 0x274c,
  23. // 0x274d, 0x274e, 0x274f, 0x2753, 0x2756, 0x2757, 0x2758, 0x275f,
  24. // 0x2761, 0x2795, 0x2798, 0x27b0, 0x27b1, 0x27bf, /* Dingbats */
  25. /* Chinese-looking stuff */
  26. //0x2e80, 0x2e9a, 0x2e9b, 0x2ef4, /* CJK Radicals Supplement */
  27. //0x2f00, 0x2fd6, /* Kangxi Radicals */
  28. //0x3400, 0x4db6, /* CJK Unified Ideographs Extension A */
  29. 0x4e00, 0x9fa6, /* CJK Unified Ideographs */
  30. /* Korean - most people don't know the difference anyway */
  31. //0xac00, 0xd7a4, /* Hangul Syllables */
  32. /* More Chinese */
  33. //0xf900, 0xfa2e, 0xfa30, 0xfa6b, 0xfa70, 0xfada, /* CJK Compat. Idgphs. */
  34. /* TODO: there's also the U+20000 and U+2f800 planes, but they're
  35. * not supported by the Twitter Javascript filter (yet?). */
  36. /* End of list marker - XXX: don't remove! */
  37. 0x0000, 0x0000
  38. };
  39. /* The maximum image size we want to support */
  40. #define MAX_W 4000
  41. #define MAX_H 4000
  42. /* How does the algorithm work: one point per cell, or two */
  43. #define POINTS_PER_CELL 2
  44. /* The range value for point parameters: X Y, red/green/blue, "strength"
  45. * Tested values (on Mona Lisa) are:
  46. * 16 16 5 5 5 2 -> 0.06511725914
  47. * 16 16 6 7 6 1 -> 0.05731491348 *
  48. * 16 16 7 6 6 1 -> 0.06450513783
  49. * 14 14 7 7 6 1 -> 0.0637207893
  50. * 19 19 6 6 5 1 -> 0.06801999094 */
  51. static unsigned int RANGE_X = 16;
  52. static unsigned int RANGE_Y = 16;
  53. static unsigned int RANGE_R = 6;
  54. static unsigned int RANGE_G = 6;
  55. static unsigned int RANGE_B = 6;
  56. static unsigned int RANGE_S = 1;
  57. /*
  58. * These values can be overwritten at runtime
  59. */
  60. static bool DEBUG = false;
  61. /* The maximum message length */
  62. static int MAX_MSG_LEN = 1140;
  63. static int ITERATIONS_PER_POINT = 50;
  64. /*
  65. * These values are computed at runtime
  66. */
  67. static float TOTAL_BITS;
  68. static float HEADER_BITS;
  69. static float DATA_BITS;
  70. static float CELL_BITS;
  71. static int NUM_CHARACTERS;
  72. static int MAX_ITERATIONS;
  73. static unsigned int TOTAL_CELLS;
  74. #define RANGE_SY (RANGE_S*RANGE_Y)
  75. #define RANGE_SYX (RANGE_S*RANGE_Y*RANGE_X)
  76. #define RANGE_SYXR (RANGE_S*RANGE_Y*RANGE_X*RANGE_R)
  77. #define RANGE_SYXRG (RANGE_S*RANGE_Y*RANGE_X*RANGE_R*RANGE_G)
  78. #define RANGE_SYXRGB (RANGE_S*RANGE_Y*RANGE_X*RANGE_R*RANGE_G*RANGE_B)
  79. struct K : CGAL::Exact_predicates_inexact_constructions_kernel {};
  80. typedef CGAL::Delaunay_triangulation_2<K> Delaunay_triangulation;
  81. typedef std::vector<std::pair<K::Point_2, K::FT> > Point_coordinate_vector;
  82. /* Global aspect ratio */
  83. static unsigned int dw, dh;
  84. /* Global point encoding */
  85. static uint32_t points[4096]; /* FIXME: allocate this dynamically */
  86. static int npoints = 0;
  87. /* Global triangulation */
  88. static Delaunay_triangulation dt;
  89. /*
  90. * Unicode stuff handling
  91. */
  92. /* Return the number of chars in the unichars table */
  93. static int count_unichars(void)
  94. {
  95. int ret = 0;
  96. for(int u = 0; unichars[u] != unichars[u + 1]; u += 2)
  97. ret += unichars[u + 1] - unichars[u];
  98. return ret;
  99. }
  100. /* Get the ith Unicode character in our list */
  101. static uint32_t index2uni(uint32_t i)
  102. {
  103. for(int u = 0; unichars[u] != unichars[u + 1]; u += 2)
  104. if(i < unichars[u + 1] - unichars[u])
  105. return unichars[u] + i;
  106. else
  107. i -= unichars[u + 1] - unichars[u];
  108. return 0; /* Should not happen! */
  109. }
  110. /* Convert a Unicode character to its position in the compact list */
  111. static uint32_t uni2index(uint32_t x)
  112. {
  113. uint32_t ret = 0;
  114. for(int u = 0; unichars[u] != unichars[u + 1]; u += 2)
  115. if(x < unichars[u + 1])
  116. return ret + x - unichars[u];
  117. else
  118. ret += unichars[u + 1] - unichars[u];
  119. return ret; /* Should not happen! */
  120. }
  121. static uint8_t const utf8_trailing[256] =
  122. {
  123. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  124. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  125. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  126. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  127. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  128. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  129. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  130. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
  131. };
  132. static uint32_t const utf8_offsets[6] =
  133. {
  134. 0x00000000UL, 0x00003080UL, 0x000E2080UL,
  135. 0x03C82080UL, 0xFA082080UL, 0x82082080UL
  136. };
  137. static uint32_t fread_utf8(FILE *f)
  138. {
  139. int ch, i = 0, todo = -1;
  140. uint32_t ret = 0;
  141. for(;;)
  142. {
  143. ch = fgetc(f);
  144. if(!ch)
  145. return 0;
  146. if(todo == -1)
  147. todo = utf8_trailing[ch];
  148. ret += ((uint32_t)ch) << (6 * (todo - i));
  149. if(todo == i++)
  150. return ret - utf8_offsets[todo];
  151. }
  152. }
  153. static void fwrite_utf8(FILE *f, uint32_t x)
  154. {
  155. static const uint8_t mark[7] =
  156. {
  157. 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
  158. };
  159. char buf[8];
  160. char *parser = buf;
  161. size_t bytes;
  162. if(x < 0x80)
  163. {
  164. fprintf(f, "%c", x);
  165. return;
  166. }
  167. bytes = (x < 0x800) ? 2 : (x < 0x10000) ? 3 : 4;
  168. parser += bytes;
  169. *parser = '\0';
  170. switch(bytes)
  171. {
  172. case 4: *--parser = (x | 0x80) & 0xbf; x >>= 6;
  173. case 3: *--parser = (x | 0x80) & 0xbf; x >>= 6;
  174. case 2: *--parser = (x | 0x80) & 0xbf; x >>= 6;
  175. }
  176. *--parser = x | mark[bytes];
  177. fprintf(f, "%s", buf);
  178. }
  179. /*
  180. * Our nifty non-power-of-two bitstack handling
  181. */
  182. class bitstack
  183. {
  184. public:
  185. bitstack() { alloc(); init(0); }
  186. ~bitstack() { delete[] digits; delete[] str; }
  187. char const *tostring()
  188. {
  189. int pos = sprintf(str, "0x%x", digits[msb]);
  190. for(int i = msb - 1; i >= 0; i--)
  191. pos += sprintf(str + pos, "%08x", digits[i]);
  192. return str;
  193. }
  194. void push(uint32_t val, uint32_t range)
  195. {
  196. if(!range)
  197. return;
  198. mul(range);
  199. add(val % range);
  200. }
  201. uint32_t pop(uint32_t range)
  202. {
  203. if(!range)
  204. return 0;
  205. return div(range);
  206. }
  207. bool isempty()
  208. {
  209. for(int i = msb; i >= 0; i--)
  210. if(digits[i])
  211. return false;
  212. return true;
  213. }
  214. private:
  215. bitstack(uint32_t i) { alloc(); init(i); }
  216. bitstack(bitstack const &b)
  217. {
  218. alloc();
  219. msb = b.msb;
  220. memcpy(digits, b.digits, (MAX_MSG_LEN + 1) * sizeof(uint32_t));
  221. }
  222. void alloc()
  223. {
  224. digits = new uint32_t[MAX_MSG_LEN + 1];
  225. str = new char[(MAX_MSG_LEN + 1) * 8 + 1];
  226. }
  227. void init(uint32_t i)
  228. {
  229. msb = 0;
  230. memset(digits, 0, (MAX_MSG_LEN + 1) * sizeof(uint32_t));
  231. digits[0] = i;
  232. }
  233. /* Could be done much faster, but we don't care! */
  234. void add(uint32_t x) { add(bitstack(x)); }
  235. void sub(uint32_t x) { sub(bitstack(x)); }
  236. void add(bitstack const &_b)
  237. {
  238. /* Copy the operand in case we get added to ourselves */
  239. bitstack b(_b);
  240. uint64_t x = 0;
  241. if(msb < b.msb)
  242. msb = b.msb;
  243. for(int i = 0; i <= msb; i++)
  244. {
  245. uint64_t tmp = (uint64_t)digits[i] + (uint64_t)b.digits[i] + x;
  246. digits[i] = tmp;
  247. if((uint64_t)digits[i] == tmp)
  248. x = 0;
  249. else
  250. {
  251. x = 1;
  252. if(i == msb)
  253. msb++;
  254. }
  255. }
  256. }
  257. void sub(bitstack const &_b)
  258. {
  259. /* Copy the operand in case we get substracted from ourselves */
  260. bitstack b(_b);
  261. uint64_t x = 0;
  262. /* We cannot substract a larger number! */
  263. if(msb < b.msb)
  264. {
  265. init(0);
  266. return;
  267. }
  268. for(int i = 0; i <= msb; i++)
  269. {
  270. uint64_t tmp = (uint64_t)digits[i] - (uint64_t)b.digits[i] - x;
  271. digits[i] = tmp;
  272. if((uint64_t)digits[i] == tmp)
  273. x = 0;
  274. else
  275. {
  276. x = 1;
  277. if(i == msb)
  278. {
  279. /* Error: carry into MSB! */
  280. init(0);
  281. return;
  282. }
  283. }
  284. }
  285. while(msb > 0 && digits[msb] == 0) msb--;
  286. }
  287. void mul(uint32_t x)
  288. {
  289. bitstack b(*this);
  290. init(0);
  291. while(x)
  292. {
  293. if(x & 1)
  294. add(b);
  295. x /= 2;
  296. b.add(b);
  297. }
  298. }
  299. uint32_t div(uint32_t x)
  300. {
  301. bitstack b(*this);
  302. for(int i = msb; i >= 0; i--)
  303. {
  304. uint64_t tmp = b.digits[i] + (((uint64_t)b.digits[i + 1]) << 32);
  305. uint32_t res = tmp / x;
  306. uint32_t rem = tmp % x;
  307. digits[i]= res;
  308. b.digits[i + 1] = 0;
  309. b.digits[i] = rem;
  310. }
  311. while(msb > 0 && digits[msb] == 0) msb--;
  312. return b.digits[0];
  313. }
  314. int msb;
  315. uint32_t *digits;
  316. char *str;
  317. };
  318. /*
  319. * Point handling
  320. */
  321. static unsigned int det_rand(unsigned int mod)
  322. {
  323. static unsigned long next = 1;
  324. next = next * 1103515245 + 12345;
  325. return ((unsigned)(next / 65536) % 32768) % mod;
  326. }
  327. static inline int range2int(float val, int range)
  328. {
  329. int ret = (int)(val * ((float)range - 0.0001));
  330. return ret < 0 ? 0 : ret > range - 1 ? range - 1 : ret;
  331. }
  332. static inline float int2midrange(int val, int range)
  333. {
  334. return (float)(1 + 2 * val) / (float)(2 * range);
  335. }
  336. static inline float int2fullrange(int val, int range)
  337. {
  338. return range > 1 ? (float)val / (float)(range - 1) : 0.0;
  339. }
  340. static inline void set_point(int index, float x, float y, float r,
  341. float g, float b, float s)
  342. {
  343. int dx = (index / POINTS_PER_CELL) % dw;
  344. int dy = (index / POINTS_PER_CELL) / dw;
  345. float fx = (x - dx * RANGE_X) / RANGE_X;
  346. float fy = (y - dy * RANGE_Y) / RANGE_Y;
  347. int is = range2int(s, RANGE_S);
  348. int ix = range2int(fx, RANGE_X);
  349. int iy = range2int(fy, RANGE_Y);
  350. int ir = range2int(r, RANGE_R);
  351. int ig = range2int(g, RANGE_G);
  352. int ib = range2int(b, RANGE_B);
  353. points[index] = is + RANGE_S * (iy + RANGE_Y * (ix + RANGE_X *
  354. (ib + RANGE_B * (ig + (RANGE_R * ir)))));
  355. }
  356. static inline void get_point(int index, float *x, float *y, float *r,
  357. float *g, float *b, float *s)
  358. {
  359. uint32_t pt = points[index];
  360. unsigned int dx = (index / POINTS_PER_CELL) % dw;
  361. unsigned int dy = (index / POINTS_PER_CELL) / dw;
  362. *s = int2fullrange(pt % RANGE_S, RANGE_S); pt /= RANGE_S;
  363. float fy = int2midrange(pt % RANGE_Y, RANGE_Y); pt /= RANGE_Y;
  364. float fx = int2midrange(pt % RANGE_X, RANGE_X); pt /= RANGE_X;
  365. *x = (fx + dx) * RANGE_X /*+ 0.5 * (index & 1)*/;
  366. *y = (fy + dy) * RANGE_Y /*+ 0.5 * (index & 1)*/;
  367. *b = int2midrange(pt % RANGE_R, RANGE_R); pt /= RANGE_R;
  368. *g = int2midrange(pt % RANGE_G, RANGE_G); pt /= RANGE_G;
  369. *r = int2midrange(pt % RANGE_B, RANGE_B); pt /= RANGE_B;
  370. }
  371. static inline float clip(float x, int modulo)
  372. {
  373. float mul = (float)modulo + 0.9999;
  374. int round = (int)(x * mul);
  375. return (float)round / (float)modulo;
  376. }
  377. static void add_point(float x, float y, float r, float g, float b, float s)
  378. {
  379. set_point(npoints, x, y, r, g, b, s);
  380. npoints++;
  381. }
  382. #if 0
  383. static void add_random_point()
  384. {
  385. points[npoints] = det_rand(RANGE_SYXRGB);
  386. npoints++;
  387. }
  388. #endif
  389. #define NB_OPS 20
  390. static uint8_t rand_op(void)
  391. {
  392. uint8_t x = det_rand(NB_OPS);
  393. /* Randomly ignore statistically less efficient ops */
  394. if(x == 0)
  395. return rand_op();
  396. if(x == 1 && (RANGE_S == 1 || det_rand(2)))
  397. return rand_op();
  398. if(x <= 5 && det_rand(2))
  399. return rand_op();
  400. //if((x < 10 || x > 15) && !det_rand(4)) /* Favour colour changes */
  401. // return rand_op();
  402. return x;
  403. }
  404. static uint32_t apply_op(uint8_t op, uint32_t val)
  405. {
  406. uint32_t rem, ext;
  407. switch(op)
  408. {
  409. case 0: /* Flip strength value */
  410. case 1:
  411. /* Statistics show that this helps often, but does not reduce
  412. * the error significantly. */
  413. return val ^ 1;
  414. case 2: /* Move up; if impossible, down */
  415. rem = val % RANGE_S;
  416. ext = (val / RANGE_S) % RANGE_Y;
  417. ext = ext > 0 ? ext - 1 : ext + 1;
  418. return (val / RANGE_SY * RANGE_Y + ext) * RANGE_S + rem;
  419. case 3: /* Move down; if impossible, up */
  420. rem = val % RANGE_S;
  421. ext = (val / RANGE_S) % RANGE_Y;
  422. ext = ext < RANGE_Y - 1 ? ext + 1 : ext - 1;
  423. return (val / RANGE_SY * RANGE_Y + ext) * RANGE_S + rem;
  424. case 4: /* Move left; if impossible, right */
  425. rem = val % RANGE_SY;
  426. ext = (val / RANGE_SY) % RANGE_X;
  427. ext = ext > 0 ? ext - 1 : ext + 1;
  428. return (val / RANGE_SYX * RANGE_X + ext) * RANGE_SY + rem;
  429. case 5: /* Move left; if impossible, right */
  430. rem = val % RANGE_SY;
  431. ext = (val / RANGE_SY) % RANGE_X;
  432. ext = ext < RANGE_X - 1 ? ext + 1 : ext - 1;
  433. return (val / RANGE_SYX * RANGE_X + ext) * RANGE_SY + rem;
  434. case 6: /* Corner 1 */
  435. return apply_op(2, apply_op(4, val));
  436. case 7: /* Corner 2 */
  437. return apply_op(2, apply_op(5, val));
  438. case 8: /* Corner 3 */
  439. return apply_op(3, apply_op(5, val));
  440. case 9: /* Corner 4 */
  441. return apply_op(3, apply_op(4, val));
  442. case 16: /* Double up */
  443. return apply_op(2, apply_op(2, val));
  444. case 17: /* Double down */
  445. return apply_op(3, apply_op(3, val));
  446. case 18: /* Double left */
  447. return apply_op(4, apply_op(4, val));
  448. case 19: /* Double right */
  449. return apply_op(5, apply_op(5, val));
  450. case 10: /* R-- (or R++) */
  451. rem = val % RANGE_SYX;
  452. ext = (val / RANGE_SYX) % RANGE_R;
  453. ext = ext > 0 ? ext - 1 : ext + 1;
  454. return (val / RANGE_SYXR * RANGE_R + ext) * RANGE_SYX + rem;
  455. case 11: /* R++ (or R--) */
  456. rem = val % RANGE_SYX;
  457. ext = (val / RANGE_SYX) % RANGE_R;
  458. ext = ext < RANGE_R - 1 ? ext + 1 : ext - 1;
  459. return (val / RANGE_SYXR * RANGE_R + ext) * RANGE_SYX + rem;
  460. case 12: /* G-- (or G++) */
  461. rem = val % RANGE_SYXR;
  462. ext = (val / RANGE_SYXR) % RANGE_G;
  463. ext = ext > 0 ? ext - 1 : ext + 1;
  464. return (val / RANGE_SYXRG * RANGE_G + ext) * RANGE_SYXR + rem;
  465. case 13: /* G++ (or G--) */
  466. rem = val % RANGE_SYXR;
  467. ext = (val / RANGE_SYXR) % RANGE_G;
  468. ext = ext < RANGE_G - 1 ? ext + 1 : ext - 1;
  469. return (val / RANGE_SYXRG * RANGE_G + ext) * RANGE_SYXR + rem;
  470. case 14: /* B-- (or B++) */
  471. rem = val % RANGE_SYXRG;
  472. ext = (val / RANGE_SYXRG) % RANGE_B;
  473. ext = ext > 0 ? ext - 1 : ext + 1;
  474. return ext * RANGE_SYXRG + rem;
  475. case 15: /* B++ (or B--) */
  476. rem = val % RANGE_SYXRG;
  477. ext = (val / RANGE_SYXRG) % RANGE_B;
  478. ext = ext < RANGE_B - 1 ? ext + 1 : ext - 1;
  479. return ext * RANGE_SYXRG + rem;
  480. #if 0
  481. case 15: /* Brightness-- */
  482. return apply_op(9, apply_op(11, apply_op(13, val)));
  483. case 16: /* Brightness++ */
  484. return apply_op(10, apply_op(12, apply_op(14, val)));
  485. case 17: /* RG-- */
  486. return apply_op(9, apply_op(11, val));
  487. case 18: /* RG++ */
  488. return apply_op(10, apply_op(12, val));
  489. case 19: /* GB-- */
  490. return apply_op(11, apply_op(13, val));
  491. case 20: /* GB++ */
  492. return apply_op(12, apply_op(14, val));
  493. case 21: /* RB-- */
  494. return apply_op(9, apply_op(13, val));
  495. case 22: /* RB++ */
  496. return apply_op(10, apply_op(14, val));
  497. #endif
  498. default:
  499. return val;
  500. }
  501. }
  502. static void render(pipi_image_t *dst, int rx, int ry, int rw, int rh)
  503. {
  504. int lookup[dw * RANGE_X * 2 * dh * RANGE_Y * 2];
  505. pipi_pixels_t *p = pipi_get_pixels(dst, PIPI_PIXELS_RGBA_F32);
  506. float *data = (float *)p->pixels;
  507. int x, y;
  508. memset(lookup, 0, sizeof(lookup));
  509. dt.clear();
  510. for(int i = 0; i < npoints; i++)
  511. {
  512. float fx, fy, fr, fg, fb, fs;
  513. get_point(i, &fx, &fy, &fr, &fg, &fb, &fs);
  514. dt.insert(K::Point_2(fx, fy));
  515. /* Keep link to point */
  516. lookup[(int)(fx * 2) + dw * RANGE_X * 2 * (int)(fy * 2)] = i;
  517. }
  518. /* Add fake points to close the triangulation */
  519. dt.insert(K::Point_2(-p->w, -p->h));
  520. dt.insert(K::Point_2(2 * p->w, -p->h));
  521. dt.insert(K::Point_2(-p->w, 2 * p->h));
  522. dt.insert(K::Point_2(2 * p->w, 2 * p->h));
  523. for(y = ry; y < ry + rh; y++)
  524. {
  525. for(x = rx; x < rx + rw; x++)
  526. {
  527. K::Point_2 m(x, y);
  528. Point_coordinate_vector coords;
  529. CGAL::Triple<
  530. std::back_insert_iterator<Point_coordinate_vector>,
  531. K::FT, bool> result =
  532. CGAL::natural_neighbor_coordinates_2(dt, m,
  533. std::back_inserter(coords));
  534. float r = 0.0f, g = 0.0f, b = 0.0f, norm = 0.000000000000001f;
  535. Point_coordinate_vector::iterator it;
  536. for(it = coords.begin(); it != coords.end(); ++it)
  537. {
  538. float fx, fy, fr, fg, fb, fs;
  539. fx = (*it).first.x();
  540. fy = (*it).first.y();
  541. if(fx < 0 || fy < 0 || fx > p->w - 1 || fy > p->h - 1)
  542. continue;
  543. int index = lookup[(int)(fx * 2)
  544. + dw * RANGE_X * 2 * (int)(fy * 2)];
  545. get_point(index, &fx, &fy, &fr, &fg, &fb, &fs);
  546. //float k = pow((*it).second * (1.0 + fs), 1.2);
  547. float k = (*it).second * (1.00f + fs);
  548. //float k = (*it).second * (0.60f + fs);
  549. //float k = pow((*it).second, (1.0f + fs));
  550. r += k * fr;
  551. g += k * fg;
  552. b += k * fb;
  553. norm += k;
  554. }
  555. data[4 * (x + y * p->w) + 0] = r / norm;
  556. data[4 * (x + y * p->w) + 1] = g / norm;
  557. data[4 * (x + y * p->w) + 2] = b / norm;
  558. data[4 * (x + y * p->w) + 3] = 0.0;
  559. }
  560. }
  561. pipi_release_pixels(dst, p);
  562. }
  563. static void analyse(pipi_image_t *src)
  564. {
  565. pipi_pixels_t *p = pipi_get_pixels(src, PIPI_PIXELS_RGBA_F32);
  566. float *data = (float *)p->pixels;
  567. for(unsigned int dy = 0; dy < dh; dy++)
  568. for(unsigned int dx = 0; dx < dw; dx++)
  569. {
  570. float min = 1.1f, max = -0.1f;
  571. float total = 0.0;
  572. int xmin = 0, xmax = 0, ymin = 0, ymax = 0;
  573. int npixels = 0;
  574. for(unsigned int iy = RANGE_Y * dy; iy < RANGE_Y * (dy + 1); iy++)
  575. for(unsigned int ix = RANGE_X * dx; ix < RANGE_X * (dx + 1); ix++)
  576. {
  577. float lum = 0.0f;
  578. lum += data[4 * (ix + iy * p->w) + 0];
  579. lum += data[4 * (ix + iy * p->w) + 1];
  580. lum += data[4 * (ix + iy * p->w) + 2];
  581. if(lum < min)
  582. {
  583. min = lum;
  584. xmin = ix;
  585. ymin = iy;
  586. }
  587. if(lum > max)
  588. {
  589. max = lum;
  590. xmax = ix;
  591. ymax = iy;
  592. }
  593. total += lum;
  594. npixels++;
  595. }
  596. total /= npixels;
  597. float wmin, wmax;
  598. if(total < min + (max - min) / 4)
  599. wmin = 1.0, wmax = 0.0;
  600. else if(total < min + (max - min) / 4 * 3)
  601. wmin = 0.0, wmax = 0.0;
  602. else
  603. wmin = 0.0, wmax = 1.0;
  604. #if 0
  605. add_random_point();
  606. add_random_point();
  607. #else
  608. #if POINTS_PER_CELL == 1
  609. if(total < min + (max - min) / 2)
  610. {
  611. #endif
  612. add_point(xmin, ymin,
  613. data[4 * (xmin + ymin * p->w) + 0],
  614. data[4 * (xmin + ymin * p->w) + 1],
  615. data[4 * (xmin + ymin * p->w) + 2],
  616. wmin);
  617. #if POINTS_PER_CELL == 1
  618. }
  619. else
  620. {
  621. #endif
  622. add_point(xmax, ymax,
  623. data[4 * (xmax + ymax * p->w) + 0],
  624. data[4 * (xmax + ymax * p->w) + 1],
  625. data[4 * (xmax + ymax * p->w) + 2],
  626. wmax);
  627. #if POINTS_PER_CELL == 1
  628. }
  629. #endif
  630. #endif
  631. }
  632. }
  633. #define MOREINFO "Try `%s --help' for more information.\n"
  634. int main(int argc, char *argv[])
  635. {
  636. int opstats[2 * NB_OPS];
  637. bitstack b;
  638. char const *srcname = NULL, *dstname = NULL;
  639. pipi_image_t *src, *tmp, *dst;
  640. double error = 1.0;
  641. int width, height, ret = 0;
  642. /* Parse command-line options */
  643. for(;;)
  644. {
  645. int option_index = 0;
  646. static struct myoption long_options[] =
  647. {
  648. { "output", 1, NULL, 'o' },
  649. { "quality", 1, NULL, 'q' },
  650. { "debug", 0, NULL, 'd' },
  651. { "help", 0, NULL, 'h' },
  652. { NULL, 0, NULL, 0 },
  653. };
  654. int c = mygetopt(argc, argv, "o:q:dh", long_options, &option_index);
  655. if(c == -1)
  656. break;
  657. switch(c)
  658. {
  659. case 'o':
  660. dstname = myoptarg;
  661. break;
  662. case 'q':
  663. ITERATIONS_PER_POINT = 10 * atoi(myoptarg);
  664. if(ITERATIONS_PER_POINT < 0)
  665. ITERATIONS_PER_POINT = 0;
  666. else if(ITERATIONS_PER_POINT > 10)
  667. ITERATIONS_PER_POINT = 10;
  668. break;
  669. case 'd':
  670. DEBUG = true;
  671. break;
  672. case 'h':
  673. printf("Usage: img2twit [OPTIONS] SOURCE\n");
  674. printf(" img2twit [OPTIONS] -o DESTINATION\n");
  675. printf("Encode SOURCE image to stdout or decode stdin to DESTINATION.\n");
  676. printf("\n");
  677. printf("Mandatory arguments to long options are mandatory for short options too.\n");
  678. printf(" -o, --output <filename> output resulting image to filename\n");
  679. printf(" -q, --quality <rate> set image quality (0 - 10) (default 5)\n");
  680. printf(" -d, --debug print debug information\n");
  681. printf(" -h, --help display this help and exit\n");
  682. printf("\n");
  683. printf("Written by Sam Hocevar. Report bugs to <sam@hocevar.net>.\n");
  684. return EXIT_SUCCESS;
  685. default:
  686. fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
  687. printf(MOREINFO, argv[0]);
  688. return EXIT_FAILURE;
  689. }
  690. }
  691. if(myoptind == argc && !dstname)
  692. {
  693. fprintf(stderr, "%s: too few arguments\n", argv[0]);
  694. printf(MOREINFO, argv[0]);
  695. return EXIT_FAILURE;
  696. }
  697. if((myoptind == argc - 1 && dstname) || myoptind < argc - 1)
  698. {
  699. fprintf(stderr, "%s: too many arguments\n", argv[0]);
  700. printf(MOREINFO, argv[0]);
  701. return EXIT_FAILURE;
  702. }
  703. if(myoptind == argc - 1)
  704. srcname = argv[myoptind];
  705. pipi_set_gamma(1.0);
  706. /* Precompute bit allocation */
  707. NUM_CHARACTERS = count_unichars();
  708. TOTAL_BITS = MAX_MSG_LEN * logf(NUM_CHARACTERS) / logf(2);
  709. HEADER_BITS = logf(MAX_W * MAX_H) / logf(2);
  710. DATA_BITS = TOTAL_BITS - HEADER_BITS;
  711. #if POINTS_PER_CELL == 1
  712. CELL_BITS = logf(RANGE_SYXRGB) / logf(2);
  713. #else
  714. // TODO: implement the following shit
  715. //float coord_bits = logf((RANGE_Y * RANGE_X) * (RANGE_Y * RANGE_X + 1) / 2);
  716. //float other_bits = logf(RANGE_R * RANGE_G * RANGE_B * RANGE_S);
  717. //CELL_BITS = (coord_bits + 2 * other_bits) / logf(2);
  718. CELL_BITS = 2 * logf(RANGE_SYXRGB) / logf(2);
  719. #endif
  720. TOTAL_CELLS = (int)(DATA_BITS / CELL_BITS);
  721. MAX_ITERATIONS = ITERATIONS_PER_POINT * POINTS_PER_CELL * TOTAL_CELLS;
  722. if(dstname)
  723. {
  724. /* Decoding mode: read UTF-8 text from stdin, find each
  725. * character's index in our character list, and push it to our
  726. * wonderful custom bitstream. */
  727. uint32_t data[MAX_MSG_LEN];
  728. for(int i = 0; i < MAX_MSG_LEN; i++)
  729. data[i] = uni2index(fread_utf8(stdin));
  730. for(int i = MAX_MSG_LEN; i--; )
  731. b.push(data[i], NUM_CHARACTERS);
  732. /* Read width and height from bitstream */
  733. src = NULL;
  734. width = b.pop(MAX_W);
  735. height = b.pop(MAX_H);
  736. }
  737. else
  738. {
  739. /* Argument given: open image for encoding */
  740. src = pipi_load(srcname);
  741. if(!src)
  742. {
  743. fprintf(stderr, "Error loading %s\n", srcname);
  744. return EXIT_FAILURE;
  745. }
  746. width = pipi_get_image_width(src);
  747. height = pipi_get_image_height(src);
  748. }
  749. /* Compute best w/h ratio */
  750. dw = 1; dh = TOTAL_CELLS;
  751. for(unsigned int i = 1; i <= TOTAL_CELLS; i++)
  752. {
  753. int j = TOTAL_CELLS / i;
  754. float r = (float)width / (float)height;
  755. float ir = (float)i / (float)j;
  756. float dwr = (float)dw / (float)dh;
  757. if(fabs(logf(r / ir)) < fabs(logf(r / dwr)))
  758. {
  759. dw = i;
  760. dh = TOTAL_CELLS / dw;
  761. }
  762. }
  763. while((dh + 1) * dw <= TOTAL_CELLS) dh++;
  764. while(dw * (dh + 1) <= TOTAL_CELLS) dw++;
  765. /* Print debug information */
  766. if(DEBUG)
  767. {
  768. fprintf(stderr, "Maximum message size: %i\n", MAX_MSG_LEN);
  769. fprintf(stderr, "Available characters: %i\n", NUM_CHARACTERS);
  770. fprintf(stderr, "Available bits: %f\n", TOTAL_BITS);
  771. fprintf(stderr, "Maximum image resolution: %ix%i\n", MAX_W, MAX_H);
  772. fprintf(stderr, "Image resolution: %ix%i\n", width, height);
  773. fprintf(stderr, "Header bits: %f\n", HEADER_BITS);
  774. fprintf(stderr, "Bits available for data: %f\n", DATA_BITS);
  775. fprintf(stderr, "Cell bits: %f\n", CELL_BITS);
  776. fprintf(stderr, "Available cells: %i\n", TOTAL_CELLS);
  777. fprintf(stderr, "Wasted bits: %f\n",
  778. DATA_BITS - CELL_BITS * TOTAL_CELLS);
  779. fprintf(stderr, "Chosen image ratio: %i:%i (wasting %i point cells)\n",
  780. dw, dh, TOTAL_CELLS - dw * dh);
  781. fprintf(stderr, "Total wasted bits: %f\n",
  782. DATA_BITS - CELL_BITS * dw * dh);
  783. }
  784. if(srcname)
  785. {
  786. /* Resize and filter image to better state */
  787. tmp = pipi_resize(src, dw * RANGE_X, dh * RANGE_Y);
  788. pipi_free(src);
  789. src = pipi_median_ext(tmp, 1, 1);
  790. pipi_free(tmp);
  791. pipi_save(src, "lol.bmp");
  792. /* Analyse image */
  793. analyse(src);
  794. /* Render what we just computed */
  795. tmp = pipi_new(dw * RANGE_X, dh * RANGE_Y);
  796. render(tmp, 0, 0, dw * RANGE_X, dh * RANGE_Y);
  797. pipi_save(tmp, "lol2.bmp");
  798. error = pipi_measure_rmsd(src, tmp);
  799. if(DEBUG)
  800. fprintf(stderr, "Initial distance: %2.10g\n", error);
  801. memset(opstats, 0, sizeof(opstats));
  802. for(int iter = 0, stuck = 0, failures = 0, success = 0;
  803. iter < MAX_ITERATIONS /* && stuck < 5 && */;
  804. iter++)
  805. {
  806. if(failures > 500)
  807. {
  808. stuck++;
  809. failures = 0;
  810. }
  811. if(!DEBUG && !(iter % 16))
  812. fprintf(stderr, "\rEncoding... %i%%",
  813. iter * 100 / MAX_ITERATIONS);
  814. pipi_image_t *scrap = pipi_copy(tmp);
  815. /* Choose a point at random */
  816. int pt = det_rand(npoints);
  817. uint32_t oldval = points[pt];
  818. /* Compute the affected image zone */
  819. float fx, fy, fr, fg, fb, fs;
  820. get_point(pt, &fx, &fy, &fr, &fg, &fb, &fs);
  821. int zonex = (int)fx / RANGE_X - 1;
  822. int zoney = (int)fy / RANGE_Y - 1;
  823. int zonew = 3;
  824. int zoneh = 3;
  825. if(zonex < 0) { zonex = 0; zonew--; }
  826. if(zoney < 0) { zoney = 0; zoneh--; }
  827. if(zonex + zonew >= (int)dw) { zonew--; }
  828. if(zoney + zoneh >= (int)dh) { zoneh--; }
  829. /* Choose random operations and measure their effect */
  830. uint8_t op1 = rand_op();
  831. //uint8_t op2 = rand_op();
  832. uint32_t candidates[3];
  833. double besterr = error + 1.0;
  834. int bestop = -1;
  835. candidates[0] = apply_op(op1, oldval);
  836. //candidates[1] = apply_op(op2, oldval);
  837. //candidates[2] = apply_op(op1, apply_op(op2, oldval));
  838. for(int i = 0; i < 1; i++)
  839. //for(int i = 0; i < 3; i++)
  840. {
  841. if(oldval == candidates[i])
  842. continue;
  843. points[pt] = candidates[i];
  844. render(scrap, zonex * RANGE_X, zoney * RANGE_Y,
  845. zonew * RANGE_X, zoneh * RANGE_Y);
  846. double newerr = pipi_measure_rmsd(src, scrap);
  847. if(newerr < besterr)
  848. {
  849. besterr = newerr;
  850. bestop = i;
  851. }
  852. }
  853. opstats[op1 * 2]++;
  854. //opstats[op2 * 2]++;
  855. if(besterr < error)
  856. {
  857. points[pt] = candidates[bestop];
  858. /* Redraw image if the last check wasn't the best one */
  859. if(bestop != 2)
  860. render(scrap, zonex * RANGE_X, zoney * RANGE_Y,
  861. zonew * RANGE_X, zoneh * RANGE_Y);
  862. pipi_free(tmp);
  863. tmp = scrap;
  864. if(DEBUG)
  865. fprintf(stderr, "%08i -.%08i %2.010g after op%i(%i)\n",
  866. iter, (int)((error - besterr) * 100000000), error,
  867. op1, pt);
  868. error = besterr;
  869. opstats[op1 * 2 + 1]++;
  870. //opstats[op2 * 2 + 1]++;
  871. failures = 0;
  872. success++;
  873. /* Save image! */
  874. //char buf[128];
  875. //sprintf(buf, "twit%08i.bmp", success);
  876. //if((success % 10) == 0)
  877. // pipi_save(tmp, buf);
  878. }
  879. else
  880. {
  881. pipi_free(scrap);
  882. points[pt] = oldval;
  883. failures++;
  884. }
  885. }
  886. if(DEBUG)
  887. {
  888. for(int j = 0; j < 2; j++)
  889. {
  890. fprintf(stderr, "operation: ");
  891. for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
  892. fprintf(stderr, "%4i ", i);
  893. fprintf(stderr, "\nattempts: ");
  894. for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
  895. fprintf(stderr, "%4i ", opstats[i * 2]);
  896. fprintf(stderr, "\nsuccesses: ");
  897. for(int i = NB_OPS / 2 * j; i < NB_OPS / 2 * (j + 1); i++)
  898. fprintf(stderr, "%4i ", opstats[i * 2 + 1]);
  899. fprintf(stderr, "\n");
  900. }
  901. fprintf(stderr, "Distance: %2.10g\n", error);
  902. }
  903. else
  904. fprintf(stderr, "\r \r");
  905. #if 0
  906. dst = pipi_resize(tmp, width, height);
  907. pipi_free(tmp);
  908. /* Save image and bail out */
  909. pipi_save(dst, "lol.bmp");
  910. pipi_free(dst);
  911. #endif
  912. /* Push our points to the bitstream */
  913. for(int i = 0; i < npoints; i++)
  914. b.push(points[i], RANGE_SYXRGB);
  915. b.push(height, MAX_H);
  916. b.push(width, MAX_W);
  917. /* Pop Unicode characters from the bitstream and print them */
  918. for(int i = 0; i < MAX_MSG_LEN; i++)
  919. fwrite_utf8(stdout, index2uni(b.pop(NUM_CHARACTERS)));
  920. fprintf(stdout, "\n");
  921. }
  922. else
  923. {
  924. /* Pop points from the bitstream */
  925. for(int i = dw * dh; i--; )
  926. {
  927. #if POINTS_PER_CELL == 2
  928. points[i * 2 + 1] = b.pop(RANGE_SYXRGB);
  929. points[i * 2] = b.pop(RANGE_SYXRGB);
  930. #else
  931. points[i] = b.pop(RANGE_SYXRGB);
  932. #endif
  933. }
  934. npoints = dw * dh * POINTS_PER_CELL;
  935. /* Render these points to a new image */
  936. tmp = pipi_new(dw * RANGE_X, dh * RANGE_Y);
  937. render(tmp, 0, 0, dw * RANGE_X, dh * RANGE_Y);
  938. /* TODO: render directly to the final image; scaling sucks */
  939. dst = pipi_resize(tmp, width, height);
  940. pipi_free(tmp);
  941. /* Save image and bail out */
  942. pipi_save(dst, dstname);
  943. pipi_free(dst);
  944. }
  945. return ret;
  946. }