main.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. /*
  2. * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR v1.6 (2019-04-08) - standalone console program
  3. * --------------------------------------------------------------------------------------------
  4. * A utility by Viktor Chlumsky, (c) 2014 - 2019
  5. *
  6. */
  7. #ifdef MSDFGEN_STANDALONE
  8. #define _USE_MATH_DEFINES
  9. #include <cstdio>
  10. #include <cmath>
  11. #include <cstring>
  12. #include "msdfgen.h"
  13. #include "msdfgen-ext.h"
  14. #ifdef _WIN32
  15. #pragma warning(disable:4996)
  16. #endif
  17. #define LARGE_VALUE 1e240
  18. using namespace msdfgen;
  19. enum Format {
  20. AUTO,
  21. PNG,
  22. BMP,
  23. TEXT,
  24. TEXT_FLOAT,
  25. BINARY,
  26. BINARY_FLOAT,
  27. BINART_FLOAT_BE
  28. };
  29. static char toupper(char c) {
  30. return c >= 'a' && c <= 'z' ? c-'a'+'A' : c;
  31. }
  32. static bool parseUnsigned(unsigned &value, const char *arg) {
  33. static char c;
  34. return sscanf(arg, "%u%c", &value, &c) == 1;
  35. }
  36. static bool parseUnsignedLL(unsigned long long &value, const char *arg) {
  37. static char c;
  38. return sscanf(arg, "%llu%c", &value, &c) == 1;
  39. }
  40. static bool parseUnsignedHex(unsigned &value, const char *arg) {
  41. static char c;
  42. return sscanf(arg, "%x%c", &value, &c) == 1;
  43. }
  44. static bool parseDouble(double &value, const char *arg) {
  45. static char c;
  46. return sscanf(arg, "%lf%c", &value, &c) == 1;
  47. }
  48. static bool parseUnicode(int &unicode, const char *arg) {
  49. unsigned uuc;
  50. if (parseUnsigned(uuc, arg)) {
  51. unicode = uuc;
  52. return true;
  53. }
  54. if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X') && parseUnsignedHex(uuc, arg+2)) {
  55. unicode = uuc;
  56. return true;
  57. }
  58. if (arg[0] == '\'' && arg[1] && arg[2] == '\'' && !arg[3]) {
  59. unicode = arg[1];
  60. return true;
  61. }
  62. return false;
  63. }
  64. static bool parseAngle(double &value, const char *arg) {
  65. char c1, c2;
  66. int result = sscanf(arg, "%lf%c%c", &value, &c1, &c2);
  67. if (result == 1)
  68. return true;
  69. if (result == 2 && (c1 == 'd' || c1 == 'D')) {
  70. value *= M_PI/180;
  71. return true;
  72. }
  73. return false;
  74. }
  75. static void parseColoring(Shape &shape, const char *edgeAssignment) {
  76. unsigned c = 0, e = 0;
  77. if (shape.contours.size() < c) return;
  78. Contour *contour = &shape.contours[c];
  79. bool change = false;
  80. bool clear = true;
  81. for (const char *in = edgeAssignment; *in; ++in) {
  82. switch (*in) {
  83. case ',':
  84. if (change)
  85. ++e;
  86. if (clear)
  87. while (e < contour->edges.size()) {
  88. contour->edges[e]->color = WHITE;
  89. ++e;
  90. }
  91. ++c, e = 0;
  92. if (shape.contours.size() <= c) return;
  93. contour = &shape.contours[c];
  94. change = false;
  95. clear = true;
  96. break;
  97. case '?':
  98. clear = false;
  99. break;
  100. case 'C': case 'M': case 'W': case 'Y': case 'c': case 'm': case 'w': case 'y':
  101. if (change) {
  102. ++e;
  103. change = false;
  104. }
  105. if (e < contour->edges.size()) {
  106. contour->edges[e]->color = EdgeColor(
  107. (*in == 'C' || *in == 'c')*CYAN|
  108. (*in == 'M' || *in == 'm')*MAGENTA|
  109. (*in == 'Y' || *in == 'y')*YELLOW|
  110. (*in == 'W' || *in == 'w')*WHITE);
  111. change = true;
  112. }
  113. break;
  114. }
  115. }
  116. }
  117. static void invertColor(Bitmap<float> &bitmap) {
  118. for (int y = 0; y < bitmap.height(); ++y)
  119. for (int x = 0; x < bitmap.width(); ++x)
  120. bitmap(x, y) = 1.f-bitmap(x, y);
  121. }
  122. static void invertColor(Bitmap<FloatRGB> &bitmap) {
  123. for (int y = 0; y < bitmap.height(); ++y)
  124. for (int x = 0; x < bitmap.width(); ++x) {
  125. bitmap(x, y).r = 1.f-bitmap(x, y).r;
  126. bitmap(x, y).g = 1.f-bitmap(x, y).g;
  127. bitmap(x, y).b = 1.f-bitmap(x, y).b;
  128. }
  129. }
  130. static bool writeTextBitmap(FILE *file, const float *values, int cols, int rows) {
  131. for (int row = 0; row < rows; ++row) {
  132. for (int col = 0; col < cols; ++col) {
  133. int v = clamp(int((*values++)*0x100), 0xff);
  134. fprintf(file, col ? " %02X" : "%02X", v);
  135. }
  136. fprintf(file, "\n");
  137. }
  138. return true;
  139. }
  140. static bool writeTextBitmapFloat(FILE *file, const float *values, int cols, int rows) {
  141. for (int row = 0; row < rows; ++row) {
  142. for (int col = 0; col < cols; ++col) {
  143. fprintf(file, col ? " %g" : "%g", *values++);
  144. }
  145. fprintf(file, "\n");
  146. }
  147. return true;
  148. }
  149. static bool writeBinBitmap(FILE *file, const float *values, int count) {
  150. for (int pos = 0; pos < count; ++pos) {
  151. unsigned char v = clamp(int((*values++)*0x100), 0xff);
  152. fwrite(&v, 1, 1, file);
  153. }
  154. return true;
  155. }
  156. #ifdef __BIG_ENDIAN__
  157. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  158. #else
  159. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  160. #endif
  161. {
  162. return fwrite(values, sizeof(float), count, file) == count;
  163. }
  164. #ifdef __BIG_ENDIAN__
  165. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  166. #else
  167. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  168. #endif
  169. {
  170. for (int pos = 0; pos < count; ++pos) {
  171. const unsigned char *b = reinterpret_cast<const unsigned char *>(values++);
  172. for (int i = sizeof(float)-1; i >= 0; --i)
  173. fwrite(b+i, 1, 1, file);
  174. }
  175. return true;
  176. }
  177. static bool cmpExtension(const char *path, const char *ext) {
  178. for (const char *a = path+strlen(path)-1, *b = ext+strlen(ext)-1; b >= ext; --a, --b)
  179. if (a < path || toupper(*a) != toupper(*b))
  180. return false;
  181. return true;
  182. }
  183. template <typename T>
  184. static const char * writeOutput(const Bitmap<T> &bitmap, const char *filename, Format format) {
  185. if (filename) {
  186. if (format == AUTO) {
  187. if (cmpExtension(filename, ".png")) format = PNG;
  188. else if (cmpExtension(filename, ".bmp")) format = BMP;
  189. else if (cmpExtension(filename, ".txt")) format = TEXT;
  190. else if (cmpExtension(filename, ".bin")) format = BINARY;
  191. else
  192. return "Could not deduce format from output file name.";
  193. }
  194. switch (format) {
  195. case PNG: return savePng(bitmap, filename) ? NULL : "Failed to write output PNG image.";
  196. case BMP: return saveBmp(bitmap, filename) ? NULL : "Failed to write output BMP image.";
  197. case TEXT: case TEXT_FLOAT: {
  198. FILE *file = fopen(filename, "w");
  199. if (!file) return "Failed to write output text file.";
  200. if (format == TEXT)
  201. writeTextBitmap(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width(), bitmap.height());
  202. else if (format == TEXT_FLOAT)
  203. writeTextBitmapFloat(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width(), bitmap.height());
  204. fclose(file);
  205. return NULL;
  206. }
  207. case BINARY: case BINARY_FLOAT: case BINART_FLOAT_BE: {
  208. FILE *file = fopen(filename, "wb");
  209. if (!file) return "Failed to write output binary file.";
  210. if (format == BINARY)
  211. writeBinBitmap(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width()*bitmap.height());
  212. else if (format == BINARY_FLOAT)
  213. writeBinBitmapFloat(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width()*bitmap.height());
  214. else if (format == BINART_FLOAT_BE)
  215. writeBinBitmapFloatBE(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width()*bitmap.height());
  216. fclose(file);
  217. return NULL;
  218. }
  219. default:;
  220. }
  221. } else {
  222. if (format == AUTO || format == TEXT)
  223. writeTextBitmap(stdout, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width(), bitmap.height());
  224. else if (format == TEXT_FLOAT)
  225. writeTextBitmapFloat(stdout, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width(), bitmap.height());
  226. else
  227. return "Unsupported format for standard output.";
  228. }
  229. return NULL;
  230. }
  231. static const char *helpText =
  232. "\n"
  233. "Multi-channel signed distance field generator by Viktor Chlumsky v" MSDFGEN_VERSION "\n"
  234. "---------------------------------------------------------------------\n"
  235. " Usage: msdfgen"
  236. #ifdef _WIN32
  237. ".exe"
  238. #endif
  239. " <mode> <input specification> <options>\n"
  240. "\n"
  241. "MODES\n"
  242. " sdf - Generate conventional monochrome signed distance field.\n"
  243. " psdf - Generate monochrome signed pseudo-distance field.\n"
  244. " msdf - Generate multi-channel signed distance field. This is used by default if no mode is specified.\n"
  245. " metrics - Report shape metrics only.\n"
  246. "\n"
  247. "INPUT SPECIFICATION\n"
  248. " -defineshape <definition>\n"
  249. "\tDefines input shape using the ad-hoc text definition.\n"
  250. " -font <filename.ttf> <character code>\n"
  251. "\tLoads a single glyph from the specified font file. Format of character code is '?', 63 or 0x3F.\n"
  252. " -shapedesc <filename.txt>\n"
  253. "\tLoads text shape description from a file.\n"
  254. " -stdin\n"
  255. "\tReads text shape description from the standard input.\n"
  256. " -svg <filename.svg>\n"
  257. "\tLoads the last vector path found in the specified SVG file.\n"
  258. "\n"
  259. "OPTIONS\n"
  260. " -angle <angle>\n"
  261. "\tSpecifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees.\n"
  262. " -ascale <x scale> <y scale>\n"
  263. "\tSets the scale used to convert shape units to pixels asymmetrically.\n"
  264. " -autoframe\n"
  265. "\tAutomatically scales (unless specified) and translates the shape to fit.\n"
  266. " -edgecolors <sequence>\n"
  267. "\tOverrides automatic edge coloring with the specified color sequence.\n"
  268. " -errorcorrection <threshold>\n"
  269. "\tChanges the threshold used to detect and correct potential artifacts. 0 disables error correction.\n"
  270. " -exportshape <filename.txt>\n"
  271. "\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"
  272. " -fillrule <nonzero / evenodd / positive / negative>\n"
  273. "\tSets the fill rule for the scanline pass. Default is nonzero.\n"
  274. " -format <png / bmp / text / textfloat / bin / binfloat / binfloatbe>\n"
  275. "\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"
  276. " -guessorder\n"
  277. "\tAttempts to detect if shape contours have the wrong winding and generates the SDF with the right one.\n"
  278. " -help\n"
  279. "\tDisplays this help.\n"
  280. " -legacy\n"
  281. "\tUses the original (legacy) distance field algorithms.\n"
  282. " -nooverlap\n"
  283. "\tDisables resolution of overlapping contours.\n"
  284. " -noscanline\n"
  285. "\tDisables the scanline pass, which corrects the distance field's signs according to the selected fill rule.\n"
  286. " -o <filename>\n"
  287. "\tSets the output file name. The default value is \"output.png\".\n"
  288. " -printmetrics\n"
  289. "\tPrints relevant metrics of the shape to the standard output.\n"
  290. " -pxrange <range>\n"
  291. "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
  292. " -range <range>\n"
  293. "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
  294. " -reverseorder\n"
  295. "\tGenerates the distance field as if shape vertices were in reverse order.\n"
  296. " -scale <scale>\n"
  297. "\tSets the scale used to convert shape units to pixels.\n"
  298. " -seed <n>\n"
  299. "\tSets the random seed for edge coloring heuristic.\n"
  300. " -size <width> <height>\n"
  301. "\tSets the dimensions of the output image.\n"
  302. " -stdout\n"
  303. "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
  304. " -testrender <filename.png> <width> <height>\n"
  305. "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
  306. " -testrendermulti <filename.png> <width> <height>\n"
  307. "\tRenders an image preview without flattening the color channels.\n"
  308. " -translate <x> <y>\n"
  309. "\tSets the translation of the shape in shape units.\n"
  310. " -yflip\n"
  311. "\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
  312. "\n";
  313. int main(int argc, const char * const *argv) {
  314. #define ABORT(msg) { puts(msg); return 1; }
  315. // Parse command line arguments
  316. enum {
  317. NONE,
  318. SVG,
  319. FONT,
  320. DESCRIPTION_ARG,
  321. DESCRIPTION_STDIN,
  322. DESCRIPTION_FILE
  323. } inputType = NONE;
  324. enum {
  325. SINGLE,
  326. PSEUDO,
  327. MULTI,
  328. METRICS
  329. } mode = MULTI;
  330. bool legacyMode = false;
  331. bool overlapSupport = true;
  332. bool scanlinePass = true;
  333. FillRule fillRule = FILL_NONZERO;
  334. Format format = AUTO;
  335. const char *input = NULL;
  336. const char *output = "output.png";
  337. const char *shapeExport = NULL;
  338. const char *testRender = NULL;
  339. const char *testRenderMulti = NULL;
  340. bool outputSpecified = false;
  341. int unicode = 0;
  342. int svgPathIndex = 0;
  343. int width = 64, height = 64;
  344. int testWidth = 0, testHeight = 0;
  345. int testWidthM = 0, testHeightM = 0;
  346. bool autoFrame = false;
  347. enum {
  348. RANGE_UNIT,
  349. RANGE_PX
  350. } rangeMode = RANGE_PX;
  351. double range = 1;
  352. double pxRange = 2;
  353. Vector2 translate;
  354. Vector2 scale = 1;
  355. bool scaleSpecified = false;
  356. double angleThreshold = 3;
  357. double edgeThreshold = 1.001;
  358. bool defEdgeAssignment = true;
  359. const char *edgeAssignment = NULL;
  360. bool yFlip = false;
  361. bool printMetrics = false;
  362. bool skipColoring = false;
  363. enum {
  364. KEEP,
  365. REVERSE,
  366. GUESS
  367. } orientation = KEEP;
  368. unsigned long long coloringSeed = 0;
  369. int argPos = 1;
  370. bool suggestHelp = false;
  371. while (argPos < argc) {
  372. const char *arg = argv[argPos];
  373. #define ARG_CASE(s, p) if (!strcmp(arg, s) && argPos+(p) < argc)
  374. #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
  375. #define SET_FORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
  376. ARG_MODE("sdf", SINGLE)
  377. ARG_MODE("psdf", PSEUDO)
  378. ARG_MODE("msdf", MULTI)
  379. ARG_MODE("metrics", METRICS)
  380. ARG_CASE("-svg", 1) {
  381. inputType = SVG;
  382. input = argv[argPos+1];
  383. argPos += 2;
  384. continue;
  385. }
  386. ARG_CASE("-font", 2) {
  387. inputType = FONT;
  388. input = argv[argPos+1];
  389. parseUnicode(unicode, argv[argPos+2]);
  390. argPos += 3;
  391. continue;
  392. }
  393. ARG_CASE("-defineshape", 1) {
  394. inputType = DESCRIPTION_ARG;
  395. input = argv[argPos+1];
  396. argPos += 2;
  397. continue;
  398. }
  399. ARG_CASE("-stdin", 0) {
  400. inputType = DESCRIPTION_STDIN;
  401. input = "stdin";
  402. argPos += 1;
  403. continue;
  404. }
  405. ARG_CASE("-shapedesc", 1) {
  406. inputType = DESCRIPTION_FILE;
  407. input = argv[argPos+1];
  408. argPos += 2;
  409. continue;
  410. }
  411. ARG_CASE("-o", 1) {
  412. output = argv[argPos+1];
  413. outputSpecified = true;
  414. argPos += 2;
  415. continue;
  416. }
  417. ARG_CASE("-stdout", 0) {
  418. output = NULL;
  419. argPos += 1;
  420. continue;
  421. }
  422. ARG_CASE("-legacy", 0) {
  423. legacyMode = true;
  424. argPos += 1;
  425. continue;
  426. }
  427. ARG_CASE("-nooverlap", 0) {
  428. overlapSupport = false;
  429. argPos += 1;
  430. continue;
  431. }
  432. ARG_CASE("-noscanline", 0) {
  433. scanlinePass = false;
  434. argPos += 1;
  435. continue;
  436. }
  437. ARG_CASE("-scanline", 0) {
  438. scanlinePass = true;
  439. argPos += 1;
  440. continue;
  441. }
  442. ARG_CASE("-fillrule", 1) {
  443. if (!strcmp(argv[argPos+1], "nonzero")) fillRule = FILL_NONZERO;
  444. else if (!strcmp(argv[argPos+1], "evenodd") || !strcmp(argv[argPos+1], "odd")) fillRule = FILL_ODD;
  445. else if (!strcmp(argv[argPos+1], "positive")) fillRule = FILL_POSITIVE;
  446. else if (!strcmp(argv[argPos+1], "negative")) fillRule = FILL_NEGATIVE;
  447. else
  448. puts("Unknown fill rule specified.");
  449. argPos += 2;
  450. continue;
  451. }
  452. ARG_CASE("-format", 1) {
  453. if (!strcmp(argv[argPos+1], "auto")) format = AUTO;
  454. else if (!strcmp(argv[argPos+1], "png")) SET_FORMAT(PNG, "png");
  455. else if (!strcmp(argv[argPos+1], "bmp")) SET_FORMAT(BMP, "bmp");
  456. else if (!strcmp(argv[argPos+1], "text") || !strcmp(argv[argPos+1], "txt")) SET_FORMAT(TEXT, "txt");
  457. else if (!strcmp(argv[argPos+1], "textfloat") || !strcmp(argv[argPos+1], "txtfloat")) SET_FORMAT(TEXT_FLOAT, "txt");
  458. else if (!strcmp(argv[argPos+1], "bin") || !strcmp(argv[argPos+1], "binary")) SET_FORMAT(BINARY, "bin");
  459. else if (!strcmp(argv[argPos+1], "binfloat") || !strcmp(argv[argPos+1], "binfloatle")) SET_FORMAT(BINARY_FLOAT, "bin");
  460. else if (!strcmp(argv[argPos+1], "binfloatbe")) SET_FORMAT(BINART_FLOAT_BE, "bin");
  461. else
  462. puts("Unknown format specified.");
  463. argPos += 2;
  464. continue;
  465. }
  466. ARG_CASE("-size", 2) {
  467. unsigned w, h;
  468. if (!parseUnsigned(w, argv[argPos+1]) || !parseUnsigned(h, argv[argPos+2]) || !w || !h)
  469. ABORT("Invalid size arguments. Use -size <width> <height> with two positive integers.");
  470. width = w, height = h;
  471. argPos += 3;
  472. continue;
  473. }
  474. ARG_CASE("-autoframe", 0) {
  475. autoFrame = true;
  476. argPos += 1;
  477. continue;
  478. }
  479. ARG_CASE("-range", 1) {
  480. double r;
  481. if (!parseDouble(r, argv[argPos+1]) || r < 0)
  482. ABORT("Invalid range argument. Use -range <range> with a positive real number.");
  483. rangeMode = RANGE_UNIT;
  484. range = r;
  485. argPos += 2;
  486. continue;
  487. }
  488. ARG_CASE("-pxrange", 1) {
  489. double r;
  490. if (!parseDouble(r, argv[argPos+1]) || r < 0)
  491. ABORT("Invalid range argument. Use -pxrange <range> with a positive real number.");
  492. rangeMode = RANGE_PX;
  493. pxRange = r;
  494. argPos += 2;
  495. continue;
  496. }
  497. ARG_CASE("-scale", 1) {
  498. double s;
  499. if (!parseDouble(s, argv[argPos+1]) || s <= 0)
  500. ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
  501. scale = s;
  502. scaleSpecified = true;
  503. argPos += 2;
  504. continue;
  505. }
  506. ARG_CASE("-ascale", 2) {
  507. double sx, sy;
  508. if (!parseDouble(sx, argv[argPos+1]) || !parseDouble(sy, argv[argPos+2]) || sx <= 0 || sy <= 0)
  509. ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
  510. scale.set(sx, sy);
  511. scaleSpecified = true;
  512. argPos += 3;
  513. continue;
  514. }
  515. ARG_CASE("-translate", 2) {
  516. double tx, ty;
  517. if (!parseDouble(tx, argv[argPos+1]) || !parseDouble(ty, argv[argPos+2]))
  518. ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
  519. translate.set(tx, ty);
  520. argPos += 3;
  521. continue;
  522. }
  523. ARG_CASE("-angle", 1) {
  524. double at;
  525. if (!parseAngle(at, argv[argPos+1]))
  526. ABORT("Invalid angle threshold. Use -angle <min angle> with a positive real number less than PI or a value in degrees followed by 'd' below 180d.");
  527. angleThreshold = at;
  528. argPos += 2;
  529. continue;
  530. }
  531. ARG_CASE("-errorcorrection", 1) {
  532. double et;
  533. if (!parseDouble(et, argv[argPos+1]) || et < 0)
  534. ABORT("Invalid error correction threshold. Use -errorcorrection <threshold> with a real number larger or equal to 1.");
  535. edgeThreshold = et;
  536. argPos += 2;
  537. continue;
  538. }
  539. ARG_CASE("-edgecolors", 1) {
  540. static const char *allowed = " ?,cmyCMY";
  541. for (int i = 0; argv[argPos+1][i]; ++i) {
  542. for (int j = 0; allowed[j]; ++j)
  543. if (argv[argPos+1][i] == allowed[j])
  544. goto ROLL_ARG;
  545. ABORT("Invalid edge coloring sequence. Use -assign <color sequence> with only the colors C, M, and Y. Separate contours by commas and use ? to keep the default assigment for a contour.");
  546. ROLL_ARG:;
  547. }
  548. edgeAssignment = argv[argPos+1];
  549. argPos += 2;
  550. continue;
  551. }
  552. ARG_CASE("-exportshape", 1) {
  553. shapeExport = argv[argPos+1];
  554. argPos += 2;
  555. continue;
  556. }
  557. ARG_CASE("-testrender", 3) {
  558. unsigned w, h;
  559. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  560. ABORT("Invalid arguments for test render. Use -testrender <output.png> <width> <height>.");
  561. testRender = argv[argPos+1];
  562. testWidth = w, testHeight = h;
  563. argPos += 4;
  564. continue;
  565. }
  566. ARG_CASE("-testrendermulti", 3) {
  567. unsigned w, h;
  568. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  569. ABORT("Invalid arguments for test render. Use -testrendermulti <output.png> <width> <height>.");
  570. testRenderMulti = argv[argPos+1];
  571. testWidthM = w, testHeightM = h;
  572. argPos += 4;
  573. continue;
  574. }
  575. ARG_CASE("-yflip", 0) {
  576. yFlip = true;
  577. argPos += 1;
  578. continue;
  579. }
  580. ARG_CASE("-printmetrics", 0) {
  581. printMetrics = true;
  582. argPos += 1;
  583. continue;
  584. }
  585. ARG_CASE("-keeporder", 0) {
  586. orientation = KEEP;
  587. argPos += 1;
  588. continue;
  589. }
  590. ARG_CASE("-reverseorder", 0) {
  591. orientation = REVERSE;
  592. argPos += 1;
  593. continue;
  594. }
  595. ARG_CASE("-guessorder", 0) {
  596. orientation = GUESS;
  597. argPos += 1;
  598. continue;
  599. }
  600. ARG_CASE("-seed", 1) {
  601. if (!parseUnsignedLL(coloringSeed, argv[argPos+1]))
  602. ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");
  603. argPos += 2;
  604. continue;
  605. }
  606. ARG_CASE("-help", 0)
  607. ABORT(helpText);
  608. printf("Unknown setting or insufficient parameters: %s\n", arg);
  609. suggestHelp = true;
  610. ++argPos;
  611. }
  612. if (suggestHelp)
  613. printf("Use -help for more information.\n");
  614. // Load input
  615. Vector2 svgDims;
  616. double glyphAdvance = 0;
  617. if (!inputType || !input)
  618. ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
  619. Shape shape;
  620. switch (inputType) {
  621. case SVG: {
  622. if (!loadSvgShape(shape, input, svgPathIndex, &svgDims))
  623. ABORT("Failed to load shape from SVG file.");
  624. break;
  625. }
  626. case FONT: {
  627. if (!unicode)
  628. ABORT("No character specified! Use -font <file.ttf/otf> <character code>. Character code can be a number (65, 0x41), or a character in apostrophes ('A').");
  629. FreetypeHandle *ft = initializeFreetype();
  630. if (!ft) return -1;
  631. FontHandle *font = loadFont(ft, input);
  632. if (!font) {
  633. deinitializeFreetype(ft);
  634. ABORT("Failed to load font file.");
  635. }
  636. if (!loadGlyph(shape, font, unicode, &glyphAdvance)) {
  637. destroyFont(font);
  638. deinitializeFreetype(ft);
  639. ABORT("Failed to load glyph from font file.");
  640. }
  641. destroyFont(font);
  642. deinitializeFreetype(ft);
  643. break;
  644. }
  645. case DESCRIPTION_ARG: {
  646. if (!readShapeDescription(input, shape, &skipColoring))
  647. ABORT("Parse error in shape description.");
  648. break;
  649. }
  650. case DESCRIPTION_STDIN: {
  651. if (!readShapeDescription(stdin, shape, &skipColoring))
  652. ABORT("Parse error in shape description.");
  653. break;
  654. }
  655. case DESCRIPTION_FILE: {
  656. FILE *file = fopen(input, "r");
  657. if (!file)
  658. ABORT("Failed to load shape description file.");
  659. if (!readShapeDescription(file, shape, &skipColoring))
  660. ABORT("Parse error in shape description.");
  661. fclose(file);
  662. break;
  663. }
  664. default:;
  665. }
  666. // Validate and normalize shape
  667. if (!shape.validate())
  668. ABORT("The geometry of the loaded shape is invalid.");
  669. shape.normalize();
  670. if (yFlip)
  671. shape.inverseYAxis = !shape.inverseYAxis;
  672. double avgScale = .5*(scale.x+scale.y);
  673. struct {
  674. double l, b, r, t;
  675. } bounds = {
  676. LARGE_VALUE, LARGE_VALUE, -LARGE_VALUE, -LARGE_VALUE
  677. };
  678. if (autoFrame || mode == METRICS || printMetrics || orientation == GUESS)
  679. shape.bounds(bounds.l, bounds.b, bounds.r, bounds.t);
  680. // Auto-frame
  681. if (autoFrame) {
  682. double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
  683. Vector2 frame(width, height);
  684. if (rangeMode == RANGE_UNIT)
  685. l -= .5*range, b -= .5*range, r += .5*range, t += .5*range;
  686. else if (!scaleSpecified)
  687. frame -= pxRange;
  688. if (l >= r || b >= t)
  689. l = 0, b = 0, r = 1, t = 1;
  690. if (frame.x <= 0 || frame.y <= 0)
  691. ABORT("Cannot fit the specified pixel range.");
  692. Vector2 dims(r-l, t-b);
  693. if (scaleSpecified)
  694. translate = .5*(frame/scale-dims)-Vector2(l, b);
  695. else {
  696. if (dims.x*frame.y < dims.y*frame.x) {
  697. translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
  698. scale = avgScale = frame.y/dims.y;
  699. } else {
  700. translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
  701. scale = avgScale = frame.x/dims.x;
  702. }
  703. }
  704. if (rangeMode == RANGE_PX && !scaleSpecified)
  705. translate += .5*pxRange/scale;
  706. }
  707. if (rangeMode == RANGE_PX)
  708. range = pxRange/min(scale.x, scale.y);
  709. // Print metrics
  710. if (mode == METRICS || printMetrics) {
  711. FILE *out = stdout;
  712. if (mode == METRICS && outputSpecified)
  713. out = fopen(output, "w");
  714. if (!out)
  715. ABORT("Failed to write output file.");
  716. if (shape.inverseYAxis)
  717. fprintf(out, "inverseY = true\n");
  718. if (bounds.r >= bounds.l && bounds.t >= bounds.b)
  719. fprintf(out, "bounds = %.12g, %.12g, %.12g, %.12g\n", bounds.l, bounds.b, bounds.r, bounds.t);
  720. if (svgDims.x != 0 && svgDims.y != 0)
  721. fprintf(out, "dimensions = %.12g, %.12g\n", svgDims.x, svgDims.y);
  722. if (glyphAdvance != 0)
  723. fprintf(out, "advance = %.12g\n", glyphAdvance);
  724. if (autoFrame) {
  725. if (!scaleSpecified)
  726. fprintf(out, "scale = %.12g\n", avgScale);
  727. fprintf(out, "translate = %.12g, %.12g\n", translate.x, translate.y);
  728. }
  729. if (rangeMode == RANGE_PX)
  730. fprintf(out, "range = %.12g\n", range);
  731. if (mode == METRICS && outputSpecified)
  732. fclose(out);
  733. }
  734. // Compute output
  735. Bitmap<float> sdf;
  736. Bitmap<FloatRGB> msdf;
  737. switch (mode) {
  738. case SINGLE: {
  739. sdf = Bitmap<float>(width, height);
  740. if (legacyMode)
  741. generateSDF_legacy(sdf, shape, range, scale, translate);
  742. else
  743. generateSDF(sdf, shape, range, scale, translate, overlapSupport);
  744. break;
  745. }
  746. case PSEUDO: {
  747. sdf = Bitmap<float>(width, height);
  748. if (legacyMode)
  749. generatePseudoSDF_legacy(sdf, shape, range, scale, translate);
  750. else
  751. generatePseudoSDF(sdf, shape, range, scale, translate, overlapSupport);
  752. break;
  753. }
  754. case MULTI: {
  755. if (!skipColoring)
  756. edgeColoringSimple(shape, angleThreshold, coloringSeed);
  757. if (edgeAssignment)
  758. parseColoring(shape, edgeAssignment);
  759. msdf = Bitmap<FloatRGB>(width, height);
  760. if (legacyMode)
  761. generateMSDF_legacy(msdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold);
  762. else
  763. generateMSDF(msdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold, overlapSupport);
  764. break;
  765. }
  766. default:;
  767. }
  768. if (orientation == GUESS) {
  769. // Get sign of signed distance outside bounds
  770. Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);
  771. double dummy;
  772. SignedDistance minDistance;
  773. for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)
  774. for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
  775. SignedDistance distance = (*edge)->signedDistance(p, dummy);
  776. if (distance < minDistance)
  777. minDistance = distance;
  778. }
  779. orientation = minDistance.sqDistance <= 0 ? KEEP : REVERSE;
  780. }
  781. if (orientation == REVERSE) {
  782. switch (mode) {
  783. case SINGLE:
  784. case PSEUDO:
  785. invertColor(sdf);
  786. break;
  787. case MULTI:
  788. invertColor(msdf);
  789. break;
  790. default:;
  791. }
  792. }
  793. if (scanlinePass) {
  794. switch (mode) {
  795. case SINGLE:
  796. case PSEUDO:
  797. distanceSignCorrection(sdf, shape, scale, translate, fillRule);
  798. break;
  799. case MULTI:
  800. distanceSignCorrection(msdf, shape, scale, translate, fillRule);
  801. if (edgeThreshold > 0)
  802. msdfErrorCorrection(msdf, edgeThreshold/(scale*range));
  803. break;
  804. default:;
  805. }
  806. }
  807. // Save output
  808. if (shapeExport) {
  809. FILE *file = fopen(shapeExport, "w");
  810. if (file) {
  811. writeShapeDescription(file, shape);
  812. fclose(file);
  813. } else
  814. puts("Failed to write shape export file.");
  815. }
  816. const char *error = NULL;
  817. switch (mode) {
  818. case SINGLE:
  819. case PSEUDO:
  820. error = writeOutput(sdf, output, format);
  821. if (error)
  822. ABORT(error);
  823. if (testRenderMulti || testRender)
  824. simulate8bit(sdf);
  825. if (testRenderMulti) {
  826. Bitmap<FloatRGB> render(testWidthM, testHeightM);
  827. renderSDF(render, sdf, avgScale*range);
  828. if (!savePng(render, testRenderMulti))
  829. puts("Failed to write test render file.");
  830. }
  831. if (testRender) {
  832. Bitmap<float> render(testWidth, testHeight);
  833. renderSDF(render, sdf, avgScale*range);
  834. if (!savePng(render, testRender))
  835. puts("Failed to write test render file.");
  836. }
  837. break;
  838. case MULTI:
  839. error = writeOutput(msdf, output, format);
  840. if (error)
  841. ABORT(error);
  842. if (testRenderMulti || testRender)
  843. simulate8bit(msdf);
  844. if (testRenderMulti) {
  845. Bitmap<FloatRGB> render(testWidthM, testHeightM);
  846. renderSDF(render, msdf, avgScale*range);
  847. if (!savePng(render, testRenderMulti))
  848. puts("Failed to write test render file.");
  849. }
  850. if (testRender) {
  851. Bitmap<float> render(testWidth, testHeight);
  852. renderSDF(render, msdf, avgScale*range);
  853. if (!savePng(render, testRender))
  854. ABORT("Failed to write test render file.");
  855. }
  856. break;
  857. default:;
  858. }
  859. return 0;
  860. }
  861. #endif