CCFontAtlas.cpp 16 KB

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