main.cpp 40 KB

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