FontFaceHandleDefault.cpp 15 KB

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