main.cpp 52 KB

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