2
0

FontFaceHandleDefault.cpp 15 KB

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