font_resource.vala 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /*
  2. * Copyright (c) 2012-2026 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. namespace Crown
  6. {
  7. [SimpleType]
  8. [CCode (cname = "GlyphData", has_type_id = false)]
  9. public struct GlyphData
  10. {
  11. int id;
  12. int x; ///< X-position inside the atlas.
  13. int y; ///< Y-position inside the atlas.
  14. int width; ///< In pixels.
  15. int height; ///< In pixels.
  16. int x_offset; ///< In pixels.
  17. int y_offset; ///< In pixels.
  18. int x_advance; ///< In pixels.
  19. }
  20. [SimpleType]
  21. [CCode (cname = "FontAtlas", has_type_id = false)]
  22. public struct FontAtlas
  23. {
  24. uchar* image_data;
  25. int size;
  26. GlyphData* glyphs;
  27. int num_glyphs;
  28. }
  29. [CCode (cname = "crown_font_atlas_free")]
  30. extern void font_atlas_free(FontAtlas* atlas);
  31. [CCode (cname = "crown_font_atlas_generate")]
  32. extern void* font_atlas_generate(string font_path, int font_size, int range_min, int range_max);
  33. public enum FontChars
  34. {
  35. ASCII_PRINTABLE,
  36. ASCII_NUMBERS,
  37. ASCII_LETTERS,
  38. CUSTOM_RANGE
  39. }
  40. // Copies @a src alpha to @a dst BRGA channels.
  41. public void copy_alpha_to_argb32(Cairo.ImageSurface dst, Cairo.ImageSurface src)
  42. {
  43. unowned uchar[] dst_data = dst.get_data();
  44. unowned uchar[] src_data = src.get_data();
  45. int src_stride = src.get_stride();
  46. int dst_stride = dst.get_stride();
  47. int width = src.get_width();
  48. int height = src.get_height();
  49. for (int yy = 0; yy < height; yy++) {
  50. for (int xx = 0; xx < width; xx++) {
  51. uint8 alpha = src_data[yy * src_stride + xx];
  52. dst_data[yy * dst_stride + 4 * xx + 0] = alpha; // B
  53. dst_data[yy * dst_stride + 4 * xx + 1] = alpha; // G
  54. dst_data[yy * dst_stride + 4 * xx + 2] = alpha; // R
  55. dst_data[yy * dst_stride + 4 * xx + 3] = alpha; // A
  56. }
  57. }
  58. }
  59. public class FontImportDialog : Gtk.Window
  60. {
  61. public Project _project;
  62. public string _destination_dir;
  63. public GLib.SList<string> _filenames;
  64. public unowned Import _import_result;
  65. public string _font_type;
  66. public FontAtlas* _font_atlas;
  67. public Cairo.ImageSurface _atlas;
  68. public PixbufView _drawing_area;
  69. public Gtk.ScrolledWindow _scrolled_window;
  70. public Gtk.Label _atlas_size;
  71. public Gtk.Label _font_path;
  72. public InputResourceBasename _font_name;
  73. public InputDouble _font_size;
  74. public Gtk.ComboBoxText _font_chars;
  75. public InputDouble _font_range_min;
  76. public InputDouble _font_range_max;
  77. public Gtk.Box _box;
  78. public Gtk.Button _import;
  79. public Gtk.Button _cancel;
  80. public Gtk.HeaderBar _header_bar;
  81. public void set_font_range(int min, int max)
  82. {
  83. if (min > max || max < min)
  84. max = min;
  85. _font_range_min.value = min;
  86. _font_range_max.value = max;
  87. }
  88. public int atlas_size()
  89. {
  90. return _font_atlas.size;
  91. }
  92. public void generate_atlas()
  93. {
  94. font_atlas_free(_font_atlas);
  95. _font_atlas = (FontAtlas*)font_atlas_generate(_font_path.get_text()
  96. , (int)_font_size.value
  97. , (int)_font_range_min.value
  98. , (int)_font_range_max.value
  99. );
  100. _atlas = new Cairo.ImageSurface.for_data((uchar[])_font_atlas.image_data
  101. , Cairo.Format.A8
  102. , _font_atlas.size
  103. , _font_atlas.size
  104. , Cairo.Format.A8.stride_for_width(_font_atlas.size)
  105. );
  106. _atlas_size.set_text(_atlas.get_width().to_string() + " × " + _atlas.get_height().to_string());
  107. _drawing_area.set_pixbuf(Gdk.pixbuf_get_from_surface(_atlas, 0, 0, _atlas.get_width(), _atlas.get_height()));
  108. _drawing_area._zoom = 1.0;
  109. }
  110. public GlyphData* glyph_data(int index)
  111. {
  112. return &_font_atlas.glyphs[index];
  113. }
  114. public void save_png(string path)
  115. {
  116. var argb32 = new Cairo.ImageSurface(Cairo.Format.ARGB32
  117. , _atlas.get_width()
  118. , _atlas.get_height()
  119. );
  120. copy_alpha_to_argb32(argb32, _atlas);
  121. argb32.write_to_png(path);
  122. }
  123. public FontImportDialog(Database database, string destination_dir, GLib.SList<string> filenames, Import import_result)
  124. {
  125. this.set_icon_name(CROWN_EDITOR_ICON_NAME);
  126. _project = database._project;
  127. _destination_dir = destination_dir;
  128. _filenames = new GLib.SList<string>();
  129. foreach (var f in filenames)
  130. _filenames.append(f);
  131. _import_result = import_result;
  132. string settings_path;
  133. string font_name;
  134. string font_path;
  135. {
  136. GLib.File file_src = File.new_for_path(filenames.nth_data(0));
  137. font_path = file_src.get_path();
  138. _font_type = font_path.substring(font_path.last_index_of_char('.') + 1
  139. , font_path.length - font_path.last_index_of_char('.') - 1
  140. );
  141. GLib.File file_dst = File.new_for_path(Path.build_filename(destination_dir, file_src.get_basename()));
  142. string resource_filename = _project.resource_filename(file_dst.get_path());
  143. string resource_path = ResourceId.normalize(resource_filename);
  144. string resource_name = ResourceId.name(resource_path);
  145. settings_path = _project.absolute_path(resource_name) + ".importer_settings";
  146. font_path = file_src.get_path();
  147. int last_slash = resource_name.last_index_of_char('/');
  148. if (last_slash == -1)
  149. font_name = resource_name;
  150. else
  151. font_name = resource_name.substring(last_slash + 1, resource_name.length - last_slash - 1);
  152. }
  153. _drawing_area = new PixbufView();
  154. _drawing_area._filter = Cairo.Filter.BILINEAR;
  155. _drawing_area._extend = Cairo.Extend.NONE;
  156. _scrolled_window = new Gtk.ScrolledWindow(null, null);
  157. _scrolled_window.min_content_width = 640;
  158. _scrolled_window.min_content_height = 640;
  159. _scrolled_window.add(_drawing_area);
  160. _atlas_size = new Gtk.Label("? × ?");
  161. _atlas_size.halign = Gtk.Align.START;
  162. _font_path = new Gtk.Label(font_path);
  163. _font_name = new InputResourceBasename(font_name);
  164. _font_name.sensitive = filenames.length() == 1;
  165. _font_size = new InputDouble(24.0, 1.0, 999.0);
  166. _font_range_min = new InputDouble(32.0, 0.0, int32.MAX);
  167. _font_range_min.sensitive = false;
  168. _font_range_max = new InputDouble(126.0, 0.0, int32.MAX);
  169. _font_range_max.sensitive = false;
  170. _font_chars = new Gtk.ComboBoxText();
  171. _font_chars.append_text("ASCII Printable"); // FontChars.ASCII_PRINTABLE
  172. _font_chars.append_text("ASCII Numbers"); // FontChars.ASCII_NUMBERS
  173. _font_chars.append_text("ASCII Letters"); // FontChars.ASCII_LETTERS
  174. _font_chars.append_text("Custom Range"); // FontChars.CUSTOM_RANGE
  175. _font_chars.active = FontChars.ASCII_PRINTABLE;
  176. _font_chars.changed.connect(() => {
  177. // code-format off
  178. switch (_font_chars.active) {
  179. case FontChars.ASCII_PRINTABLE:
  180. set_font_range(32, 126);
  181. _font_range_min.sensitive = false;
  182. _font_range_max.sensitive = false;
  183. break;
  184. case FontChars.ASCII_NUMBERS:
  185. set_font_range(48, 57);
  186. _font_range_min.sensitive = false;
  187. _font_range_max.sensitive = false;
  188. break;
  189. case FontChars.ASCII_LETTERS:
  190. set_font_range(97, 122);
  191. _font_range_min.sensitive = false;
  192. _font_range_max.sensitive = false;
  193. break;
  194. case FontChars.CUSTOM_RANGE:
  195. _font_range_min.sensitive = true;
  196. _font_range_max.sensitive = true;
  197. break;
  198. default:
  199. break;
  200. }
  201. // code-format on
  202. generate_atlas();
  203. _drawing_area.queue_draw();
  204. });
  205. _font_size.value_changed.connect(() => {
  206. generate_atlas();
  207. _drawing_area.queue_draw();
  208. });
  209. _font_range_min.value_changed.connect(() => {
  210. set_font_range((int)_font_range_min.value, (int)_font_range_max.value);
  211. generate_atlas();
  212. _drawing_area.queue_draw();
  213. });
  214. _font_range_max.value_changed.connect(() => {
  215. set_font_range((int)_font_range_min.value, (int)_font_range_max.value);
  216. generate_atlas();
  217. _drawing_area.queue_draw();
  218. });
  219. PropertyGridSet sprite_set = new PropertyGridSet();
  220. PropertyGrid cv;
  221. cv = new PropertyGrid();
  222. cv.add_row("Source", _font_path, "Source font path.");
  223. sprite_set.add_property_grid(cv, "File");
  224. cv = new PropertyGrid();
  225. cv.add_row("Name", _font_name, "Name of the imported resource.");
  226. cv.add_row("Atlas size", _atlas_size, "Resolution of the generated texture.");
  227. cv.add_row("Size", _font_size, "Size of characters.");
  228. cv.add_row("Charset", _font_chars, "Generate characters within this set.");
  229. cv.add_row("Range min", _font_range_min, "First character to generate (included).");
  230. cv.add_row("Range max", _font_range_max, "Last character to generate (included).");
  231. sprite_set.add_property_grid(cv, "Font");
  232. Gtk.Box box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 0);
  233. box.pack_start(_scrolled_window, true, true);
  234. Gtk.Paned pane;
  235. pane = new Gtk.Paned(Gtk.Orientation.HORIZONTAL);
  236. pane.pack1(box, false, false);
  237. pane.pack2(sprite_set, true, false);
  238. this.destroy.connect(on_destroy);
  239. this.map_event.connect(on_map_event);
  240. _box = new Gtk.Box(Gtk.Orientation.VERTICAL, 0);
  241. _box.pack_start(pane, false, false);
  242. _cancel = new Gtk.Button.with_label("Cancel");
  243. _cancel.clicked.connect(() => {
  244. close();
  245. });
  246. _import = new Gtk.Button.with_label("Import");
  247. _import.get_style_context().add_class("suggested-action");
  248. _import.clicked.connect(on_import);
  249. _header_bar = new Gtk.HeaderBar();
  250. _header_bar.title = "Import Font...";
  251. _header_bar.show_close_button = true;
  252. _header_bar.pack_start(_cancel);
  253. _header_bar.pack_end(_import);
  254. this.set_titlebar(_header_bar);
  255. this.add(_box);
  256. if (File.new_for_path(settings_path).query_exists()) {
  257. try {
  258. decode(SJSON.load_from_path(settings_path));
  259. } catch (JsonSyntaxError e) {
  260. // No-op.
  261. }
  262. }
  263. generate_atlas();
  264. }
  265. public bool on_map_event(Gdk.EventAny ev)
  266. {
  267. _font_name.grab_focus();
  268. return Gdk.EVENT_PROPAGATE;
  269. }
  270. public void on_destroy()
  271. {
  272. font_atlas_free(_font_atlas);
  273. }
  274. public void decode(Hashtable obj)
  275. {
  276. _font_chars.active = FontChars.CUSTOM_RANGE;
  277. _font_size.value = (double)obj["size"];
  278. set_font_range((int)(double)obj["range_min"], (int)(double)obj["range_max"]);
  279. }
  280. public Hashtable encode()
  281. {
  282. Hashtable obj = new Hashtable();
  283. obj["size"] = _font_size.value;
  284. obj["range_min"] = _font_range_min.value;
  285. obj["range_max"] = _font_range_max.value;
  286. return obj;
  287. }
  288. public void on_import()
  289. {
  290. _import_result(FontResource.do_import(this, _project, _destination_dir, _filenames));
  291. destroy();
  292. }
  293. }
  294. public class FontResource
  295. {
  296. public static ImportResult do_import(FontImportDialog dlg, Project project, string destination_dir, GLib.SList<string> filenames)
  297. {
  298. int size = (int)dlg.atlas_size();
  299. int font_size = (int)dlg._font_size.value;
  300. foreach (unowned string filename_i in filenames) {
  301. GLib.File file_src = File.new_for_path(filename_i);
  302. string resource_basename;
  303. if (filenames.length() == 1)
  304. resource_basename = dlg._font_name.value + "." + dlg._font_type;
  305. else
  306. resource_basename = file_src.get_basename();
  307. GLib.File file_dst = File.new_for_path(Path.build_filename(destination_dir, resource_basename));
  308. string resource_filename = project.resource_filename(file_dst.get_path());
  309. string resource_path = ResourceId.normalize(resource_filename);
  310. string resource_name = ResourceId.name(resource_path);
  311. try {
  312. SJSON.save(dlg.encode(), project.absolute_path(resource_name) + ".importer_settings");
  313. } catch (JsonWriteError e) {
  314. return ImportResult.ERROR;
  315. }
  316. // Save .png atlas.
  317. dlg.save_png(project.absolute_path(resource_name) + ".png");
  318. Database db = new Database(project);
  319. // Generate .texture resource.
  320. var texture_resource = TextureResource.font_atlas(db, Guid.new_guid(), resource_name + ".png");
  321. if (texture_resource.save(project, resource_name) != 0)
  322. return ImportResult.ERROR;
  323. db.reset();
  324. // Generate .material resource.
  325. MaterialResource material_resource = MaterialResource.gui(db, Guid.new_guid(), resource_name);
  326. if (material_resource.save(project, resource_name) != 0)
  327. return ImportResult.ERROR;
  328. // Generate .font resource.
  329. Guid font_id = Guid.new_guid();
  330. db.create(font_id, OBJECT_TYPE_FONT);
  331. db.set_double(font_id, "size", size);
  332. db.set_double(font_id, "font_size", font_size);
  333. for (int ii = 0; ii < dlg._font_range_max.value - dlg._font_range_min.value + 1; ++ii) {
  334. GlyphData* gd = dlg.glyph_data(ii);
  335. Guid glyph_id = Guid.new_guid();
  336. db.create(glyph_id, "font_glyph");
  337. db.set_double(glyph_id, "cp", gd->id);
  338. db.set_double(glyph_id, "x", gd->x);
  339. db.set_double(glyph_id, "y", gd->y);
  340. db.set_double(glyph_id, "width", gd->width);
  341. db.set_double(glyph_id, "height", gd->height);
  342. db.set_double(glyph_id, "x_offset", gd->x_offset);
  343. db.set_double(glyph_id, "y_offset", gd->y_offset);
  344. db.set_double(glyph_id, "x_advance", gd->x_advance);
  345. db.add_to_set(font_id, "glyphs", glyph_id);
  346. }
  347. if (db.save(project.absolute_path(resource_name) + ".font", font_id) != 0)
  348. return ImportResult.ERROR;
  349. }
  350. dlg.destroy();
  351. return ImportResult.SUCCESS;
  352. }
  353. public static void import(Import import_result, Database database, string destination_dir, SList<string> filenames, Gtk.Window? parent_window)
  354. {
  355. FontImportDialog dlg = new FontImportDialog(database, destination_dir, filenames, import_result);
  356. dlg.set_transient_for(parent_window);
  357. dlg.set_modal(true);
  358. dlg.show_all();
  359. }
  360. }
  361. } /* namespace Crown */