FontFaceHandle.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /*
  2. * This source file is part of libRocket, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://www.librocket.com
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. *
  26. */
  27. #include "precompiled.h"
  28. #include "FontFaceHandle.h"
  29. #include <algorithm>
  30. #include <Rocket/Core.h>
  31. #include "FontFaceLayer.h"
  32. #include "TextureLayout.h"
  33. namespace Rocket {
  34. namespace Core {
  35. class FontEffectSort
  36. {
  37. public:
  38. bool operator()(const FontEffect* lhs, const FontEffect* rhs)
  39. {
  40. return lhs->GetZIndex() < rhs->GetZIndex();
  41. }
  42. };
  43. FontFaceHandle::FontFaceHandle()
  44. {
  45. size = 0;
  46. average_advance = 0;
  47. x_height = 0;
  48. line_height = 0;
  49. baseline = 0;
  50. underline_position = 0;
  51. underline_thickness = 0;
  52. base_layer = NULL;
  53. }
  54. FontFaceHandle::~FontFaceHandle()
  55. {
  56. for (FontGlyphMap::iterator i = glyphs.begin(); i != glyphs.end(); ++i)
  57. delete[] i->second.bitmap_data;
  58. for (FontLayerMap::iterator i = layers.begin(); i != layers.end(); ++i)
  59. delete i->second;
  60. }
  61. // Initialises the handle so it is able to render text.
  62. bool FontFaceHandle::Initialise(FT_Face ft_face, const String& _charset, int _size)
  63. {
  64. size = _size;
  65. raw_charset = _charset;
  66. if (!UnicodeRange::BuildList(charset, raw_charset))
  67. {
  68. Log::Message(Log::LT_ERROR, "Invalid font charset '%s'.", raw_charset.CString());
  69. return false;
  70. }
  71. // Set the character size on the font face.
  72. FT_Error error = FT_Set_Char_Size(ft_face, 0, size << 6, 0, 0);
  73. if (error != 0)
  74. {
  75. Log::Message(Log::LT_ERROR, "Unable to set the character size '%d' on the font face '%s %s'.", size, ft_face->family_name, ft_face->style_name);
  76. return false;
  77. }
  78. // Construct the list of the characters specified by the charset.
  79. for (size_t i = 0; i < charset.size(); ++i)
  80. BuildGlyphMap(ft_face, charset[i]);
  81. // Generate the metrics for the handle.
  82. GenerateMetrics(ft_face);
  83. // Generate the default layer and layer configuration.
  84. base_layer = GenerateLayer(NULL);
  85. layer_configurations.push_back(LayerConfiguration());
  86. layer_configurations.back().push_back(base_layer);
  87. return true;
  88. }
  89. // Returns the point size of this font face.
  90. int FontFaceHandle::GetSize() const
  91. {
  92. return size;
  93. }
  94. // Returns the average advance of all glyphs in this font face.
  95. int FontFaceHandle::GetCharacterWidth() const
  96. {
  97. return average_advance;
  98. }
  99. // Returns the pixel height of a lower-case x in this font face.
  100. int FontFaceHandle::GetXHeight() const
  101. {
  102. return x_height;
  103. }
  104. // Returns the default height between this font face's baselines.
  105. int FontFaceHandle::GetLineHeight() const
  106. {
  107. return line_height;
  108. }
  109. // Returns the font's baseline.
  110. int FontFaceHandle::GetBaseline() const
  111. {
  112. return baseline;
  113. }
  114. // Returns the font's glyphs.
  115. const FontGlyphMap& FontFaceHandle::GetGlyphs() const
  116. {
  117. return glyphs;
  118. }
  119. // Returns the width a string will take up if rendered with this handle.
  120. int FontFaceHandle::GetStringWidth(const WString& string, word prior_character) const
  121. {
  122. int width = 0;
  123. for (size_t i = 0; i < string.Length(); i++)
  124. {
  125. word character_code = string[i];
  126. FontGlyphMap::const_iterator iterator = glyphs.find(character_code);
  127. if (iterator == glyphs.end())
  128. continue;
  129. // Adjust the cursor for the kerning between this character and the previous one.
  130. if (prior_character != 0)
  131. width += GetKerning(prior_character, string[i]);
  132. // Adjust the cursor for this character's advance.
  133. width += iterator->second.advance;
  134. prior_character = character_code;
  135. }
  136. return width;
  137. }
  138. // Generates, if required, the layer configuration for a given array of font effects.
  139. int FontFaceHandle::GenerateLayerConfiguration(FontEffectMap& font_effects)
  140. {
  141. if (font_effects.empty())
  142. return 0;
  143. // Prepare a list of effects, sorted by z-index.
  144. FontEffectList sorted_effects;
  145. for (FontEffectMap::const_iterator i = font_effects.begin(); i != font_effects.end(); ++i)
  146. sorted_effects.push_back(i->second);
  147. std::sort(sorted_effects.begin(), sorted_effects.end(), FontEffectSort());
  148. // Check each existing configuration for a match with this arrangement of effects.
  149. int configuration_index = 1;
  150. for (; configuration_index < (int) layer_configurations.size(); ++configuration_index)
  151. {
  152. const LayerConfiguration& configuration = layer_configurations[configuration_index];
  153. // Check the size is correct. For a math, there should be one layer in the configuration
  154. // plus an extra for the base layer.
  155. if (configuration.size() != sorted_effects.size() + 1)
  156. continue;
  157. // Check through each layer, checking it was created by the same effect as the one we're
  158. // checking.
  159. size_t effect_index = 0;
  160. for (size_t i = 0; i < configuration.size(); ++i)
  161. {
  162. // Skip the base layer ...
  163. if (configuration[i]->GetFontEffect() == NULL)
  164. continue;
  165. // If the ith layer's effect doesn't match the equivalent effect, then this
  166. // configuration can't match.
  167. if (configuration[i]->GetFontEffect() != sorted_effects[effect_index])
  168. break;
  169. // Check the next one ...
  170. ++effect_index;
  171. }
  172. if (effect_index == sorted_effects.size())
  173. return configuration_index;
  174. }
  175. // No match, so we have to generate a new layer configuration.
  176. layer_configurations.push_back(LayerConfiguration());
  177. LayerConfiguration& layer_configuration = layer_configurations.back();
  178. bool added_base_layer = false;
  179. for (size_t i = 0; i < sorted_effects.size(); ++i)
  180. {
  181. if (!added_base_layer &&
  182. sorted_effects[i]->GetZIndex() >= 0)
  183. {
  184. layer_configuration.push_back(base_layer);
  185. added_base_layer = true;
  186. }
  187. layer_configuration.push_back(GenerateLayer(sorted_effects[i]));
  188. }
  189. // Add the base layer now if we still haven't added it.
  190. if (!added_base_layer)
  191. layer_configuration.push_back(base_layer);
  192. return (int) (layer_configurations.size() - 1);
  193. }
  194. // Generates the texture data for a layer (for the texture database).
  195. bool FontFaceHandle::GenerateLayerTexture(const byte*& texture_data, Vector2i& texture_dimensions, FontEffect* layer_id, int texture_id)
  196. {
  197. FontLayerMap::iterator layer_iterator = layers.find(layer_id);
  198. if (layer_iterator == layers.end())
  199. return false;
  200. return layer_iterator->second->GenerateTexture(texture_data, texture_dimensions, texture_id);
  201. }
  202. // Generates the geometry required to render a single line of text.
  203. int FontFaceHandle::GenerateString(GeometryList& geometry, const WString& string, const Vector2f& position, const Colourb& colour, int layer_configuration_index) const
  204. {
  205. int geometry_index = 0;
  206. int line_width = 0;
  207. ROCKET_ASSERT(layer_configuration_index >= 0);
  208. ROCKET_ASSERT(layer_configuration_index < (int) layer_configurations.size());
  209. // Fetch the requested configuration and generate the geometry for each one.
  210. const LayerConfiguration& layer_configuration = layer_configurations[layer_configuration_index];
  211. for (size_t i = 0; i < layer_configuration.size(); ++i)
  212. {
  213. FontFaceLayer* layer = layer_configuration[i];
  214. Colourb layer_colour;
  215. if (layer == base_layer)
  216. layer_colour = colour;
  217. else
  218. layer_colour = layer->GetColour();
  219. // Resize the geometry list if required.
  220. if ((int) geometry.size() < geometry_index + layer->GetNumTextures())
  221. geometry.resize(geometry_index + layer->GetNumTextures());
  222. // Bind the textures to the geometries.
  223. for (int i = 0; i < layer->GetNumTextures(); ++i)
  224. geometry[geometry_index + i].SetTexture(layer->GetTexture(i));
  225. line_width = 0;
  226. word prior_character = 0;
  227. const word* string_iterator = string.CString();
  228. const word* string_end = string.CString() + string.Length();
  229. for (; string_iterator != string_end; string_iterator++)
  230. {
  231. FontGlyphMap::const_iterator iterator = glyphs.find(*string_iterator);
  232. if (iterator == glyphs.end())
  233. continue;
  234. // Adjust the cursor for the kerning between this character and the previous one.
  235. if (prior_character != 0)
  236. line_width += GetKerning(prior_character, *string_iterator);
  237. layer->GenerateGeometry(&geometry[geometry_index], *string_iterator, Vector2f(position.x + line_width, position.y), layer_colour);
  238. line_width += iterator->second.advance;
  239. prior_character = *string_iterator;
  240. }
  241. geometry_index += layer->GetNumTextures();
  242. }
  243. // Cull any excess geometry from a previous generation.
  244. geometry.resize(geometry_index);
  245. return line_width;
  246. }
  247. // Generates the geometry required to render a line above, below or through a line of text.
  248. void FontFaceHandle::GenerateLine(Geometry* geometry, const Vector2f& position, int width, Font::Line height, const Colourb& colour) const
  249. {
  250. std::vector< Vertex >& line_vertices = geometry->GetVertices();
  251. std::vector< int >& line_indices = geometry->GetIndices();
  252. float offset;
  253. switch (height)
  254. {
  255. case Font::UNDERLINE: offset = -underline_position; break;
  256. case Font::OVERLINE: // where to place? offset = -line_height - underline_position; break;
  257. case Font::STRIKE_THROUGH: // where to place? offset = -line_height * 0.5f; break;
  258. default: return;
  259. }
  260. line_vertices.resize(line_vertices.size() + 4);
  261. line_indices.resize(line_indices.size() + 6);
  262. GeometryUtilities::GenerateQuad(&line_vertices[0] + (line_vertices.size() - 4), &line_indices[0] + (line_indices.size() - 6), Vector2f(position.x, position.y + offset), Vector2f((float) width, underline_thickness), colour, line_vertices.size() - 4);
  263. }
  264. // Returns the font face's raw charset (the charset range as a string).
  265. const String& FontFaceHandle::GetRawCharset() const
  266. {
  267. return raw_charset;
  268. }
  269. // Returns the font face's charset.
  270. const UnicodeRangeList& FontFaceHandle::GetCharset() const
  271. {
  272. return charset;
  273. }
  274. // Destroys the handle.
  275. void FontFaceHandle::OnReferenceDeactivate()
  276. {
  277. delete this;
  278. }
  279. void FontFaceHandle::GenerateMetrics(FT_Face ft_face)
  280. {
  281. line_height = ft_face->size->metrics.height >> 6;
  282. baseline = line_height - (ft_face->size->metrics.ascender >> 6);
  283. underline_position = FT_MulFix(ft_face->underline_position, ft_face->size->metrics.y_scale) / float(1 << 6);
  284. underline_thickness = FT_MulFix(ft_face->underline_thickness, ft_face->size->metrics.y_scale) / float(1 << 6);
  285. underline_thickness = Math::Max(underline_thickness, 1.0f);
  286. average_advance = 0;
  287. for (FontGlyphMap::iterator i = glyphs.begin(); i != glyphs.end(); ++i)
  288. average_advance += i->second.advance;
  289. // Bring the total advance down to the average advance, but scaled up 10%, just to be on the safe side.
  290. average_advance = Math::RealToInteger((float) average_advance / (glyphs.size() * 0.9f));
  291. // Determine the x-height of this font face.
  292. word x = (word) 'x';
  293. int index = FT_Get_Char_Index(ft_face, x);
  294. if (FT_Load_Glyph(ft_face, index, 0) == 0)
  295. x_height = ft_face->glyph->metrics.height >> 6;
  296. else
  297. x_height = 0;
  298. }
  299. void FontFaceHandle::BuildGlyphMap(FT_Face ft_face, const UnicodeRange& unicode_range)
  300. {
  301. for (word character_code = (word) (Math::Max< unsigned int >(unicode_range.min_codepoint, 32)); character_code <= unicode_range.max_codepoint; ++character_code)
  302. {
  303. int index = FT_Get_Char_Index(ft_face, character_code);
  304. if (index != 0)
  305. {
  306. FT_Error error = FT_Load_Glyph(ft_face, index, 0);
  307. if (error != 0)
  308. {
  309. Log::Message(Log::LT_WARNING, "Unable to load glyph for character '%u' on the font face '%s %s'; error code: %d.", character_code, ft_face->family_name, ft_face->style_name, error);
  310. continue;
  311. }
  312. error = FT_Render_Glyph(ft_face->glyph, FT_RENDER_MODE_NORMAL);
  313. if (error != 0)
  314. {
  315. Log::Message(Log::LT_WARNING, "Unable to render glyph for character '%u' on the font face '%s %s'; error code: %d.", character_code, ft_face->family_name, ft_face->style_name, error);
  316. continue;
  317. }
  318. FontGlyph glyph;
  319. glyph.character = character_code;
  320. BuildGlyph(glyph, ft_face->glyph);
  321. glyphs[character_code] = glyph;
  322. }
  323. }
  324. }
  325. void FontFaceHandle::BuildGlyph(FontGlyph& glyph, FT_GlyphSlot ft_glyph)
  326. {
  327. // Set the glyph's dimensions.
  328. glyph.dimensions.x = ft_glyph->metrics.width >> 6;
  329. glyph.dimensions.y = ft_glyph->metrics.height >> 6;
  330. // Set the glyph's bearing.
  331. glyph.bearing.x = ft_glyph->metrics.horiBearingX >> 6;
  332. glyph.bearing.y = ft_glyph->metrics.horiBearingY >> 6;
  333. // Set the glyph's advance.
  334. glyph.advance = ft_glyph->metrics.horiAdvance >> 6;
  335. // Set the glyph's bitmap dimensions.
  336. glyph.bitmap_dimensions.x = ft_glyph->bitmap.width;
  337. glyph.bitmap_dimensions.y = ft_glyph->bitmap.rows;
  338. // Copy the glyph's bitmap data from the FreeType glyph handle to our glyph handle.
  339. if (glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y != 0)
  340. {
  341. // Check the pixel mode is supported.
  342. if (ft_glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  343. ft_glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  344. {
  345. glyph.bitmap_data = NULL;
  346. Log::Message(Log::LT_WARNING, "Unable to render glyph on the font face '%s %s'; unsupported pixel mode (%d).", ft_glyph->face->family_name, ft_glyph->face->style_name, ft_glyph->bitmap.pixel_mode);
  347. }
  348. else
  349. {
  350. glyph.bitmap_data = new byte[glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y];
  351. byte* source_bitmap = ft_glyph->bitmap.buffer;
  352. byte* destination_bitmap = glyph.bitmap_data;
  353. // Copy the bitmap data into the newly-allocated space on our glyph.
  354. switch (ft_glyph->bitmap.pixel_mode)
  355. {
  356. // Unpack 1-bit data into 8-bit.
  357. case FT_PIXEL_MODE_MONO:
  358. {
  359. for (int i = 0; i < glyph.bitmap_dimensions.y; ++i)
  360. {
  361. int mask = 0x80;
  362. byte* source_byte = source_bitmap;
  363. for (int j = 0; j < glyph.bitmap_dimensions.x; ++j)
  364. {
  365. if ((*source_byte & mask) == mask)
  366. destination_bitmap[j] = 255;
  367. else
  368. destination_bitmap[j] = 0;
  369. mask >>= 1;
  370. if (mask <= 0)
  371. {
  372. mask = 0x80;
  373. ++source_byte;
  374. }
  375. }
  376. destination_bitmap += glyph.bitmap_dimensions.x;
  377. source_bitmap += ft_glyph->bitmap.pitch;
  378. }
  379. }
  380. break;
  381. // Directly copy 8-bit data.
  382. case FT_PIXEL_MODE_GRAY:
  383. {
  384. for (int i = 0; i < glyph.bitmap_dimensions.y; ++i)
  385. {
  386. memcpy(destination_bitmap, source_bitmap, glyph.bitmap_dimensions.x);
  387. destination_bitmap += glyph.bitmap_dimensions.x;
  388. source_bitmap += ft_glyph->bitmap.pitch;
  389. }
  390. }
  391. break;
  392. }
  393. }
  394. }
  395. else
  396. glyph.bitmap_data = NULL;
  397. }
  398. void FontFaceHandle::BuildKerning(FT_Face ft_face)
  399. {
  400. // Compile the kerning information for this character if the font includes it.
  401. if (FT_HAS_KERNING(ft_face))
  402. {
  403. for (size_t i = 0; i < charset.size(); ++i)
  404. {
  405. for (word rhs = (word) (Math::Max< unsigned int >(charset[i].min_codepoint, 32)); rhs <= charset[i].max_codepoint; ++rhs)
  406. {
  407. GlyphKerningMap& glyph_kerning = kerning.insert(FontKerningMap::value_type(rhs, GlyphKerningMap())).first->second;
  408. for (size_t j = 0; j < charset.size(); ++j)
  409. {
  410. for (word lhs = (word) (Math::Max< unsigned int >(charset[j].min_codepoint, 32)); lhs <= charset[j].max_codepoint; ++lhs)
  411. {
  412. FT_Vector ft_kerning;
  413. FT_Get_Kerning(ft_face, FT_Get_Char_Index(ft_face, lhs), FT_Get_Char_Index(ft_face, rhs), FT_KERNING_DEFAULT, &ft_kerning);
  414. int kerning = ft_kerning.x >> 6;
  415. if (kerning != 0)
  416. glyph_kerning[lhs] = kerning;
  417. }
  418. }
  419. }
  420. }
  421. }
  422. }
  423. int FontFaceHandle::GetKerning(word lhs, word rhs) const
  424. {
  425. FontKerningMap::const_iterator rhs_iterator = kerning.find(rhs);
  426. if (rhs_iterator == kerning.end())
  427. return 0;
  428. GlyphKerningMap::const_iterator lhs_iterator = rhs_iterator->second.find(lhs);
  429. if (lhs_iterator == rhs_iterator->second.end())
  430. return 0;
  431. return lhs_iterator->second;
  432. }
  433. // Generates (or shares) a layer derived from a font effect.
  434. FontFaceLayer* FontFaceHandle::GenerateLayer(FontEffect* font_effect)
  435. {
  436. // See if this effect has been instanced before, as part of a different configuration.
  437. FontLayerMap::iterator i = layers.find(font_effect);
  438. if (i != layers.end())
  439. return i->second;
  440. FontFaceLayer* layer = new FontFaceLayer();
  441. layers[font_effect] = layer;
  442. if (font_effect == NULL)
  443. {
  444. layer->Initialise(this);
  445. }
  446. else
  447. {
  448. // Determine which, if any, layer the new layer should copy its geometry and textures from.
  449. FontFaceLayer* clone = NULL;
  450. bool deep_clone = true;
  451. String generation_key;
  452. if (!font_effect->HasUniqueTexture())
  453. {
  454. clone = base_layer;
  455. deep_clone = false;
  456. }
  457. else
  458. {
  459. generation_key = font_effect->GetName() + ";" + font_effect->GetGenerationKey();
  460. FontLayerCache::iterator cache_iterator = layer_cache.find(generation_key);
  461. if (cache_iterator != layer_cache.end())
  462. clone = cache_iterator->second;
  463. }
  464. // Create a new layer.
  465. layer->Initialise(this, font_effect, clone, deep_clone);
  466. // Cache the layer in the layer cache if it generated its own textures (ie, didn't clone).
  467. if (clone == NULL)
  468. layer_cache[generation_key] = layer;
  469. }
  470. return layer;
  471. }
  472. }
  473. }