CCFontFNT.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. /****************************************************************************
  2. Copyright (c) 2013 Zynga Inc.
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "2d/CCFontFNT.h"
  22. #include "2d/CCFontAtlas.h"
  23. #include "2d/CCSpriteFrameCache.h"
  24. #include "platform/CCFileUtils.h"
  25. #include "base/CCConfiguration.h"
  26. #include "base/CCDirector.h"
  27. #include "base/CCMap.h"
  28. #include "base/ccUTF8.h"
  29. #include "renderer/CCTextureCache.h"
  30. #include <cmath>
  31. #include <set>
  32. #include <unordered_map>
  33. NS_CC_BEGIN
  34. /**
  35. * @addtogroup GUI
  36. * @{
  37. * @addtogroup label
  38. * @{
  39. */
  40. enum {
  41. kLabelAutomaticWidth = -1,
  42. };
  43. struct _FontDefHashElement;
  44. /**
  45. @struct BMFontDef
  46. BMFont definition
  47. */
  48. typedef struct _BMFontDef {
  49. //! ID of the character
  50. unsigned int charID;
  51. //! origin and size of the font
  52. Rect rect;
  53. //! The X amount the image should be offset when drawing the image (in pixels)
  54. short xOffset;
  55. //! The Y amount the image should be offset when drawing the image (in pixels)
  56. short yOffset;
  57. //! The amount to move the current position after drawing the character (in pixels)
  58. short xAdvance;
  59. } BMFontDef;
  60. /** @struct BMFontPadding
  61. BMFont padding
  62. @since v0.8.2
  63. */
  64. typedef struct _BMFontPadding {
  65. /// padding left
  66. int left;
  67. /// padding top
  68. int top;
  69. /// padding right
  70. int right;
  71. /// padding bottom
  72. int bottom;
  73. } BMFontPadding;
  74. /** @brief BMFontConfiguration has parsed configuration of the .fnt file
  75. @since v0.8
  76. */
  77. class CC_DLL BMFontConfiguration : public Ref
  78. {
  79. // FIXME: Creating a public interface so that the bitmapFontArray[] is accessible
  80. public://@public
  81. // BMFont definitions
  82. std::unordered_map<int /* key */, BMFontDef /* fontDef */> _fontDefDictionary;
  83. //! FNTConfig: Common Height Should be signed (issue #1343)
  84. int _commonHeight;
  85. //! Padding
  86. BMFontPadding _padding;
  87. //! atlas name
  88. std::string _atlasName;
  89. //! values for kerning
  90. std::unordered_map<uint64_t /* key */, int /* amount */> _kerningDictionary;
  91. // Character Set defines the letters that actually exist in the font
  92. std::set<unsigned int> *_characterSet;
  93. //! Font Size
  94. int _fontSize;
  95. public:
  96. /**
  97. * @js ctor
  98. */
  99. BMFontConfiguration();
  100. /**
  101. * @js NA
  102. * @lua NA
  103. */
  104. virtual ~BMFontConfiguration();
  105. /**
  106. * @js NA
  107. * @lua NA
  108. */
  109. std::string description() const;
  110. /** allocates a BMFontConfiguration with a FNT file */
  111. static BMFontConfiguration * create(const std::string& FNTfile);
  112. /** initializes a BitmapFontConfiguration with a FNT file */
  113. bool initWithFNTfile(const std::string& FNTfile);
  114. const std::string& getAtlasName() { return _atlasName; }
  115. void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; }
  116. std::set<unsigned int>* getCharacterSet() const;
  117. private:
  118. std::set<unsigned int>* parseConfigFile(const std::string& controlFile);
  119. std::set<unsigned int>* parseBinaryConfigFile(unsigned char* pData, unsigned long size, const std::string& controlFile);
  120. unsigned int parseCharacterDefinition(const char* line);
  121. void parseInfoArguments(const char* line);
  122. void parseCommonArguments(const char* line);
  123. void parseImageFileName(const char* line, const std::string& fntFile);
  124. void parseKerningEntry(const char* line);
  125. void purgeKerningDictionary();
  126. void purgeFontDefDictionary();
  127. };
  128. //
  129. //FNTConfig Cache - free functions
  130. //
  131. static Map<std::string, BMFontConfiguration*>* s_configurations = nullptr;
  132. BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile)
  133. {
  134. BMFontConfiguration* ret = nullptr;
  135. if (s_configurations == nullptr)
  136. {
  137. s_configurations = new (std::nothrow) Map<std::string, BMFontConfiguration*>();
  138. }
  139. ret = s_configurations->at(fntFile);
  140. if( ret == nullptr )
  141. {
  142. ret = BMFontConfiguration::create(fntFile);
  143. if (ret)
  144. {
  145. s_configurations->insert(fntFile, ret);
  146. }
  147. }
  148. return ret;
  149. }
  150. //
  151. //BitmapFontConfiguration
  152. //
  153. BMFontConfiguration * BMFontConfiguration::create(const std::string& FNTfile)
  154. {
  155. BMFontConfiguration * ret = new (std::nothrow) BMFontConfiguration();
  156. if (ret->initWithFNTfile(FNTfile))
  157. {
  158. ret->autorelease();
  159. return ret;
  160. }
  161. CC_SAFE_DELETE(ret);
  162. return nullptr;
  163. }
  164. bool BMFontConfiguration::initWithFNTfile(const std::string& FNTfile)
  165. {
  166. _characterSet = this->parseConfigFile(FNTfile);
  167. if (! _characterSet)
  168. {
  169. return false;
  170. }
  171. return true;
  172. }
  173. std::set<unsigned int>* BMFontConfiguration::getCharacterSet() const
  174. {
  175. return _characterSet;
  176. }
  177. BMFontConfiguration::BMFontConfiguration()
  178. : _commonHeight(0)
  179. , _characterSet(nullptr)
  180. , _fontSize(0)
  181. {
  182. }
  183. BMFontConfiguration::~BMFontConfiguration()
  184. {
  185. CCLOGINFO( "deallocing BMFontConfiguration: %p", this );
  186. this->purgeFontDefDictionary();
  187. this->purgeKerningDictionary();
  188. _atlasName.clear();
  189. CC_SAFE_DELETE(_characterSet);
  190. }
  191. std::string BMFontConfiguration::description(void) const
  192. {
  193. return StringUtils::format(
  194. "<BMFontConfiguration = " CC_FORMAT_PRINTF_SIZE_T " | Glphys:%d Kernings:%d | Image = %s>",
  195. (size_t)this,
  196. static_cast<int>(_fontDefDictionary.size()),
  197. static_cast<int>(_kerningDictionary.size()),
  198. _atlasName.c_str()
  199. );
  200. }
  201. void BMFontConfiguration::purgeKerningDictionary()
  202. {
  203. _kerningDictionary.clear();
  204. }
  205. void BMFontConfiguration::purgeFontDefDictionary()
  206. {
  207. _fontDefDictionary.clear();
  208. }
  209. std::set<unsigned int>* BMFontConfiguration::parseConfigFile(const std::string& controlFile)
  210. {
  211. std::string data = FileUtils::getInstance()->getStringFromFile(controlFile);
  212. if (data.empty())
  213. {
  214. return nullptr;
  215. }
  216. if (data.size() >= (sizeof("BMP") - 1) && memcmp("BMF", data.c_str(), sizeof("BMP") - 1) == 0) {
  217. // Handle fnt file of binary format
  218. std::set<unsigned int>* ret = parseBinaryConfigFile((unsigned char*)&data.front(), data.size(), controlFile);
  219. return ret;
  220. }
  221. if (data[0] == 0)
  222. {
  223. CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str());
  224. return nullptr;
  225. }
  226. auto contents = data.c_str();
  227. std::set<unsigned int> *validCharsString = new (std::nothrow) std::set<unsigned int>();
  228. auto contentsLen = strlen(contents);
  229. char line[512] = {0};
  230. auto next = strchr(contents, '\n');
  231. auto base = contents;
  232. size_t lineLength = 0;
  233. size_t parseCount = 0;
  234. while (next)
  235. {
  236. lineLength = ((int)(next - base));
  237. memcpy(line, contents + parseCount, lineLength);
  238. line[lineLength] = 0;
  239. parseCount += lineLength + 1;
  240. if (parseCount < contentsLen)
  241. {
  242. base = next + 1;
  243. next = strchr(base, '\n');
  244. }
  245. else
  246. {
  247. next = nullptr;
  248. }
  249. if (memcmp(line, "info face", 9) == 0)
  250. {
  251. // FIXME: info parsing is incomplete
  252. // Not needed for the Hiero editors, but needed for the AngelCode editor
  253. // [self parseInfoArguments:line];
  254. this->parseInfoArguments(line);
  255. }
  256. // Check to see if the start of the line is something we are interested in
  257. else if (memcmp(line, "common lineHeight", 17) == 0)
  258. {
  259. this->parseCommonArguments(line);
  260. }
  261. else if (memcmp(line, "page id", 7) == 0)
  262. {
  263. this->parseImageFileName(line, controlFile);
  264. }
  265. else if (memcmp(line, "chars c", 7) == 0)
  266. {
  267. // Ignore this line
  268. }
  269. else if (memcmp(line, "char", 4) == 0)
  270. {
  271. // Parse the current line and create a new CharDef
  272. unsigned int charID = this->parseCharacterDefinition(line);
  273. validCharsString->insert(charID);
  274. }
  275. else if (memcmp(line, "kerning first", 13) == 0)
  276. {
  277. this->parseKerningEntry(line);
  278. }
  279. }
  280. return validCharsString;
  281. }
  282. std::set<unsigned int>* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, unsigned long size, const std::string& controlFile)
  283. {
  284. /* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */
  285. std::set<unsigned int> *validCharsString = new (std::nothrow) std::set<unsigned int>();
  286. unsigned long remains = size;
  287. CCASSERT(pData[3] == 3, "Only version 3 is supported");
  288. pData += 4; remains -= 4;
  289. while (remains > 0)
  290. {
  291. unsigned char blockId = pData[0]; pData += 1; remains -= 1;
  292. uint32_t blockSize = 0; memcpy(&blockSize, pData, 4);
  293. pData += 4; remains -= 4;
  294. if (blockId == 1)
  295. {
  296. /*
  297. fontSize 2 int 0
  298. bitField 1 bits 2 bit 0: smooth, bit 1: unicode, bit 2: italic, bit 3: bold, bit 4: fixedHeight, bits 5-7: reserved
  299. charSet 1 uint 3
  300. stretchH 2 uint 4
  301. aa 1 uint 6
  302. paddingUp 1 uint 7
  303. paddingRight 1 uint 8
  304. paddingDown 1 uint 9
  305. paddingLeft 1 uint 10
  306. spacingHoriz 1 uint 11
  307. spacingVert 1 uint 12
  308. outline 1 uint 13 added with version 2
  309. fontName n+1 string 14 null terminated string with length n
  310. */
  311. memcpy(&_fontSize, pData, 2);
  312. _padding.top = (unsigned char)pData[7];
  313. _padding.right = (unsigned char)pData[8];
  314. _padding.bottom = (unsigned char)pData[9];
  315. _padding.left = (unsigned char)pData[10];
  316. }
  317. else if (blockId == 2)
  318. {
  319. /*
  320. lineHeight 2 uint 0
  321. base 2 uint 2
  322. scaleW 2 uint 4
  323. scaleH 2 uint 6
  324. pages 2 uint 8
  325. bitField 1 bits 10 bits 0-6: reserved, bit 7: packed
  326. alphaChnl 1 uint 11
  327. redChnl 1 uint 12
  328. greenChnl 1 uint 13
  329. blueChnl 1 uint 14
  330. */
  331. uint16_t lineHeight = 0; memcpy(&lineHeight, pData, 2);
  332. _commonHeight = lineHeight;
  333. uint16_t scaleW = 0; memcpy(&scaleW, pData + 4, 2);
  334. uint16_t scaleH = 0; memcpy(&scaleH, pData + 6, 2);
  335. CCASSERT(scaleW <= Configuration::getInstance()->getMaxTextureSize() && scaleH <= Configuration::getInstance()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
  336. uint16_t pages = 0; memcpy(&pages, pData + 8, 2);
  337. CCASSERT(pages == 1, "CCBitfontAtlas: only supports 1 page");
  338. }
  339. else if (blockId == 3)
  340. {
  341. /*
  342. pageNames p*(n+1) strings 0 p null terminated strings, each with length n
  343. */
  344. const char *value = (const char *)pData;
  345. CCASSERT(strlen(value) < blockSize, "Block size should be less then string");
  346. _atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile);
  347. }
  348. else if (blockId == 4)
  349. {
  350. /*
  351. id 4 uint 0+c*20 These fields are repeated until all characters have been described
  352. x 2 uint 4+c*20
  353. y 2 uint 6+c*20
  354. width 2 uint 8+c*20
  355. height 2 uint 10+c*20
  356. xoffset 2 int 12+c*20
  357. yoffset 2 int 14+c*20
  358. xadvance 2 int 16+c*20
  359. page 1 uint 18+c*20
  360. chnl 1 uint 19+c*20
  361. */
  362. unsigned long count = blockSize / 20;
  363. for (unsigned long i = 0; i < count; i++)
  364. {
  365. uint32_t charId = 0; memcpy(&charId, pData + (i * 20), 4);
  366. BMFontDef& fontDef = _fontDefDictionary[charId];
  367. fontDef.charID = charId;
  368. uint16_t charX = 0; memcpy(&charX, pData + (i * 20) + 4, 2);
  369. fontDef.rect.origin.x = charX;
  370. uint16_t charY = 0; memcpy(&charY, pData + (i * 20) + 6, 2);
  371. fontDef.rect.origin.y = charY;
  372. uint16_t charWidth = 0; memcpy(&charWidth, pData + (i * 20) + 8, 2);
  373. fontDef.rect.size.width = charWidth;
  374. uint16_t charHeight = 0; memcpy(&charHeight, pData + (i * 20) + 10, 2);
  375. fontDef.rect.size.height = charHeight;
  376. int16_t xoffset = 0; memcpy(&xoffset, pData + (i * 20) + 12, 2);
  377. fontDef.xOffset = xoffset;
  378. int16_t yoffset = 0; memcpy(&yoffset, pData + (i * 20) + 14, 2);
  379. fontDef.yOffset = yoffset;
  380. int16_t xadvance = 0; memcpy(&xadvance, pData + (i * 20) + 16, 2);
  381. fontDef.xAdvance = xadvance;
  382. validCharsString->insert(fontDef.charID);
  383. }
  384. }
  385. else if (blockId == 5) {
  386. /*
  387. first 4 uint 0+c*10 These fields are repeated until all kerning pairs have been described
  388. second 4 uint 4+c*10
  389. amount 2 int 8+c*10
  390. */
  391. unsigned long count = blockSize / 20;
  392. for (unsigned long i = 0; i < count; i++)
  393. {
  394. uint32_t first = 0; memcpy(&first, pData + (i * 10), 4);
  395. uint32_t second = 0; memcpy(&second, pData + (i * 10) + 4, 4);
  396. int16_t amount = 0; memcpy(&amount, pData + (i * 10) + 8, 2);
  397. uint64_t key = ((uint64_t)first<<32) | ((uint64_t)second&0xffffffffll);
  398. _kerningDictionary[key] = amount;
  399. }
  400. }
  401. pData += blockSize; remains -= blockSize;
  402. }
  403. return validCharsString;
  404. }
  405. void BMFontConfiguration::parseImageFileName(const char* line, const std::string& fntFile)
  406. {
  407. //////////////////////////////////////////////////////////////////////////
  408. // line to parse:
  409. // page id=0 file="bitmapFontTest.png"
  410. //////////////////////////////////////////////////////////////////////////
  411. // page ID. Sanity check
  412. int pageId;
  413. sscanf(line, "page id=%d", &pageId);
  414. CCASSERT(pageId == 0, "LabelBMFont file could not be found");
  415. // file
  416. char fileName[255];
  417. sscanf(strchr(line,'"') + 1, "%[^\"]", fileName);
  418. _atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(fileName, fntFile);
  419. }
  420. void BMFontConfiguration::parseInfoArguments(const char* line)
  421. {
  422. //////////////////////////////////////////////////////////////////////////
  423. // possible lines to parse:
  424. // info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0
  425. // info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1
  426. //////////////////////////////////////////////////////////////////////////
  427. sscanf(strstr(line, "size=") + 5, "%d", &_fontSize);
  428. // padding
  429. sscanf(strstr(line,"padding=") + 8, "%d,%d,%d,%d", &_padding.top, &_padding.right, &_padding.bottom, &_padding.left);
  430. //CCLOG("cocos2d: padding: %d,%d,%d,%d", _padding.left, _padding.top, _padding.right, _padding.bottom);
  431. }
  432. void BMFontConfiguration::parseCommonArguments(const char* line)
  433. {
  434. //////////////////////////////////////////////////////////////////////////
  435. // line to parse:
  436. // common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0
  437. //////////////////////////////////////////////////////////////////////////
  438. // Height
  439. auto tmp = strstr(line, "lineHeight=") + 11;
  440. sscanf(tmp, "%d", &_commonHeight);
  441. #if COCOS2D_DEBUG > 0
  442. // scaleW. sanity check
  443. int value;
  444. tmp = strstr(tmp, "scaleW=") + 7;
  445. sscanf(tmp, "%d", &value);
  446. int maxTextureSize = Configuration::getInstance()->getMaxTextureSize();
  447. CCASSERT(value <= maxTextureSize, "CCLabelBMFont: page can't be larger than supported");
  448. // scaleH. sanity check
  449. tmp = strstr(tmp, "scaleH=") + 7;
  450. sscanf(tmp, "%d", &value);
  451. CCASSERT(value <= maxTextureSize, "CCLabelBMFont: page can't be larger than supported");
  452. // pages. sanity check
  453. tmp = strstr(tmp, "pages=") + 6;
  454. sscanf(tmp, "%d", &value);
  455. CCASSERT(value == 1, "CCBitfontAtlas: only supports 1 page");
  456. #endif
  457. // packed (ignore) What does this mean ??
  458. }
  459. unsigned int BMFontConfiguration::parseCharacterDefinition(const char* line)
  460. {
  461. unsigned int charID = 0;
  462. //////////////////////////////////////////////////////////////////////////
  463. // line to parse:
  464. // char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=44 xadvance=14 page=0 chnl=0
  465. //////////////////////////////////////////////////////////////////////////
  466. // Character ID
  467. auto tmp = strstr(line, "id=") + 3;
  468. sscanf(tmp, "%u", &charID);
  469. BMFontDef& characterDefinition = _fontDefDictionary[charID];
  470. characterDefinition.charID = charID;
  471. // Character x
  472. tmp = strstr(tmp, "x=") + 2;
  473. sscanf(tmp, "%f", &characterDefinition.rect.origin.x);
  474. // Character y
  475. tmp = strstr(tmp, "y=") + 2;
  476. sscanf(tmp, "%f", &characterDefinition.rect.origin.y);
  477. // Character width
  478. tmp = strstr(tmp, "width=") + 6;
  479. sscanf(tmp, "%f", &characterDefinition.rect.size.width);
  480. // Character height
  481. tmp = strstr(tmp, "height=") + 7;
  482. sscanf(tmp, "%f", &characterDefinition.rect.size.height);
  483. // Character xoffset
  484. tmp = strstr(tmp, "xoffset=") + 8;
  485. sscanf(tmp, "%hd", &characterDefinition.xOffset);
  486. // Character yoffset
  487. tmp = strstr(tmp, "yoffset=") + 8;
  488. sscanf(tmp, "%hd", &characterDefinition.yOffset);
  489. // Character xadvance
  490. tmp = strstr(tmp, "xadvance=") + 9;
  491. sscanf(tmp, "%hd", &characterDefinition.xAdvance);
  492. return charID;
  493. }
  494. void BMFontConfiguration::parseKerningEntry(const char* line)
  495. {
  496. //////////////////////////////////////////////////////////////////////////
  497. // line to parse:
  498. // kerning first=121 second=44 amount=-7
  499. //////////////////////////////////////////////////////////////////////////
  500. int first, second, amount;
  501. auto tmp = strstr(line, "first=") + 6;
  502. sscanf(tmp, "%d", &first);
  503. tmp = strstr(tmp, "second=") + 7;
  504. sscanf(tmp, "%d", &second);
  505. tmp = strstr(tmp, "amount=") + 7;
  506. sscanf(tmp, "%d", &amount);
  507. uint64_t key = ((uint64_t)first<<32) | ((uint64_t)second&0xffffffffll);
  508. _kerningDictionary[key] = amount;
  509. }
  510. FontFNT * FontFNT::create(const std::string& fntFilePath, const Vec2& imageOffset /* = Vec2::ZERO */)
  511. {
  512. BMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath);
  513. if (!newConf)
  514. return nullptr;
  515. // add the texture
  516. SpriteFrame* sf = SpriteFrameCache::getInstance()->getSpriteFrameByName(newConf->getAtlasName());
  517. if (sf == nullptr) {
  518. Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(newConf->getAtlasName());
  519. if (!tempTexture)
  520. {
  521. return nullptr;
  522. }
  523. }
  524. FontFNT *tempFont = new FontFNT(newConf,imageOffset);
  525. tempFont->setFontSize(newConf->_fontSize);
  526. if (!tempFont) {
  527. return nullptr;
  528. }
  529. tempFont->autorelease();
  530. return tempFont;
  531. }
  532. FontFNT::FontFNT(BMFontConfiguration *theContfig, const Vec2& imageOffset /* = Vec2::ZERO */)
  533. :_configuration(theContfig)
  534. ,_imageOffset(CC_POINT_PIXELS_TO_POINTS(imageOffset))
  535. {
  536. _configuration->retain();
  537. }
  538. FontFNT::~FontFNT()
  539. {
  540. _configuration->release();
  541. }
  542. void FontFNT::purgeCachedData()
  543. {
  544. if (s_configurations)
  545. {
  546. s_configurations->clear();
  547. CC_SAFE_DELETE(s_configurations);
  548. }
  549. }
  550. int * FontFNT::getHorizontalKerningForTextUTF32(const std::u32string& text, int &outNumLetters) const
  551. {
  552. outNumLetters = static_cast<int>(text.length());
  553. if (!outNumLetters)
  554. return nullptr;
  555. int *sizes = new (std::nothrow) int[outNumLetters];
  556. if (!sizes)
  557. return nullptr;
  558. for (int c = 0; c < outNumLetters; ++c)
  559. {
  560. if (c < (outNumLetters-1))
  561. sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]);
  562. else
  563. sizes[c] = 0;
  564. }
  565. return sizes;
  566. }
  567. int FontFNT::getHorizontalKerningForChars(char32_t firstChar, char32_t secondChar) const
  568. {
  569. int ret = 0;
  570. uint64_t key = ((uint64_t)firstChar << 32) | ((uint64_t)secondChar & 0xffffffffll);
  571. auto iter = _configuration->_kerningDictionary.find(key);
  572. if (iter != _configuration->_kerningDictionary.end())
  573. {
  574. ret = iter->second;
  575. }
  576. return ret;
  577. }
  578. void FontFNT::setFontSize(float fontSize)
  579. {
  580. _fontSize = fontSize;
  581. }
  582. int FontFNT::getOriginalFontSize()const
  583. {
  584. return _configuration->_fontSize;
  585. }
  586. FontAtlas * FontFNT::createFontAtlas()
  587. {
  588. // check that everything is fine with the BMFontCofniguration
  589. if (_configuration->_fontDefDictionary.empty())
  590. return nullptr;
  591. size_t numGlyphs = _configuration->_characterSet->size();
  592. if (numGlyphs == 0)
  593. return nullptr;
  594. if (_configuration->_commonHeight == 0)
  595. return nullptr;
  596. FontAtlas *tempAtlas = new (std::nothrow) FontAtlas(*this);
  597. if (tempAtlas == nullptr)
  598. return nullptr;
  599. // common height
  600. int originalFontSize = _configuration->_fontSize;
  601. float originalLineHeight = _configuration->_commonHeight;
  602. float factor = 0.0f;
  603. if (std::abs(_fontSize - originalFontSize) < FLT_EPSILON) {
  604. factor = 1.0f;
  605. }else {
  606. factor = _fontSize / originalFontSize;
  607. }
  608. tempAtlas->setLineHeight(originalLineHeight * factor);
  609. for (auto&& e : _configuration->_fontDefDictionary)
  610. {
  611. BMFontDef& fontDef = e.second;
  612. FontLetterDefinition tempDefinition;
  613. Rect tempRect;
  614. tempRect = fontDef.rect;
  615. tempRect = CC_RECT_PIXELS_TO_POINTS(tempRect);
  616. tempDefinition.offsetX = fontDef.xOffset;
  617. tempDefinition.offsetY = fontDef.yOffset;
  618. tempDefinition.U = tempRect.origin.x + _imageOffset.x;
  619. tempDefinition.V = tempRect.origin.y + _imageOffset.y;
  620. tempDefinition.width = tempRect.size.width;
  621. tempDefinition.height = tempRect.size.height;
  622. //carloX: only one texture supported FOR NOW
  623. tempDefinition.textureID = 0;
  624. tempDefinition.validDefinition = true;
  625. tempDefinition.xAdvance = fontDef.xAdvance;
  626. // add the new definition
  627. if (65535 < fontDef.charID) {
  628. CCLOGWARN("Warning: 65535 < fontDef.charID (%u), ignored", fontDef.charID);
  629. } else {
  630. tempAtlas->addLetterDefinition(fontDef.charID,tempDefinition);
  631. }
  632. }
  633. // add the texture (only one texture for now)
  634. SpriteFrame* sf = SpriteFrameCache::getInstance()->getSpriteFrameByName(_configuration->getAtlasName());
  635. if (sf != nullptr) {
  636. tempAtlas->addTexture(sf->getTexture(), 0);
  637. tempAtlas->addRectInTexture(sf->getRect(), 0);
  638. } else {
  639. Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName());
  640. if (!tempTexture) {
  641. CC_SAFE_RELEASE(tempAtlas);
  642. return nullptr;
  643. }
  644. // add the texture
  645. tempAtlas->addTexture(tempTexture, 0);
  646. }
  647. // done
  648. return tempAtlas;
  649. }
  650. void FontFNT::reloadBMFontResource(const std::string& fntFilePath)
  651. {
  652. if (s_configurations == nullptr)
  653. {
  654. s_configurations = new (std::nothrow) Map<std::string, BMFontConfiguration*>();
  655. }
  656. BMFontConfiguration *ret = s_configurations->at(fntFilePath);
  657. if (ret != nullptr)
  658. {
  659. s_configurations->erase(fntFilePath);
  660. }
  661. ret = BMFontConfiguration::create(fntFilePath);
  662. if (ret)
  663. {
  664. s_configurations->insert(fntFilePath, ret);
  665. Director::getInstance()->getTextureCache()->reloadTexture(ret->getAtlasName());
  666. }
  667. }
  668. NS_CC_END