FontFaceHandle.cpp 17 KB

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