FontFaceHandleDefault.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "FontFaceHandleDefault.h"
  29. #include "../../../Include/RmlUi/Core/Profiling.h"
  30. #include "../../../Include/RmlUi/Core/StringUtilities.h"
  31. #include "../TextureLayout.h"
  32. #include "FontFaceLayer.h"
  33. #include "FontProvider.h"
  34. #include "FreeTypeInterface.h"
  35. #include <algorithm>
  36. #include <numeric>
  37. namespace Rml {
  38. static constexpr char32_t KerningCache_AsciiSubsetBegin = 32;
  39. static constexpr char32_t KerningCache_AsciiSubsetLast = 126;
  40. FontFaceHandleDefault::FontFaceHandleDefault()
  41. {
  42. base_layer = nullptr;
  43. metrics = {};
  44. ft_face = 0;
  45. }
  46. FontFaceHandleDefault::~FontFaceHandleDefault()
  47. {
  48. glyphs.clear();
  49. layers.clear();
  50. }
  51. bool FontFaceHandleDefault::Initialize(FontFaceHandleFreetype face, int font_size, bool load_default_glyphs)
  52. {
  53. ft_face = face;
  54. RMLUI_ASSERTMSG(layer_configurations.empty(), "Initialize must only be called once.");
  55. if (!FreeType::InitialiseFaceHandle(ft_face, font_size, glyphs, metrics, load_default_glyphs))
  56. return false;
  57. has_kerning = FreeType::HasKerning(ft_face);
  58. FillKerningPairCache();
  59. // Generate the default layer and layer configuration.
  60. base_layer = GetOrCreateLayer(nullptr);
  61. layer_configurations.push_back(LayerConfiguration{base_layer});
  62. return true;
  63. }
  64. const FontMetrics& FontFaceHandleDefault::GetFontMetrics() const
  65. {
  66. return metrics;
  67. }
  68. const FontGlyphMap& FontFaceHandleDefault::GetGlyphs() const
  69. {
  70. return glyphs;
  71. }
  72. int FontFaceHandleDefault::GetStringWidth(const String& string, float letter_spacing, Character prior_character)
  73. {
  74. RMLUI_ZoneScoped;
  75. bool has_set_size = false;
  76. int width = 0;
  77. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  78. {
  79. Character character = *it_string;
  80. const FontGlyph* glyph = GetOrAppendGlyph(character);
  81. if (!glyph)
  82. continue;
  83. // Adjust the cursor for the kerning between this character and the previous one.
  84. width += GetKerning(prior_character, character, has_set_size);
  85. // Adjust the cursor for this character's advance.
  86. width += glyph->advance;
  87. width += (int)letter_spacing;
  88. prior_character = character;
  89. }
  90. return Math::Max(width, 0);
  91. }
  92. int FontFaceHandleDefault::GenerateLayerConfiguration(const FontEffectList& font_effects)
  93. {
  94. if (font_effects.empty())
  95. return 0;
  96. // Check each existing configuration for a match with this arrangement of effects.
  97. int configuration_index = 1;
  98. for (; configuration_index < (int)layer_configurations.size(); ++configuration_index)
  99. {
  100. const LayerConfiguration& configuration = layer_configurations[configuration_index];
  101. // Check the size is correct. For a match, there should be one layer in the configuration
  102. // plus an extra for the base layer.
  103. if (configuration.size() != font_effects.size() + 1)
  104. continue;
  105. // Check through each layer, checking it was created by the same effect as the one we're
  106. // checking.
  107. size_t effect_index = 0;
  108. for (size_t i = 0; i < configuration.size(); ++i)
  109. {
  110. // Skip the base layer ...
  111. if (configuration[i]->GetFontEffect() == nullptr)
  112. continue;
  113. // If the ith layer's effect doesn't match the equivalent effect, then this
  114. // configuration can't match.
  115. if (configuration[i]->GetFontEffect() != font_effects[effect_index].get())
  116. break;
  117. // Check the next one ...
  118. ++effect_index;
  119. }
  120. if (effect_index == font_effects.size())
  121. return configuration_index;
  122. }
  123. // No match, so we have to generate a new layer configuration.
  124. layer_configurations.push_back(LayerConfiguration());
  125. LayerConfiguration& layer_configuration = layer_configurations.back();
  126. bool added_base_layer = false;
  127. for (size_t i = 0; i < font_effects.size(); ++i)
  128. {
  129. if (!added_base_layer && font_effects[i]->GetLayer() == FontEffect::Layer::Front)
  130. {
  131. layer_configuration.push_back(base_layer);
  132. added_base_layer = true;
  133. }
  134. FontFaceLayer* new_layer = GetOrCreateLayer(font_effects[i]);
  135. layer_configuration.push_back(new_layer);
  136. }
  137. // Add the base layer now if we still haven't added it.
  138. if (!added_base_layer)
  139. layer_configuration.push_back(base_layer);
  140. return (int)(layer_configurations.size() - 1);
  141. }
  142. bool FontFaceHandleDefault::GenerateLayerTexture(Vector<byte>& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect,
  143. int texture_id, int handle_version) const
  144. {
  145. if (handle_version != version)
  146. {
  147. RMLUI_ERRORMSG("While generating font layer texture: Handle version mismatch in texture vs font-face.");
  148. return false;
  149. }
  150. auto it = std::find_if(layers.begin(), layers.end(), [font_effect](const EffectLayerPair& pair) { return pair.font_effect == font_effect; });
  151. if (it == layers.end())
  152. {
  153. RMLUI_ERRORMSG("While generating font layer texture: Layer id not found.");
  154. return false;
  155. }
  156. return it->layer->GenerateTexture(texture_data, texture_dimensions, texture_id, glyphs);
  157. }
  158. int FontFaceHandleDefault::GenerateString(RenderManager& render_manager, TexturedMeshList& mesh_list, const String& string, const Vector2f position,
  159. const ColourbPremultiplied colour, const float opacity, const float letter_spacing, const int layer_configuration_index)
  160. {
  161. RMLUI_ASSERT(layer_configuration_index >= 0);
  162. RMLUI_ASSERT(layer_configuration_index < (int)layer_configurations.size());
  163. int geometry_index = 0;
  164. int line_width = 0;
  165. bool has_set_size = false;
  166. UpdateLayersOnDirty();
  167. // Fetch the requested configuration and generate the geometry for each one.
  168. const LayerConfiguration& layer_configuration = layer_configurations[layer_configuration_index];
  169. // Each texture represents one geometry.
  170. const int num_geometries = std::accumulate(layer_configuration.begin(), layer_configuration.end(), 0,
  171. [](int sum, const FontFaceLayer* layer) { return sum + layer->GetNumTextures(); });
  172. mesh_list.resize(num_geometries);
  173. for (size_t layer_index = 0; layer_index < layer_configuration.size(); ++layer_index)
  174. {
  175. FontFaceLayer* layer = layer_configuration[layer_index];
  176. ColourbPremultiplied layer_colour;
  177. if (layer == base_layer)
  178. layer_colour = colour;
  179. else
  180. layer_colour = layer->GetColour(opacity);
  181. const int num_textures = layer->GetNumTextures();
  182. if (num_textures == 0)
  183. continue;
  184. RMLUI_ASSERT(geometry_index + num_textures <= (int)mesh_list.size());
  185. line_width = 0;
  186. Character prior_character = Character::Null;
  187. // Set the mesh and textures to the geometries.
  188. for (int tex_index = 0; tex_index < num_textures; ++tex_index)
  189. mesh_list[geometry_index + tex_index].texture = layer->GetTexture(render_manager, tex_index);
  190. mesh_list[geometry_index].mesh.indices.reserve(string.size() * 6);
  191. mesh_list[geometry_index].mesh.vertices.reserve(string.size() * 4);
  192. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  193. {
  194. Character character = *it_string;
  195. const FontGlyph* glyph = GetOrAppendGlyph(character);
  196. if (!glyph)
  197. continue;
  198. // Adjust the cursor for the kerning between this character and the previous one.
  199. line_width += GetKerning(prior_character, character, has_set_size);
  200. ColourbPremultiplied glyph_color = layer_colour;
  201. // Use white vertex colors on RGB glyphs.
  202. if (layer == base_layer && glyph->color_format == ColorFormat::RGBA8)
  203. glyph_color = ColourbPremultiplied(layer_colour.alpha, layer_colour.alpha);
  204. layer->GenerateGeometry(&mesh_list[geometry_index], character, Vector2f(position.x + line_width, position.y), glyph_color);
  205. line_width += glyph->advance;
  206. line_width += (int)letter_spacing;
  207. prior_character = character;
  208. }
  209. geometry_index += num_textures;
  210. }
  211. return Math::Max(line_width, 0);
  212. }
  213. bool FontFaceHandleDefault::UpdateLayersOnDirty()
  214. {
  215. bool result = false;
  216. // If we are dirty, regenerate all the layers and increment the version
  217. if (is_layers_dirty && base_layer)
  218. {
  219. is_layers_dirty = false;
  220. ++version;
  221. // Regenerate all the layers.
  222. // Note: The layer regeneration needs to happen in the order in which the layers were created,
  223. // otherwise we may end up cloning a layer which has not yet been regenerated. This means trouble!
  224. for (auto& pair : layers)
  225. {
  226. GenerateLayer(pair.layer.get());
  227. }
  228. result = true;
  229. }
  230. return result;
  231. }
  232. int FontFaceHandleDefault::GetVersion() const
  233. {
  234. return version;
  235. }
  236. bool FontFaceHandleDefault::AppendGlyph(Character character)
  237. {
  238. bool result = FreeType::AppendGlyph(ft_face, metrics.size, character, glyphs);
  239. return result;
  240. }
  241. void FontFaceHandleDefault::FillKerningPairCache()
  242. {
  243. if (!has_kerning)
  244. return;
  245. for (char32_t i = KerningCache_AsciiSubsetBegin; i <= KerningCache_AsciiSubsetLast; i++)
  246. {
  247. for (char32_t j = KerningCache_AsciiSubsetBegin; j <= KerningCache_AsciiSubsetLast; j++)
  248. {
  249. const bool first_iteration = (i == KerningCache_AsciiSubsetBegin && j == KerningCache_AsciiSubsetBegin);
  250. // Fetch the kerning from the font face. Submit zero font size on subsequent iterations for performance reasons.
  251. const int kerning = FreeType::GetKerning(ft_face, first_iteration ? metrics.size : 0, Character(i), Character(j));
  252. if (kerning != 0)
  253. {
  254. kerning_pair_cache.emplace(AsciiPair((i << 8) | j), KerningIntType(kerning));
  255. }
  256. }
  257. }
  258. }
  259. int FontFaceHandleDefault::GetKerning(Character lhs, Character rhs, bool& has_set_size) const
  260. {
  261. static_assert(' ' == 32, "Only ASCII/UTF8 character set supported.");
  262. // Check if we have no kerning, or if we have a control character.
  263. if (!has_kerning || char32_t(lhs) < ' ' || char32_t(rhs) < ' ')
  264. return 0;
  265. // See if the kerning pair has been cached.
  266. const bool lhs_in_cache = (char32_t(lhs) >= KerningCache_AsciiSubsetBegin && char32_t(lhs) <= KerningCache_AsciiSubsetLast);
  267. const bool rhs_in_cache = (char32_t(rhs) >= KerningCache_AsciiSubsetBegin && char32_t(rhs) <= KerningCache_AsciiSubsetLast);
  268. if (lhs_in_cache && rhs_in_cache)
  269. {
  270. const auto it = kerning_pair_cache.find(AsciiPair((int(lhs) << 8) | int(rhs)));
  271. if (it != kerning_pair_cache.end())
  272. {
  273. return it->second;
  274. }
  275. return 0;
  276. }
  277. // Fetch it from the font face instead.
  278. const int result = FreeType::GetKerning(ft_face, has_set_size ? 0 : metrics.size, lhs, rhs);
  279. // This is purely an optimization to avoid repeatedly setting the font size in FreeType, which can be a measurable performance hit.
  280. has_set_size = true;
  281. return result;
  282. }
  283. const FontGlyph* FontFaceHandleDefault::GetOrAppendGlyph(Character& character, bool look_in_fallback_fonts)
  284. {
  285. // Don't try to render control characters
  286. if ((char32_t)character < (char32_t)' ')
  287. return nullptr;
  288. auto it_glyph = glyphs.find(character);
  289. if (it_glyph == glyphs.end())
  290. {
  291. bool result = AppendGlyph(character);
  292. if (result)
  293. {
  294. it_glyph = glyphs.find(character);
  295. if (it_glyph == glyphs.end())
  296. {
  297. RMLUI_ERROR;
  298. return nullptr;
  299. }
  300. is_layers_dirty = true;
  301. }
  302. else if (look_in_fallback_fonts)
  303. {
  304. const int num_fallback_faces = FontProvider::CountFallbackFontFaces();
  305. for (int i = 0; i < num_fallback_faces; i++)
  306. {
  307. FontFaceHandleDefault* fallback_face = FontProvider::GetFallbackFontFace(i, metrics.size);
  308. if (!fallback_face || fallback_face == this)
  309. continue;
  310. const FontGlyph* glyph = fallback_face->GetOrAppendGlyph(character, false);
  311. if (glyph)
  312. {
  313. // Insert the new glyph into our own set of glyphs
  314. auto pair = glyphs.emplace(character, glyph->WeakCopy());
  315. it_glyph = pair.first;
  316. if (pair.second)
  317. is_layers_dirty = true;
  318. break;
  319. }
  320. }
  321. // If we still have not found a glyph, use the replacement character.
  322. if (it_glyph == glyphs.end())
  323. {
  324. character = Character::Replacement;
  325. it_glyph = glyphs.find(character);
  326. if (it_glyph == glyphs.end())
  327. return nullptr;
  328. }
  329. }
  330. else
  331. {
  332. return nullptr;
  333. }
  334. }
  335. const FontGlyph* glyph = &it_glyph->second;
  336. return glyph;
  337. }
  338. FontFaceLayer* FontFaceHandleDefault::GetOrCreateLayer(const SharedPtr<const FontEffect>& font_effect)
  339. {
  340. // Search for the font effect layer first, it may have been instanced before as part of a different configuration.
  341. const FontEffect* font_effect_ptr = font_effect.get();
  342. auto it =
  343. std::find_if(layers.begin(), layers.end(), [font_effect_ptr](const EffectLayerPair& pair) { return pair.font_effect == font_effect_ptr; });
  344. if (it != layers.end())
  345. return it->layer.get();
  346. // No existing effect matches, generate a new layer for the effect.
  347. layers.push_back(EffectLayerPair{font_effect_ptr, nullptr});
  348. auto& layer = layers.back().layer;
  349. layer = MakeUnique<FontFaceLayer>(font_effect);
  350. GenerateLayer(layer.get());
  351. return layer.get();
  352. }
  353. bool FontFaceHandleDefault::GenerateLayer(FontFaceLayer* layer)
  354. {
  355. RMLUI_ASSERT(layer);
  356. const FontEffect* font_effect = layer->GetFontEffect();
  357. bool result = false;
  358. if (!font_effect)
  359. {
  360. result = layer->Generate(this);
  361. }
  362. else
  363. {
  364. // Determine which, if any, layer the new layer should copy its geometry and textures from.
  365. FontFaceLayer* clone = nullptr;
  366. bool clone_glyph_origins = true;
  367. String generation_key;
  368. size_t fingerprint = font_effect->GetFingerprint();
  369. if (!font_effect->HasUniqueTexture())
  370. {
  371. clone = base_layer;
  372. clone_glyph_origins = false;
  373. }
  374. else
  375. {
  376. auto cache_iterator = layer_cache.find(fingerprint);
  377. if (cache_iterator != layer_cache.end() && cache_iterator->second != layer)
  378. clone = cache_iterator->second;
  379. }
  380. // Create a new layer.
  381. result = layer->Generate(this, clone, clone_glyph_origins);
  382. // Cache the layer in the layer cache if it generated its own textures (ie, didn't clone).
  383. if (!clone)
  384. layer_cache[fingerprint] = layer;
  385. }
  386. return result;
  387. }
  388. } // namespace Rml