main.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. /*
  2. * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR - standalone console program
  3. * --------------------------------------------------------------------------
  4. * A utility by Viktor Chlumsky, (c) 2014 - 2025
  5. *
  6. */
  7. #ifdef MSDFGEN_STANDALONE
  8. #ifndef _USE_MATH_DEFINES
  9. #define _USE_MATH_DEFINES
  10. #endif
  11. #ifndef _CRT_SECURE_NO_WARNINGS
  12. #define _CRT_SECURE_NO_WARNINGS
  13. #endif
  14. #include <cstdlib>
  15. #include <cstdio>
  16. #include <cmath>
  17. #include <cstring>
  18. #include <string>
  19. #include "msdfgen.h"
  20. #ifdef MSDFGEN_EXTENSIONS
  21. #include "msdfgen-ext.h"
  22. #endif
  23. #include "core/ShapeDistanceFinder.h"
  24. #define SDF_ERROR_ESTIMATE_PRECISION 19
  25. #define DEFAULT_ANGLE_THRESHOLD 3.
  26. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  27. #define DEFAULT_IMAGE_EXTENSION "png"
  28. #define SAVE_DEFAULT_IMAGE_FORMAT savePng
  29. #else
  30. #define DEFAULT_IMAGE_EXTENSION "tiff"
  31. #define SAVE_DEFAULT_IMAGE_FORMAT saveTiff
  32. #endif
  33. using namespace msdfgen;
  34. enum Format {
  35. AUTO,
  36. PNG,
  37. BMP,
  38. TIFF,
  39. RGBA,
  40. FL32,
  41. TEXT,
  42. TEXT_FLOAT,
  43. BINARY,
  44. BINARY_FLOAT,
  45. BINARY_FLOAT_BE
  46. };
  47. static bool is8bitFormat(Format format) {
  48. return format == PNG || format == BMP || format == RGBA || format == TEXT || format == BINARY;
  49. }
  50. static char toupper(char c) {
  51. return c >= 'a' && c <= 'z' ? c-'a'+'A' : c;
  52. }
  53. static bool parseUnsigned(unsigned &value, const char *arg) {
  54. char *end = NULL;
  55. value = (unsigned) strtoul(arg, &end, 10);
  56. return end > arg && !*end;
  57. }
  58. static bool parseUnsignedDecOrHex(unsigned &value, const char *arg) {
  59. char *end = NULL;
  60. if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X')) {
  61. arg += 2;
  62. value = (unsigned) strtoul(arg, &end, 16);
  63. } else
  64. value = (unsigned) strtoul(arg, &end, 10);
  65. return end > arg && !*end;
  66. }
  67. static bool parseUnsignedLL(unsigned long long &value, const char *arg) {
  68. if (*arg >= '0' && *arg <= '9') {
  69. value = 0;
  70. do {
  71. value = 10*value+(*arg++-'0');
  72. } while (*arg >= '0' && *arg <= '9');
  73. return !*arg;
  74. }
  75. return false;
  76. }
  77. static bool parseDouble(double &value, const char *arg) {
  78. char *end = NULL;
  79. value = strtod(arg, &end);
  80. return end > arg && !*end;
  81. }
  82. static bool parseAngle(double &value, const char *arg) {
  83. char *end = NULL;
  84. value = strtod(arg, &end);
  85. if (end > arg) {
  86. arg = end;
  87. if (*arg == 'd' || *arg == 'D') {
  88. ++arg;
  89. value *= M_PI/180;
  90. }
  91. return !*arg;
  92. }
  93. return false;
  94. }
  95. static void parseColoring(Shape &shape, const char *edgeAssignment) {
  96. unsigned c = 0, e = 0;
  97. if (shape.contours.size() < c) return;
  98. Contour *contour = &shape.contours[c];
  99. bool change = false;
  100. bool clear = true;
  101. for (const char *in = edgeAssignment; *in; ++in) {
  102. switch (*in) {
  103. case ',':
  104. if (change)
  105. ++e;
  106. if (clear)
  107. while (e < contour->edges.size()) {
  108. contour->edges[e]->color = WHITE;
  109. ++e;
  110. }
  111. ++c, e = 0;
  112. if (shape.contours.size() <= c) return;
  113. contour = &shape.contours[c];
  114. change = false;
  115. clear = true;
  116. break;
  117. case '?':
  118. clear = false;
  119. break;
  120. case 'C': case 'M': case 'W': case 'Y': case 'c': case 'm': case 'w': case 'y':
  121. if (change) {
  122. ++e;
  123. change = false;
  124. }
  125. if (e < contour->edges.size()) {
  126. contour->edges[e]->color = EdgeColor(
  127. (*in == 'C' || *in == 'c')*CYAN|
  128. (*in == 'M' || *in == 'm')*MAGENTA|
  129. (*in == 'Y' || *in == 'y')*YELLOW|
  130. (*in == 'W' || *in == 'w')*WHITE);
  131. change = true;
  132. }
  133. break;
  134. }
  135. }
  136. }
  137. #ifdef MSDFGEN_EXTENSIONS
  138. static bool parseUnicode(unicode_t &unicode, const char *arg) {
  139. unsigned uuc;
  140. if (parseUnsignedDecOrHex(uuc, arg)) {
  141. unicode = uuc;
  142. return true;
  143. }
  144. if (arg[0] == '\'' && arg[1] && arg[2] == '\'' && !arg[3]) {
  145. unicode = (unicode_t) (unsigned char) arg[1];
  146. return true;
  147. }
  148. return false;
  149. }
  150. #ifndef MSDFGEN_DISABLE_VARIABLE_FONTS
  151. static FontHandle *loadVarFont(FreetypeHandle *library, const char *filename) {
  152. std::string buffer;
  153. while (*filename && *filename != '?')
  154. buffer.push_back(*filename++);
  155. FontHandle *font = loadFont(library, buffer.c_str());
  156. if (font && *filename++ == '?') {
  157. do {
  158. buffer.clear();
  159. while (*filename && *filename != '=')
  160. buffer.push_back(*filename++);
  161. if (*filename == '=') {
  162. char *end = NULL;
  163. double value = strtod(++filename, &end);
  164. if (end > filename) {
  165. filename = end;
  166. setFontVariationAxis(library, font, buffer.c_str(), value);
  167. }
  168. }
  169. } while (*filename++ == '&');
  170. }
  171. return font;
  172. }
  173. #endif
  174. #endif
  175. template <int N>
  176. static void invertColor(const BitmapRef<float, N> &bitmap) {
  177. const float *end = bitmap.pixels+N*bitmap.width*bitmap.height;
  178. for (float *p = bitmap.pixels; p < end; ++p)
  179. *p = 1.f-*p;
  180. }
  181. static bool writeTextBitmap(FILE *file, const float *values, int cols, int rows) {
  182. for (int row = 0; row < rows; ++row) {
  183. for (int col = 0; col < cols; ++col) {
  184. int v = clamp(int((*values++)*0x100), 0xff);
  185. fprintf(file, col ? " %02X" : "%02X", v);
  186. }
  187. fprintf(file, "\n");
  188. }
  189. return true;
  190. }
  191. static bool writeTextBitmapFloat(FILE *file, const float *values, int cols, int rows) {
  192. for (int row = 0; row < rows; ++row) {
  193. for (int col = 0; col < cols; ++col) {
  194. fprintf(file, col ? " %.9g" : "%.9g", *values++);
  195. }
  196. fprintf(file, "\n");
  197. }
  198. return true;
  199. }
  200. static bool writeBinBitmap(FILE *file, const float *values, int count) {
  201. for (int pos = 0; pos < count; ++pos) {
  202. unsigned char v = clamp(int((*values++)*0x100), 0xff);
  203. fwrite(&v, 1, 1, file);
  204. }
  205. return true;
  206. }
  207. #ifdef __BIG_ENDIAN__
  208. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  209. #else
  210. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  211. #endif
  212. {
  213. return (int) fwrite(values, sizeof(float), count, file) == count;
  214. }
  215. #ifdef __BIG_ENDIAN__
  216. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  217. #else
  218. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  219. #endif
  220. {
  221. for (int pos = 0; pos < count; ++pos) {
  222. const unsigned char *b = reinterpret_cast<const unsigned char *>(values++);
  223. for (int i = sizeof(float)-1; i >= 0; --i)
  224. fwrite(b+i, 1, 1, file);
  225. }
  226. return true;
  227. }
  228. static bool cmpExtension(const char *path, const char *ext) {
  229. for (const char *a = path+strlen(path)-1, *b = ext+strlen(ext)-1; b >= ext; --a, --b)
  230. if (a < path || toupper(*a) != toupper(*b))
  231. return false;
  232. return true;
  233. }
  234. template <int N>
  235. static const char *writeOutput(const BitmapConstRef<float, N> &bitmap, const char *filename, Format &format) {
  236. if (filename) {
  237. if (format == AUTO) {
  238. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  239. if (cmpExtension(filename, ".png")) format = PNG;
  240. #else
  241. if (cmpExtension(filename, ".png"))
  242. return "PNG format is not available in core-only version.";
  243. #endif
  244. else if (cmpExtension(filename, ".bmp")) format = BMP;
  245. else if (cmpExtension(filename, ".tiff") || cmpExtension(filename, ".tif")) format = TIFF;
  246. else if (cmpExtension(filename, ".rgba")) format = RGBA;
  247. else if (cmpExtension(filename, ".fl32")) format = FL32;
  248. else if (cmpExtension(filename, ".txt")) format = TEXT;
  249. else if (cmpExtension(filename, ".bin")) format = BINARY;
  250. else
  251. return "Could not deduce format from output file name.";
  252. }
  253. switch (format) {
  254. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  255. case PNG: return savePng(bitmap, filename) ? NULL : "Failed to write output PNG image.";
  256. #endif
  257. case BMP: return saveBmp(bitmap, filename) ? NULL : "Failed to write output BMP image.";
  258. case TIFF: return saveTiff(bitmap, filename) ? NULL : "Failed to write output TIFF image.";
  259. case RGBA: return saveRgba(bitmap, filename) ? NULL : "Failed to write output RGBA image.";
  260. case FL32: return saveFl32(bitmap, filename) ? NULL : "Failed to write output FL32 image.";
  261. case TEXT: case TEXT_FLOAT: {
  262. FILE *file = fopen(filename, "w");
  263. if (!file) return "Failed to write output text file.";
  264. if (format == TEXT)
  265. writeTextBitmap(file, bitmap.pixels, N*bitmap.width, bitmap.height);
  266. else if (format == TEXT_FLOAT)
  267. writeTextBitmapFloat(file, bitmap.pixels, N*bitmap.width, bitmap.height);
  268. fclose(file);
  269. return NULL;
  270. }
  271. case BINARY: case BINARY_FLOAT: case BINARY_FLOAT_BE: {
  272. FILE *file = fopen(filename, "wb");
  273. if (!file) return "Failed to write output binary file.";
  274. if (format == BINARY)
  275. writeBinBitmap(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  276. else if (format == BINARY_FLOAT)
  277. writeBinBitmapFloat(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  278. else if (format == BINARY_FLOAT_BE)
  279. writeBinBitmapFloatBE(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  280. fclose(file);
  281. return NULL;
  282. }
  283. default:;
  284. }
  285. } else {
  286. if (format == AUTO || format == TEXT)
  287. writeTextBitmap(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
  288. else if (format == TEXT_FLOAT)
  289. writeTextBitmapFloat(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
  290. else
  291. return "Unsupported format for standard output.";
  292. }
  293. return NULL;
  294. }
  295. #define STRINGIZE_(x) #x
  296. #define STRINGIZE(x) STRINGIZE_(x)
  297. #define MSDFGEN_VERSION_STRING STRINGIZE(MSDFGEN_VERSION)
  298. #ifdef MSDFGEN_VERSION_UNDERLINE
  299. #define VERSION_UNDERLINE STRINGIZE(MSDFGEN_VERSION_UNDERLINE)
  300. #else
  301. #define VERSION_UNDERLINE "--------"
  302. #endif
  303. #if defined(MSDFGEN_EXTENSIONS) && (defined(MSDFGEN_DISABLE_SVG) || defined(MSDFGEN_DISABLE_PNG) || defined(MSDFGEN_DISABLE_VARIABLE_FONTS))
  304. #define TITLE_SUFFIX " - custom config"
  305. #define SUFFIX_UNDERLINE "----------------"
  306. #elif !defined(MSDFGEN_EXTENSIONS) && defined(MSDFGEN_USE_OPENMP)
  307. #define TITLE_SUFFIX " - core with OpenMP"
  308. #define SUFFIX_UNDERLINE "-------------------"
  309. #elif !defined(MSDFGEN_EXTENSIONS)
  310. #define TITLE_SUFFIX " - core only"
  311. #define SUFFIX_UNDERLINE "------------"
  312. #elif defined(MSDFGEN_USE_SKIA) && defined(MSDFGEN_USE_OPENMP)
  313. #define TITLE_SUFFIX " with Skia & OpenMP"
  314. #define SUFFIX_UNDERLINE "-------------------"
  315. #elif defined(MSDFGEN_USE_SKIA)
  316. #define TITLE_SUFFIX " with Skia"
  317. #define SUFFIX_UNDERLINE "----------"
  318. #elif defined(MSDFGEN_USE_OPENMP)
  319. #define TITLE_SUFFIX " with OpenMP"
  320. #define SUFFIX_UNDERLINE "------------"
  321. #else
  322. #define TITLE_SUFFIX
  323. #define SUFFIX_UNDERLINE
  324. #endif
  325. static const char *const versionText =
  326. "MSDFgen v" MSDFGEN_VERSION_STRING TITLE_SUFFIX "\n"
  327. "(c) 2016 - " STRINGIZE(MSDFGEN_COPYRIGHT_YEAR) " Viktor Chlumsky";
  328. static const char *const helpText =
  329. "\n"
  330. "Multi-channel signed distance field generator by Viktor Chlumsky v" MSDFGEN_VERSION_STRING TITLE_SUFFIX "\n"
  331. "------------------------------------------------------------------" VERSION_UNDERLINE SUFFIX_UNDERLINE "\n"
  332. " Usage: msdfgen"
  333. #ifdef _WIN32
  334. ".exe"
  335. #endif
  336. " <mode> <input specification> <options>\n"
  337. "\n"
  338. "MODES\n"
  339. " sdf - Generate conventional monochrome (true) signed distance field.\n"
  340. " psdf - Generate monochrome signed perpendicular distance field.\n"
  341. " msdf - Generate multi-channel signed distance field. This is used by default if no mode is specified.\n"
  342. " mtsdf - Generate combined multi-channel and true signed distance field in the alpha channel.\n"
  343. " metrics - Report shape metrics only.\n"
  344. "\n"
  345. "INPUT SPECIFICATION\n"
  346. " -defineshape <definition>\n"
  347. "\tDefines input shape using the ad-hoc text definition.\n"
  348. #ifdef MSDFGEN_EXTENSIONS
  349. " -font <filename.ttf> <character code>\n"
  350. "\tLoads a single glyph from the specified font file.\n"
  351. "\tFormat of character code is '?', 63, 0x3F (Unicode value), or g34 (glyph index).\n"
  352. #endif
  353. " -shapedesc <filename.txt>\n"
  354. "\tLoads text shape description from a file.\n"
  355. " -stdin\n"
  356. "\tReads text shape description from the standard input.\n"
  357. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)
  358. " -svg <filename.svg>\n"
  359. "\tLoads the last vector path found in the specified SVG file.\n"
  360. #endif
  361. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_VARIABLE_FONTS)
  362. " -varfont <filename and variables> <character code>\n"
  363. "\tLoads a single glyph from a variable font. Specify variable values as x.ttf?var1=0.5&var2=1\n"
  364. #endif
  365. "\n"
  366. // Keep alphabetical order!
  367. "OPTIONS\n"
  368. " -angle <angle>\n"
  369. "\tSpecifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees.\n"
  370. " -apxrange <outermost distance> <innermost distance>\n"
  371. "\tSpecifies the outermost (negative) and innermost representable distance in pixels.\n"
  372. " -arange <outermost distance> <innermost distance>\n"
  373. "\tSpecifies the outermost (negative) and innermost representable distance in shape units.\n"
  374. " -ascale <x scale> <y scale>\n"
  375. "\tSets the scale used to convert shape units to pixels asymmetrically.\n"
  376. " -autoframe\n"
  377. "\tAutomatically scales (unless specified) and translates the shape to fit.\n"
  378. " -coloringstrategy <simple / inktrap / distance>\n"
  379. "\tSelects the strategy of the edge coloring heuristic.\n"
  380. " -dimensions <width> <height>\n"
  381. "\tSets the dimensions of the output image.\n"
  382. " -edgecolors <sequence>\n"
  383. "\tOverrides automatic edge coloring with the specified color sequence.\n"
  384. #ifdef MSDFGEN_EXTENSIONS
  385. " -emnormalize\n"
  386. "\tBefore applying scale, normalizes font glyph coordinates so that 1 = 1 em.\n"
  387. #endif
  388. " -errorcorrection <mode>\n"
  389. "\tChanges the MSDF/MTSDF error correction mode. Use -errorcorrection help for a list of valid modes.\n"
  390. " -errordeviationratio <ratio>\n"
  391. "\tSets the minimum ratio between the actual and maximum expected distance delta to be considered an error.\n"
  392. " -errorimproveratio <ratio>\n"
  393. "\tSets the minimum ratio between the pre-correction distance error and the post-correction distance error.\n"
  394. " -estimateerror\n"
  395. "\tComputes and prints the distance field's estimated fill error to the standard output.\n"
  396. " -exportshape <filename.txt>\n"
  397. "\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"
  398. " -exportsvg <filename.svg>\n"
  399. "\tSaves the shape geometry into a simple SVG file.\n"
  400. " -fillrule <nonzero / evenodd / positive / negative>\n"
  401. "\tSets the fill rule for the scanline pass. Default is nonzero.\n"
  402. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  403. " -format <png / bmp / tiff / rgba / fl32 / text / textfloat / bin / binfloat / binfloatbe>\n"
  404. #else
  405. " -format <bmp / tiff / rgba / fl32 / text / textfloat / bin / binfloat / binfloatbe>\n"
  406. #endif
  407. "\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"
  408. " -guessorder\n"
  409. "\tAttempts to detect if shape contours have the wrong winding and generates the SDF with the right one.\n"
  410. " -help\n"
  411. "\tDisplays this help.\n"
  412. " -legacy\n"
  413. "\tUses the original (legacy) distance field algorithms.\n"
  414. #ifdef MSDFGEN_EXTENSIONS
  415. " -noemnormalize\n"
  416. "\tRaw integer font glyph coordinates will be used. Without this option, legacy scaling will be applied.\n"
  417. #endif
  418. #ifdef MSDFGEN_USE_SKIA
  419. " -nopreprocess\n"
  420. "\tDisables path preprocessing which resolves self-intersections and overlapping contours.\n"
  421. #else
  422. " -nooverlap\n"
  423. "\tDisables resolution of overlapping contours.\n"
  424. " -noscanline\n"
  425. "\tDisables the scanline pass, which corrects the distance field's signs according to the selected fill rule.\n"
  426. #endif
  427. " -o <filename>\n"
  428. "\tSets the output file name. The default value is \"output." DEFAULT_IMAGE_EXTENSION "\".\n"
  429. #ifdef MSDFGEN_USE_SKIA
  430. " -overlap\n"
  431. "\tSwitches to distance field generator with support for overlapping contours.\n"
  432. #endif
  433. " -printmetrics\n"
  434. "\tPrints relevant metrics of the shape to the standard output.\n"
  435. " -pxrange <range>\n"
  436. "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
  437. " -range <range>\n"
  438. "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
  439. " -reverseorder\n"
  440. "\tGenerates the distance field as if the shape's vertices were in reverse order.\n"
  441. " -scale <scale>\n"
  442. "\tSets the scale used to convert shape units to pixels.\n"
  443. #ifdef MSDFGEN_USE_SKIA
  444. " -scanline\n"
  445. "\tPerforms an additional scanline pass to fix the signs of the distances.\n"
  446. #endif
  447. " -seed <n>\n"
  448. "\tSets the random seed for edge coloring heuristic.\n"
  449. " -stdout\n"
  450. "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
  451. " -testrender <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"
  452. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  453. "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
  454. #else
  455. "\tRenders an image preview using the generated distance field and saves it as a TIFF file.\n"
  456. #endif
  457. " -testrendermulti <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"
  458. "\tRenders an image preview without flattening the color channels.\n"
  459. " -translate <x> <y>\n"
  460. "\tSets the translation of the shape in shape units.\n"
  461. " -version\n"
  462. "\tPrints the version of the program.\n"
  463. " -windingpreprocess\n"
  464. "\tAttempts to fix only the contour windings assuming no self-intersections and even-odd fill rule.\n"
  465. " -yflip\n"
  466. "\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
  467. "\n";
  468. static const char *errorCorrectionHelpText =
  469. "\n"
  470. "ERROR CORRECTION MODES\n"
  471. " auto-fast\n"
  472. "\tDetects inversion artifacts and distance errors that do not affect edges by range testing.\n"
  473. " auto-full\n"
  474. "\tDetects inversion artifacts and distance errors that do not affect edges by exact distance evaluation.\n"
  475. " auto-mixed (default)\n"
  476. "\tDetects inversions by distance evaluation and distance errors that do not affect edges by range testing.\n"
  477. " disabled\n"
  478. "\tDisables error correction.\n"
  479. " distance-fast\n"
  480. "\tDetects distance errors by range testing. Does not care if edges and corners are affected.\n"
  481. " distance-full\n"
  482. "\tDetects distance errors by exact distance evaluation. Does not care if edges and corners are affected, slow.\n"
  483. " edge-fast\n"
  484. "\tDetects inversion artifacts only by range testing.\n"
  485. " edge-full\n"
  486. "\tDetects inversion artifacts only by exact distance evaluation.\n"
  487. " help\n"
  488. "\tDisplays this help.\n"
  489. "\n";
  490. int main(int argc, const char *const *argv) {
  491. #define ABORT(msg) do { fputs(msg "\n", stderr); return 1; } while (false)
  492. // Parse command line arguments
  493. enum {
  494. NONE,
  495. SVG,
  496. FONT,
  497. VAR_FONT,
  498. DESCRIPTION_ARG,
  499. DESCRIPTION_STDIN,
  500. DESCRIPTION_FILE
  501. } inputType = NONE;
  502. enum {
  503. SINGLE,
  504. PERPENDICULAR,
  505. MULTI,
  506. MULTI_AND_TRUE,
  507. METRICS
  508. } mode = MULTI;
  509. enum {
  510. NO_PREPROCESS,
  511. WINDING_PREPROCESS,
  512. FULL_PREPROCESS
  513. } geometryPreproc = (
  514. #ifdef MSDFGEN_USE_SKIA
  515. FULL_PREPROCESS
  516. #else
  517. NO_PREPROCESS
  518. #endif
  519. );
  520. bool legacyMode = false;
  521. MSDFGeneratorConfig generatorConfig;
  522. generatorConfig.overlapSupport = geometryPreproc == NO_PREPROCESS;
  523. bool scanlinePass = geometryPreproc == NO_PREPROCESS;
  524. FillRule fillRule = FILL_NONZERO;
  525. Format format = AUTO;
  526. const char *input = NULL;
  527. const char *output = "output." DEFAULT_IMAGE_EXTENSION;
  528. const char *shapeExport = NULL;
  529. const char *svgExport = NULL;
  530. const char *testRender = NULL;
  531. const char *testRenderMulti = NULL;
  532. bool outputSpecified = false;
  533. #ifdef MSDFGEN_EXTENSIONS
  534. bool glyphIndexSpecified = false;
  535. GlyphIndex glyphIndex;
  536. unicode_t unicode = 0;
  537. FontCoordinateScaling fontCoordinateScaling = FONT_SCALING_LEGACY;
  538. bool fontCoordinateScalingSpecified = false;
  539. #endif
  540. int width = 64, height = 64;
  541. int testWidth = 0, testHeight = 0;
  542. int testWidthM = 0, testHeightM = 0;
  543. bool autoFrame = false;
  544. enum {
  545. RANGE_UNIT,
  546. RANGE_PX
  547. } rangeMode = RANGE_PX;
  548. Range range(1);
  549. Range pxRange(2);
  550. Vector2 translate;
  551. Vector2 scale = 1;
  552. bool scaleSpecified = false;
  553. double angleThreshold = DEFAULT_ANGLE_THRESHOLD;
  554. float outputDistanceShift = 0.f;
  555. const char *edgeAssignment = NULL;
  556. bool yFlip = false;
  557. bool printMetrics = false;
  558. bool estimateError = false;
  559. bool skipColoring = false;
  560. enum {
  561. KEEP,
  562. REVERSE,
  563. GUESS
  564. } orientation = KEEP;
  565. unsigned long long coloringSeed = 0;
  566. void (*edgeColoring)(Shape &, double, unsigned long long) = &edgeColoringSimple;
  567. bool explicitErrorCorrectionMode = false;
  568. int argPos = 1;
  569. bool suggestHelp = false;
  570. while (argPos < argc) {
  571. const char *arg = argv[argPos];
  572. #define ARG_CASE(s, p) if ((!strcmp(arg, s)) && argPos+(p) < argc && (++argPos, true))
  573. #define ARG_CASE_OR ) || !strcmp(arg,
  574. #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
  575. #define ARG_IS(s) (!strcmp(argv[argPos], s))
  576. #define SET_FORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
  577. // Accept arguments prefixed with -- instead of -
  578. if (arg[0] == '-' && arg[1] == '-')
  579. ++arg;
  580. ARG_MODE("sdf", SINGLE)
  581. ARG_MODE("psdf", PERPENDICULAR)
  582. ARG_MODE("msdf", MULTI)
  583. ARG_MODE("mtsdf", MULTI_AND_TRUE)
  584. ARG_MODE("metrics", METRICS)
  585. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)
  586. ARG_CASE("-svg", 1) {
  587. inputType = SVG;
  588. input = argv[argPos++];
  589. continue;
  590. }
  591. #endif
  592. #ifdef MSDFGEN_EXTENSIONS
  593. //ARG_CASE -font, -varfont
  594. if (argPos+2 < argc && (
  595. (!strcmp(arg, "-font") && (inputType = FONT, true))
  596. #ifndef MSDFGEN_DISABLE_VARIABLE_FONTS
  597. || (!strcmp(arg, "-varfont") && (inputType = VAR_FONT, true))
  598. #endif
  599. ) && (++argPos, true)) {
  600. input = argv[argPos++];
  601. const char *charArg = argv[argPos++];
  602. unsigned gi;
  603. switch (charArg[0]) {
  604. case 'G': case 'g':
  605. if (parseUnsignedDecOrHex(gi, charArg+1)) {
  606. glyphIndex = GlyphIndex(gi);
  607. glyphIndexSpecified = true;
  608. }
  609. break;
  610. case 'U': case 'u':
  611. ++charArg;
  612. // fallthrough
  613. default:
  614. parseUnicode(unicode, charArg);
  615. }
  616. continue;
  617. }
  618. ARG_CASE("-noemnormalize", 0) {
  619. fontCoordinateScaling = FONT_SCALING_NONE;
  620. fontCoordinateScalingSpecified = true;
  621. continue;
  622. }
  623. ARG_CASE("-emnormalize", 0) {
  624. fontCoordinateScaling = FONT_SCALING_EM_NORMALIZED;
  625. fontCoordinateScalingSpecified = true;
  626. continue;
  627. }
  628. ARG_CASE("-legacyfontscaling", 0) {
  629. fontCoordinateScaling = FONT_SCALING_LEGACY;
  630. fontCoordinateScalingSpecified = true;
  631. continue;
  632. }
  633. #else
  634. ARG_CASE("-svg", 1) {
  635. ABORT("SVG input is not available in core-only version.");
  636. }
  637. ARG_CASE("-font", 2) {
  638. ABORT("Font input is not available in core-only version.");
  639. }
  640. ARG_CASE("-varfont", 2) {
  641. ABORT("Variable font input is not available in core-only version.");
  642. }
  643. #endif
  644. ARG_CASE("-defineshape", 1) {
  645. inputType = DESCRIPTION_ARG;
  646. input = argv[argPos++];
  647. continue;
  648. }
  649. ARG_CASE("-stdin", 0) {
  650. inputType = DESCRIPTION_STDIN;
  651. input = "stdin";
  652. continue;
  653. }
  654. ARG_CASE("-shapedesc", 1) {
  655. inputType = DESCRIPTION_FILE;
  656. input = argv[argPos++];
  657. continue;
  658. }
  659. ARG_CASE("-o" ARG_CASE_OR "-out" ARG_CASE_OR "-output" ARG_CASE_OR "-imageout", 1) {
  660. output = argv[argPos++];
  661. outputSpecified = true;
  662. continue;
  663. }
  664. ARG_CASE("-stdout", 0) {
  665. output = NULL;
  666. continue;
  667. }
  668. ARG_CASE("-legacy", 0) {
  669. legacyMode = true;
  670. #ifdef MSDFGEN_EXTENSIONS
  671. fontCoordinateScaling = FONT_SCALING_LEGACY;
  672. fontCoordinateScalingSpecified = true;
  673. #endif
  674. continue;
  675. }
  676. ARG_CASE("-nopreprocess", 0) {
  677. geometryPreproc = NO_PREPROCESS;
  678. continue;
  679. }
  680. ARG_CASE("-windingpreprocess", 0) {
  681. geometryPreproc = WINDING_PREPROCESS;
  682. continue;
  683. }
  684. ARG_CASE("-preprocess", 0) {
  685. geometryPreproc = FULL_PREPROCESS;
  686. continue;
  687. }
  688. ARG_CASE("-nooverlap", 0) {
  689. generatorConfig.overlapSupport = false;
  690. continue;
  691. }
  692. ARG_CASE("-overlap", 0) {
  693. generatorConfig.overlapSupport = true;
  694. continue;
  695. }
  696. ARG_CASE("-noscanline", 0) {
  697. scanlinePass = false;
  698. continue;
  699. }
  700. ARG_CASE("-scanline", 0) {
  701. scanlinePass = true;
  702. continue;
  703. }
  704. ARG_CASE("-fillrule", 1) {
  705. scanlinePass = true;
  706. if (ARG_IS("nonzero")) fillRule = FILL_NONZERO;
  707. else if (ARG_IS("evenodd") || ARG_IS("odd")) fillRule = FILL_ODD;
  708. else if (ARG_IS("positive")) fillRule = FILL_POSITIVE;
  709. else if (ARG_IS("negative")) fillRule = FILL_NEGATIVE;
  710. else
  711. fputs("Unknown fill rule specified.\n", stderr);
  712. ++argPos;
  713. continue;
  714. }
  715. ARG_CASE("-format", 1) {
  716. if (ARG_IS("auto")) format = AUTO;
  717. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  718. else if (ARG_IS("png")) SET_FORMAT(PNG, "png");
  719. #else
  720. else if (ARG_IS("png"))
  721. fputs("PNG format is not available in core-only version.\n", stderr);
  722. #endif
  723. else if (ARG_IS("bmp")) SET_FORMAT(BMP, "bmp");
  724. else if (ARG_IS("tiff") || ARG_IS("tif")) SET_FORMAT(TIFF, "tiff");
  725. else if (ARG_IS("rgba")) SET_FORMAT(RGBA, "rgba");
  726. else if (ARG_IS("fl32")) SET_FORMAT(FL32, "fl32");
  727. else if (ARG_IS("text") || ARG_IS("txt")) SET_FORMAT(TEXT, "txt");
  728. else if (ARG_IS("textfloat") || ARG_IS("txtfloat")) SET_FORMAT(TEXT_FLOAT, "txt");
  729. else if (ARG_IS("bin") || ARG_IS("binary")) SET_FORMAT(BINARY, "bin");
  730. else if (ARG_IS("binfloat") || ARG_IS("binfloatle")) SET_FORMAT(BINARY_FLOAT, "bin");
  731. else if (ARG_IS("binfloatbe")) SET_FORMAT(BINARY_FLOAT_BE, "bin");
  732. else
  733. fputs("Unknown format specified.\n", stderr);
  734. ++argPos;
  735. continue;
  736. }
  737. ARG_CASE("-dimensions" ARG_CASE_OR "-size", 2) {
  738. unsigned w, h;
  739. if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && w && h))
  740. ABORT("Invalid dimensions. Use -dimensions <width> <height> with two positive integers.");
  741. width = w, height = h;
  742. continue;
  743. }
  744. ARG_CASE("-autoframe", 0) {
  745. autoFrame = true;
  746. continue;
  747. }
  748. ARG_CASE("-range" ARG_CASE_OR "-unitrange", 1) {
  749. double r;
  750. if (!parseDouble(r, argv[argPos++]))
  751. ABORT("Invalid range argument. Use -range <range> with a real number.");
  752. if (r == 0)
  753. ABORT("Range must be non-zero.");
  754. rangeMode = RANGE_UNIT;
  755. range = Range(r);
  756. continue;
  757. }
  758. ARG_CASE("-pxrange", 1) {
  759. double r;
  760. if (!parseDouble(r, argv[argPos++]))
  761. ABORT("Invalid range argument. Use -pxrange <range> with a real number.");
  762. if (r == 0)
  763. ABORT("Range must be non-zero.");
  764. rangeMode = RANGE_PX;
  765. pxRange = Range(r);
  766. continue;
  767. }
  768. ARG_CASE("-arange" ARG_CASE_OR "-aunitrange", 2) {
  769. double r0, r1;
  770. if (!(parseDouble(r0, argv[argPos++]) && parseDouble(r1, argv[argPos++])))
  771. ABORT("Invalid range arguments. Use -arange <minimum> <maximum> with two real numbers.");
  772. if (r0 == r1)
  773. ABORT("Range must be non-empty.");
  774. rangeMode = RANGE_UNIT;
  775. range = Range(r0, r1);
  776. continue;
  777. }
  778. ARG_CASE("-apxrange", 2) {
  779. double r0, r1;
  780. if (!(parseDouble(r0, argv[argPos++]) && parseDouble(r1, argv[argPos++])))
  781. ABORT("Invalid range arguments. Use -apxrange <minimum> <maximum> with two real numbers.");
  782. if (r0 == r1)
  783. ABORT("Range must be non-empty.");
  784. rangeMode = RANGE_PX;
  785. pxRange = Range(r0, r1);
  786. continue;
  787. }
  788. ARG_CASE("-scale", 1) {
  789. double s;
  790. if (!(parseDouble(s, argv[argPos++]) && s > 0))
  791. ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
  792. scale = s;
  793. scaleSpecified = true;
  794. continue;
  795. }
  796. ARG_CASE("-ascale", 2) {
  797. double sx, sy;
  798. if (!(parseDouble(sx, argv[argPos++]) && parseDouble(sy, argv[argPos++]) && sx > 0 && sy > 0))
  799. ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
  800. scale.set(sx, sy);
  801. scaleSpecified = true;
  802. continue;
  803. }
  804. ARG_CASE("-translate", 2) {
  805. double tx, ty;
  806. if (!(parseDouble(tx, argv[argPos++]) && parseDouble(ty, argv[argPos++])))
  807. ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
  808. translate.set(tx, ty);
  809. continue;
  810. }
  811. ARG_CASE("-angle", 1) {
  812. double at;
  813. if (!parseAngle(at, argv[argPos++]))
  814. 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.");
  815. angleThreshold = at;
  816. continue;
  817. }
  818. ARG_CASE("-errorcorrection", 1) {
  819. if (ARG_IS("disable") || ARG_IS("disabled") || ARG_IS("0") || ARG_IS("none") || ARG_IS("false")) {
  820. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
  821. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  822. } else if (ARG_IS("default") || ARG_IS("auto") || ARG_IS("auto-mixed") || ARG_IS("mixed")) {
  823. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  824. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE;
  825. } else if (ARG_IS("auto-fast") || ARG_IS("fast")) {
  826. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  827. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  828. } else if (ARG_IS("auto-full") || ARG_IS("full")) {
  829. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  830. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  831. } else if (ARG_IS("distance") || ARG_IS("distance-fast") || ARG_IS("indiscriminate") || ARG_IS("indiscriminate-fast")) {
  832. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
  833. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  834. } else if (ARG_IS("distance-full") || ARG_IS("indiscriminate-full")) {
  835. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
  836. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  837. } else if (ARG_IS("edge-fast")) {
  838. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
  839. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  840. } else if (ARG_IS("edge") || ARG_IS("edge-full")) {
  841. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
  842. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  843. } else if (ARG_IS("help")) {
  844. puts(errorCorrectionHelpText);
  845. return 0;
  846. } else
  847. fputs("Unknown error correction mode. Use -errorcorrection help for more information.\n", stderr);
  848. ++argPos;
  849. explicitErrorCorrectionMode = true;
  850. continue;
  851. }
  852. ARG_CASE("-errordeviationratio", 1) {
  853. double edr;
  854. if (!(parseDouble(edr, argv[argPos++]) && edr > 0))
  855. ABORT("Invalid error deviation ratio. Use -errordeviationratio <ratio> with a positive real number.");
  856. generatorConfig.errorCorrection.minDeviationRatio = edr;
  857. continue;
  858. }
  859. ARG_CASE("-errorimproveratio", 1) {
  860. double eir;
  861. if (!(parseDouble(eir, argv[argPos++]) && eir > 0))
  862. ABORT("Invalid error improvement ratio. Use -errorimproveratio <ratio> with a positive real number.");
  863. generatorConfig.errorCorrection.minImproveRatio = eir;
  864. continue;
  865. }
  866. ARG_CASE("-coloringstrategy" ARG_CASE_OR "-edgecoloring", 1) {
  867. if (ARG_IS("simple")) edgeColoring = &edgeColoringSimple;
  868. else if (ARG_IS("inktrap")) edgeColoring = &edgeColoringInkTrap;
  869. else if (ARG_IS("distance")) edgeColoring = &edgeColoringByDistance;
  870. else
  871. fputs("Unknown coloring strategy specified.\n", stderr);
  872. ++argPos;
  873. continue;
  874. }
  875. ARG_CASE("-edgecolors", 1) {
  876. static const char *allowed = " ?,cmwyCMWY";
  877. for (int i = 0; argv[argPos][i]; ++i) {
  878. for (int j = 0; allowed[j]; ++j)
  879. if (argv[argPos][i] == allowed[j])
  880. goto EDGE_COLOR_VERIFIED;
  881. 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.");
  882. EDGE_COLOR_VERIFIED:;
  883. }
  884. edgeAssignment = argv[argPos++];
  885. continue;
  886. }
  887. ARG_CASE("-distanceshift", 1) {
  888. double ds;
  889. if (!parseDouble(ds, argv[argPos++]))
  890. ABORT("Invalid distance shift. Use -distanceshift <shift> with a real value.");
  891. outputDistanceShift = (float) ds;
  892. continue;
  893. }
  894. ARG_CASE("-exportshape", 1) {
  895. shapeExport = argv[argPos++];
  896. continue;
  897. }
  898. ARG_CASE("-exportsvg", 1) {
  899. svgExport = argv[argPos++];
  900. continue;
  901. }
  902. ARG_CASE("-testrender", 3) {
  903. unsigned w, h;
  904. testRender = argv[argPos++];
  905. if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && (int) w > 0 && (int) h > 0))
  906. ABORT("Invalid arguments for test render. Use -testrender <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");
  907. testWidth = w, testHeight = h;
  908. continue;
  909. }
  910. ARG_CASE("-testrendermulti", 3) {
  911. unsigned w, h;
  912. testRenderMulti = argv[argPos++];
  913. if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && (int) w > 0 && (int) h > 0))
  914. ABORT("Invalid arguments for test render. Use -testrendermulti <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");
  915. testWidthM = w, testHeightM = h;
  916. continue;
  917. }
  918. ARG_CASE("-yflip", 0) {
  919. yFlip = true;
  920. continue;
  921. }
  922. ARG_CASE("-printmetrics", 0) {
  923. printMetrics = true;
  924. continue;
  925. }
  926. ARG_CASE("-estimateerror", 0) {
  927. estimateError = true;
  928. continue;
  929. }
  930. ARG_CASE("-keeporder", 0) {
  931. orientation = KEEP;
  932. continue;
  933. }
  934. ARG_CASE("-reverseorder", 0) {
  935. orientation = REVERSE;
  936. continue;
  937. }
  938. ARG_CASE("-guessorder", 0) {
  939. orientation = GUESS;
  940. continue;
  941. }
  942. ARG_CASE("-seed", 1) {
  943. if (!parseUnsignedLL(coloringSeed, argv[argPos++]))
  944. ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");
  945. continue;
  946. }
  947. ARG_CASE("-version", 0) {
  948. puts(versionText);
  949. return 0;
  950. }
  951. ARG_CASE("-help", 0) {
  952. puts(helpText);
  953. return 0;
  954. }
  955. fprintf(stderr, "Unknown setting or insufficient parameters: %s\n", argv[argPos++]);
  956. suggestHelp = true;
  957. }
  958. if (suggestHelp)
  959. fprintf(stderr, "Use -help for more information.\n");
  960. // Load input
  961. Shape::Bounds svgViewBox = { };
  962. double glyphAdvance = 0;
  963. if (!inputType || !input) {
  964. #ifdef MSDFGEN_EXTENSIONS
  965. #ifdef MSDFGEN_DISABLE_SVG
  966. ABORT("No input specified! Use -font <file.ttf/otf> <character code> or see -help.");
  967. #else
  968. ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
  969. #endif
  970. #else
  971. ABORT("No input specified! See -help.");
  972. #endif
  973. }
  974. Shape shape;
  975. switch (inputType) {
  976. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)
  977. case SVG: {
  978. int svgImportFlags = loadSvgShape(shape, svgViewBox, input);
  979. if (!(svgImportFlags&SVG_IMPORT_SUCCESS_FLAG))
  980. ABORT("Failed to load shape from SVG file.");
  981. if (svgImportFlags&SVG_IMPORT_PARTIAL_FAILURE_FLAG)
  982. fputs("Warning: Failed to load part of SVG file.\n", stderr);
  983. if (svgImportFlags&SVG_IMPORT_INCOMPLETE_FLAG)
  984. fputs("Warning: SVG file contains multiple paths or shapes but this version is only able to load one.\n", stderr);
  985. else if (svgImportFlags&SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG)
  986. fputs("Warning: SVG file likely contains elements that are unsupported.\n", stderr);
  987. if (svgImportFlags&SVG_IMPORT_TRANSFORMATION_IGNORED_FLAG)
  988. fputs("Warning: SVG path transformation ignored.\n", stderr);
  989. break;
  990. }
  991. #endif
  992. #ifdef MSDFGEN_EXTENSIONS
  993. case FONT: case VAR_FONT: {
  994. if (!glyphIndexSpecified && !unicode)
  995. 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).");
  996. struct FreetypeFontGuard {
  997. FreetypeHandle *ft;
  998. FontHandle *font;
  999. FreetypeFontGuard() : ft(), font() { }
  1000. ~FreetypeFontGuard() {
  1001. if (ft) {
  1002. if (font)
  1003. destroyFont(font);
  1004. deinitializeFreetype(ft);
  1005. }
  1006. }
  1007. } guard;
  1008. if (!(guard.ft = initializeFreetype()))
  1009. ABORT("Failed to initialize FreeType library.");
  1010. if (!(guard.font = (
  1011. #ifndef MSDFGEN_DISABLE_VARIABLE_FONTS
  1012. inputType == VAR_FONT ? loadVarFont(guard.ft, input) :
  1013. #endif
  1014. loadFont(guard.ft, input)
  1015. )))
  1016. ABORT("Failed to load font file.");
  1017. if (unicode)
  1018. getGlyphIndex(glyphIndex, guard.font, unicode);
  1019. if (!loadGlyph(shape, guard.font, glyphIndex, fontCoordinateScaling, &glyphAdvance))
  1020. ABORT("Failed to load glyph from font file.");
  1021. if (!fontCoordinateScalingSpecified && (!autoFrame || scaleSpecified || rangeMode == RANGE_UNIT || mode == METRICS || printMetrics || shapeExport || svgExport)) {
  1022. fputs(
  1023. "Warning: Using legacy font coordinate conversion for compatibility reasons.\n"
  1024. " The implicit scaling behavior will likely change in a future version resulting in different output.\n"
  1025. " To silence this warning, use one of the following options:\n"
  1026. " -noemnormalize to switch to the correct native font coordinates,\n"
  1027. " -emnormalize to switch to coordinates normalized to 1 em, or\n"
  1028. " -legacyfontscaling to keep current behavior and make sure it will not change.\n", stderr);
  1029. }
  1030. break;
  1031. }
  1032. #endif
  1033. case DESCRIPTION_ARG: {
  1034. if (!readShapeDescription(input, shape, &skipColoring))
  1035. ABORT("Parse error in shape description.");
  1036. break;
  1037. }
  1038. case DESCRIPTION_STDIN: {
  1039. if (!readShapeDescription(stdin, shape, &skipColoring))
  1040. ABORT("Parse error in shape description.");
  1041. break;
  1042. }
  1043. case DESCRIPTION_FILE: {
  1044. FILE *file = fopen(input, "r");
  1045. if (!file)
  1046. ABORT("Failed to load shape description file.");
  1047. bool readSuccessful = readShapeDescription(file, shape, &skipColoring);
  1048. fclose(file);
  1049. if (!readSuccessful)
  1050. ABORT("Parse error in shape description.");
  1051. break;
  1052. }
  1053. default:;
  1054. }
  1055. // Validate and normalize shape
  1056. if (!shape.validate())
  1057. ABORT("The geometry of the loaded shape is invalid.");
  1058. switch (geometryPreproc) {
  1059. case NO_PREPROCESS:
  1060. break;
  1061. case WINDING_PREPROCESS:
  1062. shape.orientContours();
  1063. break;
  1064. case FULL_PREPROCESS:
  1065. #ifdef MSDFGEN_USE_SKIA
  1066. if (!resolveShapeGeometry(shape))
  1067. fputs("Shape geometry preprocessing failed, skipping.\n", stderr);
  1068. else if (skipColoring) {
  1069. skipColoring = false;
  1070. fputs("Note: Input shape coloring won't be preserved due to geometry preprocessing.\n", stderr);
  1071. }
  1072. #else
  1073. ABORT("Shape geometry preprocessing (-preprocess) is not available in this version because the Skia library is not present.");
  1074. #endif
  1075. break;
  1076. }
  1077. shape.normalize();
  1078. if (yFlip)
  1079. shape.inverseYAxis = !shape.inverseYAxis;
  1080. double avgScale = .5*(scale.x+scale.y);
  1081. Shape::Bounds bounds = { };
  1082. if (autoFrame || mode == METRICS || printMetrics || orientation == GUESS || svgExport)
  1083. bounds = shape.getBounds();
  1084. if (outputDistanceShift) {
  1085. Range &rangeRef = rangeMode == RANGE_PX ? pxRange : range;
  1086. double rangeShift = -outputDistanceShift*(rangeRef.upper-rangeRef.lower);
  1087. rangeRef.lower += rangeShift;
  1088. rangeRef.upper += rangeShift;
  1089. }
  1090. // Auto-frame
  1091. if (autoFrame) {
  1092. double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
  1093. Vector2 frame(width, height);
  1094. if (!scaleSpecified) {
  1095. if (rangeMode == RANGE_UNIT)
  1096. l += range.lower, b += range.lower, r -= range.lower, t -= range.lower;
  1097. else
  1098. frame += 2*pxRange.lower;
  1099. }
  1100. if (l >= r || b >= t)
  1101. l = 0, b = 0, r = 1, t = 1;
  1102. if (frame.x <= 0 || frame.y <= 0)
  1103. ABORT("Cannot fit the specified pixel range.");
  1104. Vector2 dims(r-l, t-b);
  1105. if (scaleSpecified)
  1106. translate = .5*(frame/scale-dims)-Vector2(l, b);
  1107. else {
  1108. if (dims.x*frame.y < dims.y*frame.x) {
  1109. translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
  1110. scale = avgScale = frame.y/dims.y;
  1111. } else {
  1112. translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
  1113. scale = avgScale = frame.x/dims.x;
  1114. }
  1115. }
  1116. if (rangeMode == RANGE_PX && !scaleSpecified)
  1117. translate -= pxRange.lower/scale;
  1118. }
  1119. if (rangeMode == RANGE_PX)
  1120. range = pxRange/min(scale.x, scale.y);
  1121. // Print metrics
  1122. if (mode == METRICS || printMetrics) {
  1123. FILE *out = stdout;
  1124. if (mode == METRICS && outputSpecified)
  1125. out = fopen(output, "w");
  1126. if (!out)
  1127. ABORT("Failed to write output file.");
  1128. if (shape.inverseYAxis)
  1129. fprintf(out, "inverseY = true\n");
  1130. if (svgViewBox.l < svgViewBox.r && svgViewBox.b < svgViewBox.t)
  1131. fprintf(out, "view box = %.17g, %.17g, %.17g, %.17g\n", svgViewBox.l, svgViewBox.b, svgViewBox.r, svgViewBox.t);
  1132. if (bounds.l < bounds.r && bounds.b < bounds.t)
  1133. fprintf(out, "bounds = %.17g, %.17g, %.17g, %.17g\n", bounds.l, bounds.b, bounds.r, bounds.t);
  1134. if (glyphAdvance != 0)
  1135. fprintf(out, "advance = %.17g\n", glyphAdvance);
  1136. if (autoFrame) {
  1137. if (!scaleSpecified)
  1138. fprintf(out, "scale = %.17g\n", avgScale);
  1139. fprintf(out, "translate = %.17g, %.17g\n", translate.x, translate.y);
  1140. }
  1141. if (rangeMode == RANGE_PX)
  1142. fprintf(out, "range %.17g to %.17g\n", range.lower, range.upper);
  1143. if (mode == METRICS && outputSpecified)
  1144. fclose(out);
  1145. }
  1146. // Compute output
  1147. SDFTransformation transformation(Projection(scale, translate), range);
  1148. Bitmap<float, 1> sdf;
  1149. Bitmap<float, 3> msdf;
  1150. Bitmap<float, 4> mtsdf;
  1151. MSDFGeneratorConfig postErrorCorrectionConfig(generatorConfig);
  1152. if (scanlinePass) {
  1153. if (explicitErrorCorrectionMode && generatorConfig.errorCorrection.distanceCheckMode != ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE) {
  1154. const char *fallbackModeName = "unknown";
  1155. switch (generatorConfig.errorCorrection.mode) {
  1156. case ErrorCorrectionConfig::DISABLED: fallbackModeName = "disabled"; break;
  1157. case ErrorCorrectionConfig::INDISCRIMINATE: fallbackModeName = "distance-fast"; break;
  1158. case ErrorCorrectionConfig::EDGE_PRIORITY: fallbackModeName = "auto-fast"; break;
  1159. case ErrorCorrectionConfig::EDGE_ONLY: fallbackModeName = "edge-fast"; break;
  1160. }
  1161. fprintf(stderr, "Selected error correction mode not compatible with scanline pass, falling back to %s.\n", fallbackModeName);
  1162. }
  1163. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
  1164. postErrorCorrectionConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  1165. }
  1166. switch (mode) {
  1167. case SINGLE: {
  1168. sdf = Bitmap<float, 1>(width, height);
  1169. if (legacyMode)
  1170. generateSDF_legacy(sdf, shape, range, scale, translate);
  1171. else
  1172. generateSDF(sdf, shape, transformation, generatorConfig);
  1173. break;
  1174. }
  1175. case PERPENDICULAR: {
  1176. sdf = Bitmap<float, 1>(width, height);
  1177. if (legacyMode)
  1178. generatePSDF_legacy(sdf, shape, range, scale, translate);
  1179. else
  1180. generatePSDF(sdf, shape, transformation, generatorConfig);
  1181. break;
  1182. }
  1183. case MULTI: {
  1184. if (!skipColoring)
  1185. edgeColoring(shape, angleThreshold, coloringSeed);
  1186. if (edgeAssignment)
  1187. parseColoring(shape, edgeAssignment);
  1188. msdf = Bitmap<float, 3>(width, height);
  1189. if (legacyMode)
  1190. generateMSDF_legacy(msdf, shape, range, scale, translate, generatorConfig.errorCorrection);
  1191. else
  1192. generateMSDF(msdf, shape, transformation, generatorConfig);
  1193. break;
  1194. }
  1195. case MULTI_AND_TRUE: {
  1196. if (!skipColoring)
  1197. edgeColoring(shape, angleThreshold, coloringSeed);
  1198. if (edgeAssignment)
  1199. parseColoring(shape, edgeAssignment);
  1200. mtsdf = Bitmap<float, 4>(width, height);
  1201. if (legacyMode)
  1202. generateMTSDF_legacy(mtsdf, shape, range, scale, translate, generatorConfig.errorCorrection);
  1203. else
  1204. generateMTSDF(mtsdf, shape, transformation, generatorConfig);
  1205. break;
  1206. }
  1207. default:;
  1208. }
  1209. if (orientation == GUESS) {
  1210. // Get sign of signed distance outside bounds
  1211. Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);
  1212. double distance = SimpleTrueShapeDistanceFinder::oneShotDistance(shape, p);
  1213. orientation = distance <= 0 ? KEEP : REVERSE;
  1214. }
  1215. if (orientation == REVERSE) {
  1216. switch (mode) {
  1217. case SINGLE:
  1218. case PERPENDICULAR:
  1219. invertColor<1>(sdf);
  1220. break;
  1221. case MULTI:
  1222. invertColor<3>(msdf);
  1223. break;
  1224. case MULTI_AND_TRUE:
  1225. invertColor<4>(mtsdf);
  1226. break;
  1227. default:;
  1228. }
  1229. }
  1230. if (scanlinePass) {
  1231. switch (mode) {
  1232. case SINGLE:
  1233. case PERPENDICULAR:
  1234. distanceSignCorrection(sdf, shape, transformation, fillRule);
  1235. break;
  1236. case MULTI:
  1237. distanceSignCorrection(msdf, shape, transformation, fillRule);
  1238. msdfErrorCorrection(msdf, shape, transformation, postErrorCorrectionConfig);
  1239. break;
  1240. case MULTI_AND_TRUE:
  1241. distanceSignCorrection(mtsdf, shape, transformation, fillRule);
  1242. msdfErrorCorrection(mtsdf, shape, transformation, postErrorCorrectionConfig);
  1243. break;
  1244. default:;
  1245. }
  1246. }
  1247. // Save output
  1248. if (shapeExport) {
  1249. if (FILE *file = fopen(shapeExport, "w")) {
  1250. writeShapeDescription(file, shape);
  1251. fclose(file);
  1252. } else
  1253. fputs("Failed to write shape export file.\n", stderr);
  1254. }
  1255. if (svgExport) {
  1256. if (!saveSvgShape(shape, bounds, svgExport))
  1257. fputs("Failed to write shape SVG file.\n", stderr);
  1258. }
  1259. const char *error = NULL;
  1260. switch (mode) {
  1261. case SINGLE:
  1262. case PERPENDICULAR:
  1263. if ((error = writeOutput<1>(sdf, output, format))) {
  1264. fprintf(stderr, "%s\n", error);
  1265. return 1;
  1266. }
  1267. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1268. simulate8bit(sdf);
  1269. if (estimateError) {
  1270. double sdfError = estimateSDFError(sdf, shape, transformation, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1271. printf("SDF error ~ %e\n", sdfError);
  1272. }
  1273. if (testRenderMulti) {
  1274. Bitmap<float, 3> render(testWidthM, testHeightM);
  1275. renderSDF(render, sdf, avgScale*range);
  1276. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1277. fputs("Failed to write test render file.\n", stderr);
  1278. }
  1279. if (testRender) {
  1280. Bitmap<float, 1> render(testWidth, testHeight);
  1281. renderSDF(render, sdf, avgScale*range);
  1282. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1283. fputs("Failed to write test render file.\n", stderr);
  1284. }
  1285. break;
  1286. case MULTI:
  1287. if ((error = writeOutput<3>(msdf, output, format))) {
  1288. fprintf(stderr, "%s\n", error);
  1289. return 1;
  1290. }
  1291. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1292. simulate8bit(msdf);
  1293. if (estimateError) {
  1294. double sdfError = estimateSDFError(msdf, shape, transformation, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1295. printf("SDF error ~ %e\n", sdfError);
  1296. }
  1297. if (testRenderMulti) {
  1298. Bitmap<float, 3> render(testWidthM, testHeightM);
  1299. renderSDF(render, msdf, avgScale*range);
  1300. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1301. fputs("Failed to write test render file.\n", stderr);
  1302. }
  1303. if (testRender) {
  1304. Bitmap<float, 1> render(testWidth, testHeight);
  1305. renderSDF(render, msdf, avgScale*range);
  1306. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1307. fputs("Failed to write test render file.\n", stderr);
  1308. }
  1309. break;
  1310. case MULTI_AND_TRUE:
  1311. if ((error = writeOutput<4>(mtsdf, output, format))) {
  1312. fprintf(stderr, "%s\n", error);
  1313. return 1;
  1314. }
  1315. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1316. simulate8bit(mtsdf);
  1317. if (estimateError) {
  1318. double sdfError = estimateSDFError(mtsdf, shape, transformation, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1319. printf("SDF error ~ %e\n", sdfError);
  1320. }
  1321. if (testRenderMulti) {
  1322. Bitmap<float, 4> render(testWidthM, testHeightM);
  1323. renderSDF(render, mtsdf, avgScale*range);
  1324. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1325. fputs("Failed to write test render file.\n", stderr);
  1326. }
  1327. if (testRender) {
  1328. Bitmap<float, 1> render(testWidth, testHeight);
  1329. renderSDF(render, mtsdf, avgScale*range);
  1330. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1331. fputs("Failed to write test render file.\n", stderr);
  1332. }
  1333. break;
  1334. default:;
  1335. }
  1336. return 0;
  1337. }
  1338. #endif