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/StringUtilities.h"
  30. #include "../TextureLayout.h"
  31. #include "FontFaceLayer.h"
  32. #include "FontProvider.h"
  33. #include "FreeTypeInterface.h"
  34. #include <algorithm>
  35. namespace Rml {
  36. static constexpr char32_t KerningCache_AsciiSubsetBegin = 32;
  37. static constexpr char32_t KerningCache_AsciiSubsetLast = 126;
  38. FontFaceHandleDefault::FontFaceHandleDefault()
  39. {
  40. base_layer = nullptr;
  41. metrics = {};
  42. ft_face = 0;
  43. }
  44. FontFaceHandleDefault::~FontFaceHandleDefault()
  45. {
  46. glyphs.clear();
  47. layers.clear();
  48. }
  49. bool FontFaceHandleDefault::Initialize(FontFaceHandleFreetype face, int font_size, bool load_default_glyphs)
  50. {
  51. ft_face = face;
  52. RMLUI_ASSERTMSG(layer_configurations.empty(), "Initialize must only be called once.");
  53. if (!FreeType::InitialiseFaceHandle(ft_face, font_size, glyphs, metrics, load_default_glyphs))
  54. return false;
  55. has_kerning = FreeType::HasKerning(ft_face);
  56. FillKerningPairCache();
  57. // Generate the default layer and layer configuration.
  58. base_layer = GetOrCreateLayer(nullptr);
  59. layer_configurations.push_back(LayerConfiguration{base_layer});
  60. return true;
  61. }
  62. const FontMetrics& FontFaceHandleDefault::GetFontMetrics() const
  63. {
  64. return metrics;
  65. }
  66. const FontGlyphMap& FontFaceHandleDefault::GetGlyphs() const
  67. {
  68. return glyphs;
  69. }
  70. int FontFaceHandleDefault::GetStringWidth(const String& string, float letter_spacing, Character prior_character)
  71. {
  72. int width = 0;
  73. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  74. {
  75. Character character = *it_string;
  76. const FontGlyph* glyph = GetOrAppendGlyph(character);
  77. if (!glyph)
  78. continue;
  79. // Adjust the cursor for the kerning between this character and the previous one.
  80. width += GetKerning(prior_character, character);
  81. // Adjust the cursor for this character's advance.
  82. width += glyph->advance;
  83. width += (int)letter_spacing;
  84. prior_character = character;
  85. }
  86. return Math::Max(width, 0);
  87. }
  88. int FontFaceHandleDefault::GenerateLayerConfiguration(const FontEffectList& font_effects)
  89. {
  90. if (font_effects.empty())
  91. return 0;
  92. // Check each existing configuration for a match with this arrangement of effects.
  93. int configuration_index = 1;
  94. for (; configuration_index < (int)layer_configurations.size(); ++configuration_index)
  95. {
  96. const LayerConfiguration& configuration = layer_configurations[configuration_index];
  97. // Check the size is correct. For a match, there should be one layer in the configuration
  98. // plus an extra for the base layer.
  99. if (configuration.size() != font_effects.size() + 1)
  100. continue;
  101. // Check through each layer, checking it was created by the same effect as the one we're
  102. // checking.
  103. size_t effect_index = 0;
  104. for (size_t i = 0; i < configuration.size(); ++i)
  105. {
  106. // Skip the base layer ...
  107. if (configuration[i]->GetFontEffect() == nullptr)
  108. continue;
  109. // If the ith layer's effect doesn't match the equivalent effect, then this
  110. // configuration can't match.
  111. if (configuration[i]->GetFontEffect() != font_effects[effect_index].get())
  112. break;
  113. // Check the next one ...
  114. ++effect_index;
  115. }
  116. if (effect_index == font_effects.size())
  117. return configuration_index;
  118. }
  119. // No match, so we have to generate a new layer configuration.
  120. layer_configurations.push_back(LayerConfiguration());
  121. LayerConfiguration& layer_configuration = layer_configurations.back();
  122. bool added_base_layer = false;
  123. for (size_t i = 0; i < font_effects.size(); ++i)
  124. {
  125. if (!added_base_layer && font_effects[i]->GetLayer() == FontEffect::Layer::Front)
  126. {
  127. layer_configuration.push_back(base_layer);
  128. added_base_layer = true;
  129. }
  130. FontFaceLayer* new_layer = GetOrCreateLayer(font_effects[i]);
  131. layer_configuration.push_back(new_layer);
  132. }
  133. // Add the base layer now if we still haven't added it.
  134. if (!added_base_layer)
  135. layer_configuration.push_back(base_layer);
  136. return (int)(layer_configurations.size() - 1);
  137. }
  138. bool FontFaceHandleDefault::GenerateLayerTexture(UniquePtr<const byte[]>& texture_data, Vector2i& texture_dimensions, const FontEffect* font_effect,
  139. int texture_id, int handle_version) const
  140. {
  141. if (handle_version != version)
  142. {
  143. RMLUI_ERRORMSG("While generating font layer texture: Handle version mismatch in texture vs font-face.");
  144. return false;
  145. }
  146. auto it = std::find_if(layers.begin(), layers.end(), [font_effect](const EffectLayerPair& pair) { return pair.font_effect == font_effect; });
  147. if (it == layers.end())
  148. {
  149. RMLUI_ERRORMSG("While generating font layer texture: Layer id not found.");
  150. return false;
  151. }
  152. return it->layer->GenerateTexture(texture_data, texture_dimensions, texture_id, glyphs);
  153. }
  154. int FontFaceHandleDefault::GenerateString(GeometryList& geometry, const String& string, const Vector2f position, const Colourb colour,
  155. const float opacity, const float letter_spacing, const int layer_configuration_index)
  156. {
  157. int geometry_index = 0;
  158. int line_width = 0;
  159. RMLUI_ASSERT(layer_configuration_index >= 0);
  160. RMLUI_ASSERT(layer_configuration_index < (int)layer_configurations.size());
  161. UpdateLayersOnDirty();
  162. // Fetch the requested configuration and generate the geometry for each one.
  163. const LayerConfiguration& layer_configuration = layer_configurations[layer_configuration_index];
  164. // Reserve for the common case of one texture per layer.
  165. geometry.reserve(layer_configuration.size());
  166. for (size_t i = 0; i < layer_configuration.size(); ++i)
  167. {
  168. FontFaceLayer* layer = layer_configuration[i];
  169. Colourb layer_colour;
  170. if (layer == base_layer)
  171. {
  172. layer_colour = colour;
  173. }
  174. else
  175. {
  176. layer_colour = layer->GetColour();
  177. if (opacity < 1.f)
  178. layer_colour.alpha = byte(opacity * float(layer_colour.alpha));
  179. }
  180. const int num_textures = layer->GetNumTextures();
  181. if (num_textures == 0)
  182. continue;
  183. // Resize the geometry list if required.
  184. if ((int)geometry.size() < geometry_index + num_textures)
  185. geometry.resize(geometry_index + num_textures);
  186. RMLUI_ASSERT(geometry_index < (int)geometry.size());
  187. // Bind the textures to the geometries.
  188. for (int tex_index = 0; tex_index < num_textures; ++tex_index)
  189. geometry[geometry_index + tex_index].SetTexture(layer->GetTexture(tex_index));
  190. line_width = 0;
  191. Character prior_character = Character::Null;
  192. geometry[geometry_index].GetIndices().reserve(string.size() * 6);
  193. geometry[geometry_index].GetVertices().reserve(string.size() * 4);
  194. for (auto it_string = StringIteratorU8(string); it_string; ++it_string)
  195. {
  196. Character character = *it_string;
  197. const FontGlyph* glyph = GetOrAppendGlyph(character);
  198. if (!glyph)
  199. continue;
  200. // Adjust the cursor for the kerning between this character and the previous one.
  201. line_width += GetKerning(prior_character, character);
  202. // Use white vertex colors on RGB glyphs.
  203. const Colourb glyph_color =
  204. (layer == base_layer && glyph->color_format == ColorFormat::RGBA8 ? Colourb(255, layer_colour.alpha) : layer_colour);
  205. layer->GenerateGeometry(&geometry[geometry_index], character, Vector2f(position.x + line_width, position.y), glyph_color);
  206. line_width += glyph->advance;
  207. line_width += (int)letter_spacing;
  208. prior_character = character;
  209. }
  210. geometry_index += num_textures;
  211. }
  212. // Cull any excess geometry from a previous generation.
  213. geometry.resize(geometry_index);
  214. return Math::Max(line_width, 0);
  215. }
  216. bool FontFaceHandleDefault::UpdateLayersOnDirty()
  217. {
  218. bool result = false;
  219. // If we are dirty, regenerate all the layers and increment the version
  220. if (is_layers_dirty && base_layer)
  221. {
  222. is_layers_dirty = false;
  223. ++version;
  224. // Regenerate all the layers.
  225. // Note: The layer regeneration needs to happen in the order in which the layers were created,
  226. // otherwise we may end up cloning a layer which has not yet been regenerated. This means trouble!
  227. for (auto& pair : layers)
  228. {
  229. GenerateLayer(pair.layer.get());
  230. }
  231. result = true;
  232. }
  233. return result;
  234. }
  235. int FontFaceHandleDefault::GetVersion() const
  236. {
  237. return version;
  238. }
  239. bool FontFaceHandleDefault::AppendGlyph(Character character)
  240. {
  241. bool result = FreeType::AppendGlyph(ft_face, metrics.size, character, glyphs);
  242. return result;
  243. }
  244. void FontFaceHandleDefault::FillKerningPairCache()
  245. {
  246. if (!has_kerning)
  247. return;
  248. for (char32_t i = KerningCache_AsciiSubsetBegin; i <= KerningCache_AsciiSubsetLast; i++)
  249. {
  250. for (char32_t j = KerningCache_AsciiSubsetBegin; j <= KerningCache_AsciiSubsetLast; j++)
  251. {
  252. const bool first_iteration = (i == KerningCache_AsciiSubsetBegin && j == KerningCache_AsciiSubsetBegin);
  253. // Fetch the kerning from the font face. Submit zero font size on subsequent iterations for performance reasons.
  254. const int kerning = FreeType::GetKerning(ft_face, first_iteration ? metrics.size : 0, Character(i), Character(j));
  255. if (kerning != 0)
  256. {
  257. kerning_pair_cache.emplace(AsciiPair((i << 8) | j), KerningIntType(kerning));
  258. }
  259. }
  260. }
  261. }
  262. int FontFaceHandleDefault::GetKerning(Character lhs, Character rhs) const
  263. {
  264. static_assert(' ' == 32, "Only ASCII/UTF8 character set supported.");
  265. // Check if we have no kerning, or if we are have a control character.
  266. if (!has_kerning || char32_t(lhs) < ' ' || char32_t(rhs) < ' ')
  267. return 0;
  268. // See if the kerning pair has been cached.
  269. const bool lhs_in_cache = (char32_t(lhs) >= KerningCache_AsciiSubsetBegin && char32_t(lhs) <= KerningCache_AsciiSubsetLast);
  270. const bool rhs_in_cache = (char32_t(rhs) >= KerningCache_AsciiSubsetBegin && char32_t(rhs) <= KerningCache_AsciiSubsetLast);
  271. if (lhs_in_cache && rhs_in_cache)
  272. {
  273. const auto it = kerning_pair_cache.find(AsciiPair((int(lhs) << 8) | int(rhs)));
  274. if (it != kerning_pair_cache.end())
  275. {
  276. return it->second;
  277. }
  278. return 0;
  279. }
  280. // Fetch it from the font face instead.
  281. const int result = FreeType::GetKerning(ft_face, metrics.size, lhs, rhs);
  282. return result;
  283. }
  284. const FontGlyph* FontFaceHandleDefault::GetOrAppendGlyph(Character& character, bool look_in_fallback_fonts)
  285. {
  286. // Don't try to render control characters
  287. if ((char32_t)character < (char32_t)' ')
  288. return nullptr;
  289. auto it_glyph = glyphs.find(character);
  290. if (it_glyph == glyphs.end())
  291. {
  292. bool result = AppendGlyph(character);
  293. if (result)
  294. {
  295. it_glyph = glyphs.find(character);
  296. if (it_glyph == glyphs.end())
  297. {
  298. RMLUI_ERROR;
  299. return nullptr;
  300. }
  301. is_layers_dirty = true;
  302. }
  303. else if (look_in_fallback_fonts)
  304. {
  305. const int num_fallback_faces = FontProvider::CountFallbackFontFaces();
  306. for (int i = 0; i < num_fallback_faces; i++)
  307. {
  308. FontFaceHandleDefault* fallback_face = FontProvider::GetFallbackFontFace(i, metrics.size);
  309. if (!fallback_face || fallback_face == this)
  310. continue;
  311. const FontGlyph* glyph = fallback_face->GetOrAppendGlyph(character, false);
  312. if (glyph)
  313. {
  314. // Insert the new glyph into our own set of glyphs
  315. auto pair = glyphs.emplace(character, glyph->WeakCopy());
  316. it_glyph = pair.first;
  317. if (pair.second)
  318. is_layers_dirty = true;
  319. break;
  320. }
  321. }
  322. // If we still have not found a glyph, use the replacement character.
  323. if (it_glyph == glyphs.end())
  324. {
  325. character = Character::Replacement;
  326. it_glyph = glyphs.find(character);
  327. if (it_glyph == glyphs.end())
  328. return nullptr;
  329. }
  330. }
  331. else
  332. {
  333. return nullptr;
  334. }
  335. }
  336. const FontGlyph* glyph = &it_glyph->second;
  337. return glyph;
  338. }
  339. FontFaceLayer* FontFaceHandleDefault::GetOrCreateLayer(const SharedPtr<const FontEffect>& font_effect)
  340. {
  341. // Search for the font effect layer first, it may have been instanced before as part of a different configuration.
  342. const FontEffect* font_effect_ptr = font_effect.get();
  343. auto it =
  344. std::find_if(layers.begin(), layers.end(), [font_effect_ptr](const EffectLayerPair& pair) { return pair.font_effect == font_effect_ptr; });
  345. if (it != layers.end())
  346. return it->layer.get();
  347. // No existing effect matches, generate a new layer for the effect.
  348. layers.push_back(EffectLayerPair{font_effect_ptr, nullptr});
  349. auto& layer = layers.back().layer;
  350. layer = MakeUnique<FontFaceLayer>(font_effect);
  351. GenerateLayer(layer.get());
  352. return layer.get();
  353. }
  354. bool FontFaceHandleDefault::GenerateLayer(FontFaceLayer* layer)
  355. {
  356. RMLUI_ASSERT(layer);
  357. const FontEffect* font_effect = layer->GetFontEffect();
  358. bool result = false;
  359. if (!font_effect)
  360. {
  361. result = layer->Generate(this);
  362. }
  363. else
  364. {
  365. // Determine which, if any, layer the new layer should copy its geometry and textures from.
  366. FontFaceLayer* clone = nullptr;
  367. bool clone_glyph_origins = true;
  368. String generation_key;
  369. size_t fingerprint = font_effect->GetFingerprint();
  370. if (!font_effect->HasUniqueTexture())
  371. {
  372. clone = base_layer;
  373. clone_glyph_origins = false;
  374. }
  375. else
  376. {
  377. auto cache_iterator = layer_cache.find(fingerprint);
  378. if (cache_iterator != layer_cache.end() && cache_iterator->second != layer)
  379. clone = cache_iterator->second;
  380. }
  381. // Create a new layer.
  382. result = layer->Generate(this, clone, clone_glyph_origins);
  383. // Cache the layer in the layer cache if it generated its own textures (ie, didn't clone).
  384. if (!clone)
  385. layer_cache[fingerprint] = layer;
  386. }
  387. return result;
  388. }
  389. } // namespace Rml