FontFaceHandle.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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 (FontGlyphList::iterator i = glyphs.begin(); i != glyphs.end(); ++i)
  57. delete[] i->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. // find the maximum character we are interested in
  79. max_codepoint = 0;
  80. for (size_t i = 0; i < charset.size(); ++i)
  81. max_codepoint = Math::Max(max_codepoint, charset[i].max_codepoint);
  82. // Construct the list of the characters specified by the charset.
  83. glyphs.resize(max_codepoint+1, FontGlyph());
  84. for (size_t i = 0; i < charset.size(); ++i)
  85. BuildGlyphMap(ft_face, charset[i]);
  86. // Generate the metrics for the handle.
  87. GenerateMetrics(ft_face);
  88. BuildKerning(ft_face);
  89. // Generate the default layer and layer configuration.
  90. base_layer = GenerateLayer(NULL);
  91. layer_configurations.push_back(LayerConfiguration());
  92. layer_configurations.back().push_back(base_layer);
  93. return true;
  94. }
  95. // Returns the point size of this font face.
  96. int FontFaceHandle::GetSize() const
  97. {
  98. return size;
  99. }
  100. // Returns the average advance of all glyphs in this font face.
  101. int FontFaceHandle::GetCharacterWidth() const
  102. {
  103. return average_advance;
  104. }
  105. // Returns the pixel height of a lower-case x in this font face.
  106. int FontFaceHandle::GetXHeight() const
  107. {
  108. return x_height;
  109. }
  110. // Returns the default height between this font face's baselines.
  111. int FontFaceHandle::GetLineHeight() const
  112. {
  113. return line_height;
  114. }
  115. // Returns the font's baseline.
  116. int FontFaceHandle::GetBaseline() const
  117. {
  118. return baseline;
  119. }
  120. // Returns the font's glyphs.
  121. const FontGlyphList& FontFaceHandle::GetGlyphs() const
  122. {
  123. return glyphs;
  124. }
  125. // Returns the width a string will take up if rendered with this handle.
  126. int FontFaceHandle::GetStringWidth(const WString& string, word prior_character) const
  127. {
  128. int width = 0;
  129. for (size_t i = 0; i < string.Length(); i++)
  130. {
  131. word character_code = string[i];
  132. if (character_code >= glyphs.size())
  133. continue;
  134. const FontGlyph &glyph = glyphs[character_code];
  135. // Adjust the cursor for the kerning between this character and the previous one.
  136. if (prior_character != 0)
  137. width += GetKerning(prior_character, string[i]);
  138. // Adjust the cursor for this character's advance.
  139. width += glyph.advance;
  140. prior_character = character_code;
  141. }
  142. return width;
  143. }
  144. // Generates, if required, the layer configuration for a given array of font effects.
  145. int FontFaceHandle::GenerateLayerConfiguration(FontEffectMap& font_effects)
  146. {
  147. if (font_effects.empty())
  148. return 0;
  149. // Prepare a list of effects, sorted by z-index.
  150. FontEffectList sorted_effects;
  151. for (FontEffectMap::const_iterator i = font_effects.begin(); i != font_effects.end(); ++i)
  152. sorted_effects.push_back(i->second);
  153. std::sort(sorted_effects.begin(), sorted_effects.end(), FontEffectSort());
  154. // Check each existing configuration for a match with this arrangement of effects.
  155. int configuration_index = 1;
  156. for (; configuration_index < (int) layer_configurations.size(); ++configuration_index)
  157. {
  158. const LayerConfiguration& configuration = layer_configurations[configuration_index];
  159. // Check the size is correct. For a math, there should be one layer in the configuration
  160. // plus an extra for the base layer.
  161. if (configuration.size() != sorted_effects.size() + 1)
  162. continue;
  163. // Check through each layer, checking it was created by the same effect as the one we're
  164. // checking.
  165. size_t effect_index = 0;
  166. for (size_t i = 0; i < configuration.size(); ++i)
  167. {
  168. // Skip the base layer ...
  169. if (configuration[i]->GetFontEffect() == NULL)
  170. continue;
  171. // If the ith layer's effect doesn't match the equivalent effect, then this
  172. // configuration can't match.
  173. if (configuration[i]->GetFontEffect() != sorted_effects[effect_index])
  174. break;
  175. // Check the next one ...
  176. ++effect_index;
  177. }
  178. if (effect_index == sorted_effects.size())
  179. return configuration_index;
  180. }
  181. // No match, so we have to generate a new layer configuration.
  182. layer_configurations.push_back(LayerConfiguration());
  183. LayerConfiguration& layer_configuration = layer_configurations.back();
  184. bool added_base_layer = false;
  185. for (size_t i = 0; i < sorted_effects.size(); ++i)
  186. {
  187. if (!added_base_layer &&
  188. sorted_effects[i]->GetZIndex() >= 0)
  189. {
  190. layer_configuration.push_back(base_layer);
  191. added_base_layer = true;
  192. }
  193. layer_configuration.push_back(GenerateLayer(sorted_effects[i]));
  194. }
  195. // Add the base layer now if we still haven't added it.
  196. if (!added_base_layer)
  197. layer_configuration.push_back(base_layer);
  198. return (int) (layer_configurations.size() - 1);
  199. }
  200. // Generates the texture data for a layer (for the texture database).
  201. bool FontFaceHandle::GenerateLayerTexture(const byte*& texture_data, Vector2i& texture_dimensions, FontEffect* layer_id, int texture_id)
  202. {
  203. FontLayerMap::iterator layer_iterator = layers.find(layer_id);
  204. if (layer_iterator == layers.end())
  205. return false;
  206. return layer_iterator->second->GenerateTexture(texture_data, texture_dimensions, texture_id);
  207. }
  208. // Generates the geometry required to render a single line of text.
  209. int FontFaceHandle::GenerateString(GeometryList& geometry, const WString& string, const Vector2f& position, const Colourb& colour, int layer_configuration_index) const
  210. {
  211. int geometry_index = 0;
  212. int line_width = 0;
  213. ROCKET_ASSERT(layer_configuration_index >= 0);
  214. ROCKET_ASSERT(layer_configuration_index < (int) layer_configurations.size());
  215. // Fetch the requested configuration and generate the geometry for each one.
  216. const LayerConfiguration& layer_configuration = layer_configurations[layer_configuration_index];
  217. for (size_t i = 0; i < layer_configuration.size(); ++i)
  218. {
  219. FontFaceLayer* layer = layer_configuration[i];
  220. Colourb layer_colour;
  221. if (layer == base_layer)
  222. layer_colour = colour;
  223. else
  224. layer_colour = layer->GetColour();
  225. // Resize the geometry list if required.
  226. if ((int) geometry.size() < geometry_index + layer->GetNumTextures())
  227. geometry.resize(geometry_index + layer->GetNumTextures());
  228. // Bind the textures to the geometries.
  229. for (int i = 0; i < layer->GetNumTextures(); ++i)
  230. geometry[geometry_index + i].SetTexture(layer->GetTexture(i));
  231. line_width = 0;
  232. word prior_character = 0;
  233. const word* string_iterator = string.CString();
  234. const word* string_end = string.CString() + string.Length();
  235. for (; string_iterator != string_end; string_iterator++)
  236. {
  237. if (*string_iterator >= glyphs.size())
  238. continue;
  239. const FontGlyph &glyph = glyphs[*string_iterator];
  240. // Adjust the cursor for the kerning between this character and the previous one.
  241. if (prior_character != 0)
  242. line_width += GetKerning(prior_character, *string_iterator);
  243. layer->GenerateGeometry(&geometry[geometry_index], *string_iterator, Vector2f(position.x + line_width, position.y), layer_colour);
  244. line_width += glyph.advance;
  245. prior_character = *string_iterator;
  246. }
  247. geometry_index += layer->GetNumTextures();
  248. }
  249. // Cull any excess geometry from a previous generation.
  250. geometry.resize(geometry_index);
  251. return line_width;
  252. }
  253. // Generates the geometry required to render a line above, below or through a line of text.
  254. void FontFaceHandle::GenerateLine(Geometry* geometry, const Vector2f& position, int width, Font::Line height, const Colourb& colour) const
  255. {
  256. std::vector< Vertex >& line_vertices = geometry->GetVertices();
  257. std::vector< int >& line_indices = geometry->GetIndices();
  258. float offset;
  259. switch (height)
  260. {
  261. case Font::UNDERLINE: offset = -underline_position; break;
  262. case Font::OVERLINE: // where to place? offset = -line_height - underline_position; break;
  263. case Font::STRIKE_THROUGH: // where to place? offset = -line_height * 0.5f; break;
  264. default: return;
  265. }
  266. line_vertices.resize(line_vertices.size() + 4);
  267. line_indices.resize(line_indices.size() + 6);
  268. 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, (int)line_vertices.size() - 4);
  269. }
  270. // Returns the font face's raw charset (the charset range as a string).
  271. const String& FontFaceHandle::GetRawCharset() const
  272. {
  273. return raw_charset;
  274. }
  275. // Returns the font face's charset.
  276. const UnicodeRangeList& FontFaceHandle::GetCharset() const
  277. {
  278. return charset;
  279. }
  280. // Destroys the handle.
  281. void FontFaceHandle::OnReferenceDeactivate()
  282. {
  283. delete this;
  284. }
  285. void FontFaceHandle::GenerateMetrics(FT_Face ft_face)
  286. {
  287. line_height = ft_face->size->metrics.height >> 6;
  288. baseline = line_height - (ft_face->size->metrics.ascender >> 6);
  289. underline_position = FT_MulFix(ft_face->underline_position, ft_face->size->metrics.y_scale) / float(1 << 6);
  290. underline_thickness = FT_MulFix(ft_face->underline_thickness, ft_face->size->metrics.y_scale) / float(1 << 6);
  291. underline_thickness = Math::Max(underline_thickness, 1.0f);
  292. average_advance = 0;
  293. unsigned int num_visible_glyphs = 0;
  294. for (FontGlyphList::iterator i = glyphs.begin(); i != glyphs.end(); ++i)
  295. {
  296. if (i->advance)
  297. {
  298. average_advance += i->advance;
  299. num_visible_glyphs++;
  300. }
  301. }
  302. // Bring the total advance down to the average advance, but scaled up 10%, just to be on the safe side.
  303. if (num_visible_glyphs)
  304. average_advance = Math::RealToInteger((float) average_advance / (num_visible_glyphs * 0.9f));
  305. // Determine the x-height of this font face.
  306. word x = (word) 'x';
  307. int index = FT_Get_Char_Index(ft_face, x);
  308. if (FT_Load_Glyph(ft_face, index, 0) == 0)
  309. x_height = ft_face->glyph->metrics.height >> 6;
  310. else
  311. x_height = 0;
  312. }
  313. void FontFaceHandle::BuildGlyphMap(FT_Face ft_face, const UnicodeRange& unicode_range)
  314. {
  315. for (word character_code = (word) (Math::Max< unsigned int >(unicode_range.min_codepoint, 32)); character_code <= unicode_range.max_codepoint; ++character_code)
  316. {
  317. int index = FT_Get_Char_Index(ft_face, character_code);
  318. if (index != 0)
  319. {
  320. FT_Error error = FT_Load_Glyph(ft_face, index, 0);
  321. if (error != 0)
  322. {
  323. 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);
  324. continue;
  325. }
  326. error = FT_Render_Glyph(ft_face->glyph, FT_RENDER_MODE_NORMAL);
  327. if (error != 0)
  328. {
  329. 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);
  330. continue;
  331. }
  332. FontGlyph glyph;
  333. glyph.character = character_code;
  334. BuildGlyph(glyph, ft_face->glyph);
  335. glyphs[character_code] = glyph;
  336. }
  337. }
  338. }
  339. void FontFaceHandle::BuildGlyph(FontGlyph& glyph, FT_GlyphSlot ft_glyph)
  340. {
  341. // Set the glyph's dimensions.
  342. glyph.dimensions.x = ft_glyph->metrics.width >> 6;
  343. glyph.dimensions.y = ft_glyph->metrics.height >> 6;
  344. // Set the glyph's bearing.
  345. glyph.bearing.x = ft_glyph->metrics.horiBearingX >> 6;
  346. glyph.bearing.y = ft_glyph->metrics.horiBearingY >> 6;
  347. // Set the glyph's advance.
  348. glyph.advance = ft_glyph->metrics.horiAdvance >> 6;
  349. // Set the glyph's bitmap dimensions.
  350. glyph.bitmap_dimensions.x = ft_glyph->bitmap.width;
  351. glyph.bitmap_dimensions.y = ft_glyph->bitmap.rows;
  352. // Copy the glyph's bitmap data from the FreeType glyph handle to our glyph handle.
  353. if (glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y != 0)
  354. {
  355. // Check the pixel mode is supported.
  356. if (ft_glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  357. ft_glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  358. {
  359. glyph.bitmap_data = NULL;
  360. 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);
  361. }
  362. else
  363. {
  364. glyph.bitmap_data = new byte[glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y];
  365. byte* source_bitmap = ft_glyph->bitmap.buffer;
  366. byte* destination_bitmap = glyph.bitmap_data;
  367. // Copy the bitmap data into the newly-allocated space on our glyph.
  368. switch (ft_glyph->bitmap.pixel_mode)
  369. {
  370. // Unpack 1-bit data into 8-bit.
  371. case FT_PIXEL_MODE_MONO:
  372. {
  373. for (int i = 0; i < glyph.bitmap_dimensions.y; ++i)
  374. {
  375. int mask = 0x80;
  376. byte* source_byte = source_bitmap;
  377. for (int j = 0; j < glyph.bitmap_dimensions.x; ++j)
  378. {
  379. if ((*source_byte & mask) == mask)
  380. destination_bitmap[j] = 255;
  381. else
  382. destination_bitmap[j] = 0;
  383. mask >>= 1;
  384. if (mask <= 0)
  385. {
  386. mask = 0x80;
  387. ++source_byte;
  388. }
  389. }
  390. destination_bitmap += glyph.bitmap_dimensions.x;
  391. source_bitmap += ft_glyph->bitmap.pitch;
  392. }
  393. }
  394. break;
  395. // Directly copy 8-bit data.
  396. case FT_PIXEL_MODE_GRAY:
  397. {
  398. for (int i = 0; i < glyph.bitmap_dimensions.y; ++i)
  399. {
  400. memcpy(destination_bitmap, source_bitmap, glyph.bitmap_dimensions.x);
  401. destination_bitmap += glyph.bitmap_dimensions.x;
  402. source_bitmap += ft_glyph->bitmap.pitch;
  403. }
  404. }
  405. break;
  406. }
  407. }
  408. }
  409. else
  410. glyph.bitmap_data = NULL;
  411. }
  412. void FontFaceHandle::BuildKerning(FT_Face ft_face)
  413. {
  414. // Compile the kerning information for this character if the font includes it.
  415. if (FT_HAS_KERNING(ft_face))
  416. {
  417. kerning.resize(max_codepoint+1, GlyphKerningList(max_codepoint+1, 0));
  418. for (size_t i = 0; i < charset.size(); ++i)
  419. {
  420. for (word rhs = (word) (Math::Max< unsigned int >(charset[i].min_codepoint, 32)); rhs <= charset[i].max_codepoint; ++rhs)
  421. {
  422. GlyphKerningList glyph_kerning(max_codepoint+1, 0);
  423. for (size_t j = 0; j < charset.size(); ++j)
  424. {
  425. for (word lhs = (word) (Math::Max< unsigned int >(charset[j].min_codepoint, 32)); lhs <= charset[j].max_codepoint; ++lhs)
  426. {
  427. FT_Vector ft_kerning;
  428. FT_Get_Kerning(ft_face, FT_Get_Char_Index(ft_face, lhs), FT_Get_Char_Index(ft_face, rhs), FT_KERNING_DEFAULT, &ft_kerning);
  429. int kerning = ft_kerning.x >> 6;
  430. if (kerning != 0)
  431. glyph_kerning[lhs] = kerning;
  432. }
  433. }
  434. kerning[rhs] = glyph_kerning;
  435. }
  436. }
  437. }
  438. }
  439. int FontFaceHandle::GetKerning(word lhs, word rhs) const
  440. {
  441. if (rhs >= kerning.size())
  442. return 0;
  443. const GlyphKerningList &kerning_map = kerning[rhs];
  444. if (lhs >= kerning_map.size())
  445. return 0;
  446. return kerning_map[lhs];
  447. }
  448. // Generates (or shares) a layer derived from a font effect.
  449. FontFaceLayer* FontFaceHandle::GenerateLayer(FontEffect* font_effect)
  450. {
  451. // See if this effect has been instanced before, as part of a different configuration.
  452. FontLayerMap::iterator i = layers.find(font_effect);
  453. if (i != layers.end())
  454. return i->second;
  455. FontFaceLayer* layer = new FontFaceLayer();
  456. layers[font_effect] = layer;
  457. if (font_effect == NULL)
  458. {
  459. layer->Initialise(this);
  460. }
  461. else
  462. {
  463. // Determine which, if any, layer the new layer should copy its geometry and textures from.
  464. FontFaceLayer* clone = NULL;
  465. bool deep_clone = true;
  466. String generation_key;
  467. if (!font_effect->HasUniqueTexture())
  468. {
  469. clone = base_layer;
  470. deep_clone = false;
  471. }
  472. else
  473. {
  474. generation_key = font_effect->GetName() + ";" + font_effect->GetGenerationKey();
  475. FontLayerCache::iterator cache_iterator = layer_cache.find(generation_key);
  476. if (cache_iterator != layer_cache.end())
  477. clone = cache_iterator->second;
  478. }
  479. // Create a new layer.
  480. layer->Initialise(this, font_effect, clone, deep_clone);
  481. // Cache the layer in the layer cache if it generated its own textures (ie, didn't clone).
  482. if (clone == NULL)
  483. layer_cache[generation_key] = layer;
  484. }
  485. return layer;
  486. }
  487. }
  488. }