CCFontAtlas.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /****************************************************************************
  2. Copyright (c) 2013 Zynga Inc.
  3. Copyright (c) 2013-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #include "2d/CCFontAtlas.h"
  23. #if CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 && CC_TARGET_PLATFORM != CC_PLATFORM_WINRT && CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID
  24. #include <iconv.h>
  25. #elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  26. #include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
  27. #endif
  28. #include "2d/CCFontFreeType.h"
  29. #include "base/ccUTF8.h"
  30. #include "base/CCDirector.h"
  31. #include "base/CCEventListenerCustom.h"
  32. #include "base/CCEventDispatcher.h"
  33. #include "base/CCEventType.h"
  34. NS_CC_BEGIN
  35. const int FontAtlas::CacheTextureWidth = 512;
  36. const int FontAtlas::CacheTextureHeight = 512;
  37. const char* FontAtlas::CMD_PURGE_FONTATLAS = "__cc_PURGE_FONTATLAS";
  38. const char* FontAtlas::CMD_RESET_FONTATLAS = "__cc_RESET_FONTATLAS";
  39. FontAtlas::FontAtlas(Font &theFont)
  40. : _font(&theFont)
  41. , _fontFreeType(nullptr)
  42. , _iconv(nullptr)
  43. , _currentPageData(nullptr)
  44. , _fontAscender(0)
  45. , _rendererRecreatedListener(nullptr)
  46. , _antialiasEnabled(true)
  47. , _currLineHeight(0)
  48. {
  49. _font->retain();
  50. _fontFreeType = dynamic_cast<FontFreeType*>(_font);
  51. if (_fontFreeType)
  52. {
  53. _lineHeight = _font->getFontMaxHeight();
  54. _fontAscender = _fontFreeType->getFontAscender();
  55. _currentPage = 0;
  56. _currentPageOrigX = 0;
  57. _currentPageOrigY = 0;
  58. _letterEdgeExtend = 2;
  59. _letterPadding = 0;
  60. if (_fontFreeType->isDistanceFieldEnabled())
  61. {
  62. _letterPadding += 2 * FontFreeType::DistanceMapSpread;
  63. }
  64. reinit();
  65. #if CC_ENABLE_CACHE_TEXTURE_DATA
  66. auto eventDispatcher = Director::getInstance()->getEventDispatcher();
  67. _rendererRecreatedListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, CC_CALLBACK_1(FontAtlas::listenRendererRecreated, this));
  68. eventDispatcher->addEventListenerWithFixedPriority(_rendererRecreatedListener, 1);
  69. #endif
  70. }
  71. }
  72. void FontAtlas::reinit()
  73. {
  74. if (_currentPageData)
  75. {
  76. delete []_currentPageData;
  77. _currentPageData = nullptr;
  78. }
  79. auto texture = new (std::nothrow) Texture2D;
  80. _currentPageDataSize = CacheTextureWidth * CacheTextureHeight;
  81. auto outlineSize = _fontFreeType->getOutlineSize();
  82. if(outlineSize > 0)
  83. {
  84. _lineHeight += 2 * outlineSize;
  85. _currentPageDataSize *= 2;
  86. }
  87. _currentPageData = new (std::nothrow) unsigned char[_currentPageDataSize];
  88. memset(_currentPageData, 0, _currentPageDataSize);
  89. auto pixelFormat = outlineSize > 0 ? Texture2D::PixelFormat::AI88 : Texture2D::PixelFormat::A8;
  90. texture->initWithData(_currentPageData, _currentPageDataSize,
  91. pixelFormat, CacheTextureWidth, CacheTextureHeight, Size(CacheTextureWidth,CacheTextureHeight) );
  92. addTexture(texture,0);
  93. texture->release();
  94. }
  95. FontAtlas::~FontAtlas()
  96. {
  97. #if CC_ENABLE_CACHE_TEXTURE_DATA
  98. if (_fontFreeType && _rendererRecreatedListener)
  99. {
  100. auto eventDispatcher = Director::getInstance()->getEventDispatcher();
  101. eventDispatcher->removeEventListener(_rendererRecreatedListener);
  102. _rendererRecreatedListener = nullptr;
  103. }
  104. #endif
  105. _font->release();
  106. releaseTextures();
  107. delete []_currentPageData;
  108. #if CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 && CC_TARGET_PLATFORM != CC_PLATFORM_WINRT && CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID
  109. if (_iconv)
  110. {
  111. iconv_close(_iconv);
  112. _iconv = nullptr;
  113. }
  114. #endif
  115. }
  116. void FontAtlas::reset()
  117. {
  118. releaseTextures();
  119. _currLineHeight = 0;
  120. _currentPage = 0;
  121. _currentPageOrigX = 0;
  122. _currentPageOrigY = 0;
  123. _letterDefinitions.clear();
  124. reinit();
  125. }
  126. void FontAtlas::releaseTextures()
  127. {
  128. for( auto &item: _atlasTextures)
  129. {
  130. item.second->release();
  131. }
  132. _atlasTextures.clear();
  133. }
  134. void FontAtlas::purgeTexturesAtlas()
  135. {
  136. if (_fontFreeType)
  137. {
  138. reset();
  139. auto eventDispatcher = Director::getInstance()->getEventDispatcher();
  140. eventDispatcher->dispatchCustomEvent(CMD_PURGE_FONTATLAS,this);
  141. eventDispatcher->dispatchCustomEvent(CMD_RESET_FONTATLAS,this);
  142. }
  143. }
  144. void FontAtlas::listenRendererRecreated(EventCustom * /*event*/)
  145. {
  146. purgeTexturesAtlas();
  147. }
  148. void FontAtlas::addLetterDefinition(char32_t utf32Char, const FontLetterDefinition &letterDefinition)
  149. {
  150. _letterDefinitions[utf32Char] = letterDefinition;
  151. }
  152. void FontAtlas::scaleFontLetterDefinition(float scaleFactor)
  153. {
  154. for (auto&& fontDefinition : _letterDefinitions) {
  155. auto& letterDefinition = fontDefinition.second;
  156. letterDefinition.width *= scaleFactor;
  157. letterDefinition.height *= scaleFactor;
  158. letterDefinition.offsetX *= scaleFactor;
  159. letterDefinition.offsetY *= scaleFactor;
  160. letterDefinition.xAdvance *= scaleFactor;
  161. }
  162. }
  163. bool FontAtlas::getLetterDefinitionForChar(char32_t utf32Char, FontLetterDefinition &letterDefinition)
  164. {
  165. auto outIterator = _letterDefinitions.find(utf32Char);
  166. if (outIterator != _letterDefinitions.end())
  167. {
  168. letterDefinition = (*outIterator).second;
  169. return letterDefinition.validDefinition;
  170. }
  171. else
  172. {
  173. return false;
  174. }
  175. }
  176. void FontAtlas::conversionU32TOGB2312(const std::u32string& u32Text, std::unordered_map<unsigned int, unsigned int>& charCodeMap)
  177. {
  178. size_t strLen = u32Text.length();
  179. auto gb2312StrSize = strLen * 2;
  180. auto gb2312Text = new (std::nothrow) char[gb2312StrSize];
  181. memset(gb2312Text, 0, gb2312StrSize);
  182. switch (_fontFreeType->getEncoding())
  183. {
  184. case FT_ENCODING_GB2312:
  185. {
  186. #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
  187. std::u16string u16Text;
  188. cocos2d::StringUtils::UTF32ToUTF16(u32Text, u16Text);
  189. WideCharToMultiByte(936, NULL, (LPCWCH)u16Text.c_str(), strLen, (LPSTR)gb2312Text, gb2312StrSize, NULL, NULL);
  190. #elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  191. conversionEncodingJNI((char*)u32Text.c_str(), gb2312StrSize, "UTF-32LE", gb2312Text, "GB2312");
  192. #else
  193. if (_iconv == nullptr)
  194. {
  195. _iconv = iconv_open("GBK//TRANSLIT", "UTF-32LE");
  196. }
  197. if (_iconv == (iconv_t)-1)
  198. {
  199. CCLOG("conversion from utf32 to gb2312 not available");
  200. }
  201. else
  202. {
  203. char* pin = (char*)u32Text.c_str();
  204. char* pout = gb2312Text;
  205. size_t inLen = strLen * 2;
  206. size_t outLen = gb2312StrSize;
  207. iconv(_iconv, (char**)&pin, &inLen, &pout, &outLen);
  208. }
  209. #endif
  210. }
  211. break;
  212. default:
  213. CCLOG("Unsupported encoding:%d", _fontFreeType->getEncoding());
  214. break;
  215. }
  216. unsigned short gb2312Code = 0;
  217. unsigned char* dst = (unsigned char*)&gb2312Code;
  218. char32_t u32Code;
  219. for (size_t index = 0, gbIndex = 0; index < strLen; ++index)
  220. {
  221. u32Code = u32Text[index];
  222. if (u32Code < 256)
  223. {
  224. charCodeMap[u32Code] = u32Code;
  225. gbIndex += 1;
  226. }
  227. else
  228. {
  229. dst[0] = gb2312Text[gbIndex + 1];
  230. dst[1] = gb2312Text[gbIndex];
  231. charCodeMap[u32Code] = gb2312Code;
  232. gbIndex += 2;
  233. }
  234. }
  235. delete[] gb2312Text;
  236. }
  237. void FontAtlas::findNewCharacters(const std::u32string& u32Text, std::unordered_map<unsigned int, unsigned int>& charCodeMap)
  238. {
  239. std::u32string newChars;
  240. FT_Encoding charEncoding = _fontFreeType->getEncoding();
  241. //find new characters
  242. if (_letterDefinitions.empty())
  243. {
  244. // fixed #16169: new android project crash in android 5.0.2 device (Nexus 7) when use 3.12.
  245. // While using clang compiler with gnustl_static on android, the copy assignment operator of `std::u32string`
  246. // will affect the memory validity, it means after `newChars` is destroyed, the memory of `u32Text` holds
  247. // will be a dead region. `u32text` represents the variable in `Label::_utf32Text`, when somewhere
  248. // allocates memory by `malloc, realloc, new, new[]`, the generated memory address may be the same
  249. // as `Label::_utf32Text` holds. If doing a `memset` or other memory operations, the orignal `Label::_utf32Text`
  250. // will be in an unknown state. Meanwhile, a bunch lots of logic which depends on `Label::_utf32Text`
  251. // will be broken.
  252. // newChars = u32Text;
  253. // Using `append` method is a workaround for this issue. So please be carefuly while using the assignment operator
  254. // of `std::u32string`.
  255. newChars.append(u32Text);
  256. }
  257. else
  258. {
  259. auto length = u32Text.length();
  260. newChars.reserve(length);
  261. for (size_t i = 0; i < length; ++i)
  262. {
  263. auto outIterator = _letterDefinitions.find(u32Text[i]);
  264. if (outIterator == _letterDefinitions.end())
  265. {
  266. newChars.push_back(u32Text[i]);
  267. }
  268. }
  269. }
  270. if (!newChars.empty())
  271. {
  272. switch (charEncoding)
  273. {
  274. case FT_ENCODING_UNICODE:
  275. {
  276. for (auto u32Code : newChars)
  277. {
  278. charCodeMap[u32Code] = u32Code;
  279. }
  280. break;
  281. }
  282. case FT_ENCODING_GB2312:
  283. {
  284. conversionU32TOGB2312(newChars, charCodeMap);
  285. break;
  286. }
  287. default:
  288. CCLOG("FontAtlas::findNewCharacters: Unsupported encoding:%d", charEncoding);
  289. break;
  290. }
  291. }
  292. }
  293. bool FontAtlas::prepareLetterDefinitions(const std::u32string& utf32Text)
  294. {
  295. if (_fontFreeType == nullptr)
  296. {
  297. return false;
  298. }
  299. std::unordered_map<unsigned int, unsigned int> codeMapOfNewChar;
  300. findNewCharacters(utf32Text, codeMapOfNewChar);
  301. if (codeMapOfNewChar.empty())
  302. {
  303. return false;
  304. }
  305. int adjustForDistanceMap = _letterPadding / 2;
  306. int adjustForExtend = _letterEdgeExtend / 2;
  307. long bitmapWidth;
  308. long bitmapHeight;
  309. int glyphHeight;
  310. Rect tempRect;
  311. FontLetterDefinition tempDef;
  312. auto scaleFactor = CC_CONTENT_SCALE_FACTOR();
  313. auto pixelFormat = _fontFreeType->getOutlineSize() > 0 ? Texture2D::PixelFormat::AI88 : Texture2D::PixelFormat::A8;
  314. float startY = _currentPageOrigY;
  315. for (auto&& it : codeMapOfNewChar)
  316. {
  317. auto bitmap = _fontFreeType->getGlyphBitmap(it.second, bitmapWidth, bitmapHeight, tempRect, tempDef.xAdvance);
  318. if (bitmap && bitmapWidth > 0 && bitmapHeight > 0)
  319. {
  320. tempDef.validDefinition = true;
  321. tempDef.width = tempRect.size.width + _letterPadding + _letterEdgeExtend;
  322. tempDef.height = tempRect.size.height + _letterPadding + _letterEdgeExtend;
  323. tempDef.offsetX = tempRect.origin.x - adjustForDistanceMap - adjustForExtend;
  324. tempDef.offsetY = _fontAscender + tempRect.origin.y - adjustForDistanceMap - adjustForExtend;
  325. if (_currentPageOrigX + tempDef.width > CacheTextureWidth)
  326. {
  327. _currentPageOrigY += _currLineHeight;
  328. _currLineHeight = 0;
  329. _currentPageOrigX = 0;
  330. if (_currentPageOrigY + _lineHeight + _letterPadding + _letterEdgeExtend >= CacheTextureHeight)
  331. {
  332. unsigned char *data = nullptr;
  333. if (pixelFormat == Texture2D::PixelFormat::AI88)
  334. {
  335. data = _currentPageData + CacheTextureWidth * (int)startY * 2;
  336. }
  337. else
  338. {
  339. data = _currentPageData + CacheTextureWidth * (int)startY;
  340. }
  341. _atlasTextures[_currentPage]->updateWithData(data, 0, startY,
  342. CacheTextureWidth, CacheTextureHeight - startY);
  343. startY = 0.0f;
  344. _currentPageOrigY = 0;
  345. memset(_currentPageData, 0, _currentPageDataSize);
  346. _currentPage++;
  347. auto tex = new (std::nothrow) Texture2D;
  348. if (_antialiasEnabled)
  349. {
  350. tex->setAntiAliasTexParameters();
  351. }
  352. else
  353. {
  354. tex->setAliasTexParameters();
  355. }
  356. tex->initWithData(_currentPageData, _currentPageDataSize,
  357. pixelFormat, CacheTextureWidth, CacheTextureHeight, Size(CacheTextureWidth, CacheTextureHeight));
  358. addTexture(tex, _currentPage);
  359. tex->release();
  360. }
  361. }
  362. glyphHeight = static_cast<int>(bitmapHeight) + _letterPadding + _letterEdgeExtend;
  363. if (glyphHeight > _currLineHeight)
  364. {
  365. _currLineHeight = glyphHeight;
  366. }
  367. _fontFreeType->renderCharAt(_currentPageData, _currentPageOrigX + adjustForExtend, _currentPageOrigY + adjustForExtend, bitmap, bitmapWidth, bitmapHeight);
  368. tempDef.U = _currentPageOrigX;
  369. tempDef.V = _currentPageOrigY;
  370. tempDef.textureID = _currentPage;
  371. _currentPageOrigX += tempDef.width + 1;
  372. // take from pixels to points
  373. tempDef.width = tempDef.width / scaleFactor;
  374. tempDef.height = tempDef.height / scaleFactor;
  375. tempDef.U = tempDef.U / scaleFactor;
  376. tempDef.V = tempDef.V / scaleFactor;
  377. }
  378. else{
  379. if(bitmap)
  380. delete[] bitmap;
  381. if (tempDef.xAdvance)
  382. tempDef.validDefinition = true;
  383. else
  384. tempDef.validDefinition = false;
  385. tempDef.width = 0;
  386. tempDef.height = 0;
  387. tempDef.U = 0;
  388. tempDef.V = 0;
  389. tempDef.offsetX = 0;
  390. tempDef.offsetY = 0;
  391. tempDef.textureID = 0;
  392. _currentPageOrigX += 1;
  393. }
  394. _letterDefinitions[it.first] = tempDef;
  395. }
  396. unsigned char *data = nullptr;
  397. if (pixelFormat == Texture2D::PixelFormat::AI88)
  398. {
  399. data = _currentPageData + CacheTextureWidth * (int)startY * 2;
  400. }
  401. else
  402. {
  403. data = _currentPageData + CacheTextureWidth * (int)startY;
  404. }
  405. _atlasTextures[_currentPage]->updateWithData(data, 0, startY, CacheTextureWidth, _currentPageOrigY - startY + _currLineHeight);
  406. return true;
  407. }
  408. void FontAtlas::addTexture(Texture2D *texture, int slot)
  409. {
  410. texture->retain();
  411. _atlasTextures[slot] = texture;
  412. }
  413. Texture2D* FontAtlas::getTexture(int slot)
  414. {
  415. return _atlasTextures[slot];
  416. }
  417. void FontAtlas::setLineHeight(float newHeight)
  418. {
  419. _lineHeight = newHeight;
  420. }
  421. void FontAtlas::setAliasTexParameters()
  422. {
  423. if (_antialiasEnabled)
  424. {
  425. _antialiasEnabled = false;
  426. for (const auto & tex : _atlasTextures)
  427. {
  428. tex.second->setAliasTexParameters();
  429. }
  430. }
  431. }
  432. void FontAtlas::setAntiAliasTexParameters()
  433. {
  434. if (! _antialiasEnabled)
  435. {
  436. _antialiasEnabled = true;
  437. for (const auto & tex : _atlasTextures)
  438. {
  439. tex.second->setAntiAliasTexParameters();
  440. }
  441. }
  442. }
  443. NS_CC_END