diff --git a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 9e007ea849..07bbc0b4a4 100644 --- a/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1feddf59d7fbc2b063a496bbf4a4770d0ac4435e \ No newline at end of file +b347c177e552f5a7b345253c78b21dad031a9d8a \ No newline at end of file diff --git a/cocos2dx/Android.mk b/cocos2dx/Android.mk index f2f22e0231..a44da2990e 100644 --- a/cocos2dx/Android.mk +++ b/cocos2dx/Android.mk @@ -65,18 +65,14 @@ label_nodes/CCFont.cpp \ label_nodes/CCFontAtlas.cpp \ label_nodes/CCFontAtlasCache.cpp \ label_nodes/CCFontAtlasFactory.cpp \ -label_nodes/CCFontCache.cpp \ label_nodes/CCFontDefinition.cpp \ label_nodes/CCFontFNT.cpp \ label_nodes/CCFontFreeType.cpp \ -label_nodes/CCFontRenderFreeType.cpp \ label_nodes/CCLabel.cpp \ label_nodes/CCLabelAtlas.cpp \ label_nodes/CCLabelBMFont.cpp \ label_nodes/CCLabelTTF.cpp \ label_nodes/CCLabelTextFormatter.cpp \ -label_nodes/CCStringBMFont.cpp \ -label_nodes/CCStringTTF.cpp \ label_nodes/CCTextImage.cpp \ layers_scenes_transitions_nodes/CCLayer.cpp \ layers_scenes_transitions_nodes/CCScene.cpp \ diff --git a/cocos2dx/include/cocos2d.h b/cocos2dx/include/cocos2d.h index 8ab33a8931..01e5739d96 100755 --- a/cocos2dx/include/cocos2d.h +++ b/cocos2dx/include/cocos2d.h @@ -99,8 +99,7 @@ THE SOFTWARE. #include "label_nodes/CCLabelAtlas.h" #include "label_nodes/CCLabelTTF.h" #include "label_nodes/CCLabelBMFont.h" -#include "label_nodes/CCStringBMFont.h" -#include "label_nodes/CCStringTTF.h" +#include "label_nodes/CCLabel.h" // layers_scenes_transitions_nodes #include "layers_scenes_transitions_nodes/CCLayer.h" diff --git a/cocos2dx/label_nodes/CCFont.cpp b/cocos2dx/label_nodes/CCFont.cpp index 858d69fc01..47381c0d8b 100644 --- a/cocos2dx/label_nodes/CCFont.cpp +++ b/cocos2dx/label_nodes/CCFont.cpp @@ -25,8 +25,88 @@ #include "CCFont.h" #include "support/ccUTF8.h" +#include "CCFontFNT.h" +#include "CCFontFreeType.h" + NS_CC_BEGIN +const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ "; + +const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; + + +Font::Font() : _usedGlyphs(GlyphCollection::ASCII), _customGlyphs(nullptr) +{ +} + +const char * Font::getGlyphCollection(GlyphCollection glyphs) +{ + switch (glyphs) + { + case GlyphCollection::NEHE: + return _glyphNEHE; + break; + + case GlyphCollection::ASCII: + return _glyphASCII; + break; + + default: + return 0; + break; + } +} + +void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs) +{ + if (_customGlyphs) + delete [] _customGlyphs; + + switch (glyphs) + { + case GlyphCollection::NEHE: + _customGlyphs = 0; + break; + + case GlyphCollection::ASCII: + _customGlyphs = 0; + break; + + default: + + int lenght = strlen(customGlyphs); + _customGlyphs = new char [lenght + 2]; + memcpy(_customGlyphs, customGlyphs, lenght); + + _customGlyphs[lenght] = 0; + _customGlyphs[lenght+1] = 0; + + break; + } +} + +const char * Font::getCurrentGlyphCollection() +{ + if (_customGlyphs) + { + return _customGlyphs; + } + else + { + return getGlyphCollection(_usedGlyphs); + } +} + +Font* Font::createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) +{ + return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs); +} + +Font* Font::createWithFNT(const char* fntFilePath) +{ + return FontFNT::create(fntFilePath); +} + unsigned short int * Font::getUTF16Text(const char *pText, int &outNumLetters) { unsigned short* utf16String = cc_utf8_to_utf16(pText); diff --git a/cocos2dx/label_nodes/CCFont.h b/cocos2dx/label_nodes/CCFont.h index 1d40b5c11c..33c098fc25 100644 --- a/cocos2dx/label_nodes/CCFont.h +++ b/cocos2dx/label_nodes/CCFont.h @@ -26,31 +26,54 @@ #define _CCFont_h_ #include + #include "cocos2d.h" +#include "CCLabel.h" NS_CC_BEGIN +// fwd class GlyphDef; +class FontAtlas; + class CC_DLL Font : public Object { public: + + // create the font + static Font* createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); + static Font* createWithFNT(const char* fntFilePath); - virtual ~Font() {} - + virtual FontAtlas *createFontAtlas() = 0; + virtual Size * getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters) = 0; + virtual const char * getCurrentGlyphCollection(); - virtual bool createFontObject(const std::string &fontName, int fontSize) { return false; } virtual int getLetterPadding() { return 0; } virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) { return 0; } - virtual int getFontMaxHeight() { return 0; } virtual GlyphDef * getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text = false) { return 0; } + virtual int getFontMaxHeight() { return 0; } virtual Rect getRectForChar(unsigned short theChar); - virtual unsigned short int * getUTF16Text(const char *pText, int &outNumLetters); virtual int getUTF16TextLenght(unsigned short int *pText); + virtual unsigned short int * getUTF16Text(const char *pText, int &outNumLetters); virtual unsigned short int * trimUTF16Text(unsigned short int *pText, int newBegin, int newEnd); +protected: + + Font(); + virtual ~Font() {} + void setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs = 0); + const char * getGlyphCollection(GlyphCollection glyphs); + +private: + + GlyphCollection _usedGlyphs; + char * _customGlyphs; + static const char * _glyphASCII; + static const char * _glyphNEHE; + }; NS_CC_END diff --git a/cocos2dx/label_nodes/CCFontAtlas.cpp b/cocos2dx/label_nodes/CCFontAtlas.cpp index 02d3e074d9..7b4f721beb 100644 --- a/cocos2dx/label_nodes/CCFontAtlas.cpp +++ b/cocos2dx/label_nodes/CCFontAtlas.cpp @@ -27,11 +27,8 @@ void FontAtlas::relaseTextures() { for( auto &item: _atlasTextures) { - if ( item.second ) - item.second->release(); + item.second->release(); } - - _atlasTextures.clear(); } void FontAtlas::addLetterDefinition(const FontLetterDefinition &letterDefinition) @@ -39,7 +36,7 @@ void FontAtlas::addLetterDefinition(const FontLetterDefinition &letterDefinition _fontLetterDefinitions[letterDefinition.letteCharUTF16] = letterDefinition; } -bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition) const +bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition) { auto outIterator = _fontLetterDefinitions.find(letteCharUTF16); @@ -60,12 +57,12 @@ void FontAtlas::addTexture(Texture2D &texture, int slot) _atlasTextures[slot] = &texture; } -Texture2D & FontAtlas::getTexture(int slot) +Texture2D & FontAtlas::getTexture(int slot) { return *(_atlasTextures[slot]); } -float FontAtlas::getCommonLineHeight() const +float FontAtlas::getCommonLineHeight() { return _commonLineHeight; } @@ -75,21 +72,9 @@ void FontAtlas::setCommonLineHeight(float newHeight) _commonLineHeight = newHeight; } -unsigned short int * FontAtlas::getUTF16Text(const char *pText, int &outNumLetters) const -{ - unsigned short* utf16String = cc_utf8_to_utf16(pText); - - if(!utf16String) - return 0; - - outNumLetters = cc_wcslen(utf16String); - return utf16String; -} - -Font & FontAtlas::getFont() const +Font & FontAtlas::getFont() { return _font; } - NS_CC_END \ No newline at end of file diff --git a/cocos2dx/label_nodes/CCFontAtlas.h b/cocos2dx/label_nodes/CCFontAtlas.h index 4875de6e54..1dd42f9974 100644 --- a/cocos2dx/label_nodes/CCFontAtlas.h +++ b/cocos2dx/label_nodes/CCFontAtlas.h @@ -24,11 +24,13 @@ #ifndef _CCFontAtlas_h_ #define _CCFontAtlas_h_ - #include NS_CC_BEGIN +//fwd +class Font; + struct FontLetterDefinition { unsigned short letteCharUTF16; @@ -47,20 +49,20 @@ struct FontLetterDefinition class CC_DLL FontAtlas : public Object { - public: FontAtlas(Font &theFont); virtual ~FontAtlas(); void addLetterDefinition(const FontLetterDefinition &letterDefinition); - bool getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition) const; - void addTexture(Texture2D &texture, int slot); - Texture2D & getTexture(int slot); + bool getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition); + + void addTexture(Texture2D &texture, int slot); + float getCommonLineHeight(); void setCommonLineHeight(float newHeight); - float getCommonLineHeight() const; - unsigned short int * getUTF16Text(const char *pText, int &outNumLetters) const; - Font & getFont() const; + + Texture2D & getTexture(int slot); + Font & getFont(); private: diff --git a/cocos2dx/label_nodes/CCFontAtlasCache.cpp b/cocos2dx/label_nodes/CCFontAtlasCache.cpp index 4c4b1de435..762a506ae4 100644 --- a/cocos2dx/label_nodes/CCFontAtlasCache.cpp +++ b/cocos2dx/label_nodes/CCFontAtlasCache.cpp @@ -30,24 +30,16 @@ NS_CC_BEGIN std::map FontAtlasCache::_atlasMap; - FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs) { std::string atlasName = generateFontName(fontFileName, size, glyphs); - FontAtlas *tempAtlas = _atlasMap[atlasName]; + FontAtlas *tempAtlas = _atlasMap[atlasName]; if ( !tempAtlas ) { tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs); - if (tempAtlas) - { _atlasMap[atlasName] = tempAtlas; - } - else - { - return nullptr; - } } else { @@ -65,15 +57,8 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const char *fontFileName) if ( !tempAtlas ) { tempAtlas = FontAtlasFactory::createAtlasFromFNT(fontFileName); - if (tempAtlas) - { _atlasMap[atlasName] = tempAtlas; - } - else - { - return nullptr; - } } else { @@ -89,7 +74,6 @@ std::string FontAtlasCache::generateFontName(const char *fontFileName, int size, switch (theGlyphs) { - case GlyphCollection::DYNAMIC: tempName.append("_DYNAMIC_"); break; @@ -110,9 +94,9 @@ std::string FontAtlasCache::generateFontName(const char *fontFileName, int size, break; } + // std::to_string is not supported on android, using std::stringstream instead. std::stringstream ss; ss << size; - // std::to_string is not supported on android, using std::stringstream instead. return tempName.append(ss.str()); } @@ -120,7 +104,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas *atlas) { if (atlas) { - for( auto &item: _atlasMap) + for( auto &item: _atlasMap ) { if ( item.second == atlas ) { diff --git a/cocos2dx/label_nodes/CCFontAtlasCache.h b/cocos2dx/label_nodes/CCFontAtlasCache.h index 2db750f039..c63c832d48 100644 --- a/cocos2dx/label_nodes/CCFontAtlasCache.h +++ b/cocos2dx/label_nodes/CCFontAtlasCache.h @@ -40,7 +40,8 @@ public: static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0); static FontAtlas * getFontAtlasFNT(const char *fontFileName); - static bool releaseFontAtlas(FontAtlas *atlas); + + static bool releaseFontAtlas(FontAtlas *atlas); private: diff --git a/cocos2dx/label_nodes/CCFontAtlasFactory.cpp b/cocos2dx/label_nodes/CCFontAtlasFactory.cpp index e1bcbf5f6e..8ea4a024fc 100644 --- a/cocos2dx/label_nodes/CCFontAtlasFactory.cpp +++ b/cocos2dx/label_nodes/CCFontAtlasFactory.cpp @@ -14,154 +14,29 @@ NS_CC_BEGIN - -const char *FontAtlasFactory::glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ "; - -const char *FontAtlasFactory::glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; - - - FontAtlas * FontAtlasFactory::createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { - FontDefinitionTTF *def = 0; - if ( (glyphs == GlyphCollection::NEHE) || (glyphs == GlyphCollection::ASCII) ) + if( glyphs == GlyphCollection::DYNAMIC ) { - def = FontDefinitionTTF::create(fntFilePath, fontSize, getGlyphCollection(glyphs)); - } - else - { - if( glyphs == GlyphCollection::DYNAMIC ) - { - log("ERROR: GlyphCollection::DYNAMIC is not supported yet!"); - return nullptr; - } - else - { - if ( !customGlyphs ) - { - log("ERROR: GlyphCollection::CUSTOM used but no input glyphs provided!"); - return nullptr; - } - - def = FontDefinitionTTF::create(fntFilePath, fontSize, customGlyphs); - } - } - - if(!def) + log("ERROR: GlyphCollection::DYNAMIC is not supported yet!"); return nullptr; + } - // create the font atlas from the font definition - FontAtlas *tempAtlas = def->createFontAtlas(); - - // release the font definition, we don't need it anymore - def->release(); - - // return the atlas - return tempAtlas; + Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs); + if (font) + return font->createFontAtlas(); + else + return nullptr; } FontAtlas * FontAtlasFactory::createAtlasFromFNT(const char* fntFilePath) { - CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath); + Font *pFont = Font::createWithFNT(fntFilePath); - if (newConf) - return createFontAtlasFromFNTConfig(newConf); + if(pFont) + return pFont->createFontAtlas(); else - return 0; -} - -const char * FontAtlasFactory::getGlyphCollection(GlyphCollection glyphs) -{ - switch (glyphs) - { - case GlyphCollection::NEHE: - return glyphNEHE; - break; - - case GlyphCollection::ASCII: - return glyphASCII; - break; - - default: - return 0; - break; - } -} - -FontAtlas * FontAtlasFactory::createFontAtlasFromFNTConfig(CCBMFontConfiguration *theConfig) -{ - if (!theConfig) - return 0; - - FontFNT *tempFont = new FontFNT(theConfig); - if (!tempFont) - return 0; - - FontAtlas *tempAtlas = new FontAtlas(*tempFont); - if (!tempAtlas) - return 0; - - // check that everything is fine with the BMFontCofniguration - if (!theConfig->_fontDefDictionary) - return 0; - - - int numGlyphs = theConfig->_characterSet->size(); - if (!numGlyphs) - return 0; - - if (theConfig->_commonHeight == 0) - return 0; - - // commone height - tempAtlas->setCommonLineHeight(theConfig->_commonHeight); - - - ccBMFontDef fontDef; - tFontDefHashElement *current_element, *tmp; - - // Purge uniform hash - HASH_ITER(hh, theConfig->_fontDefDictionary, current_element, tmp) - { - - FontLetterDefinition tempDefinition; - - fontDef = current_element->fontDef; - Rect tempRect; - - tempRect = fontDef.rect; - tempRect = CC_RECT_PIXELS_TO_POINTS(tempRect); - - tempDefinition.letteCharUTF16 = fontDef.charID; - - tempDefinition.offsetX = fontDef.xOffset; - tempDefinition.offsetY = fontDef.yOffset; - - tempDefinition.U = tempRect.origin.x; - tempDefinition.V = tempRect.origin.y; - - tempDefinition.width = tempRect.size.width; - tempDefinition.height = tempRect.size.height; - - //carloX: only one texture supported FOR NOW - tempDefinition.textureID = 0; - - tempDefinition.anchorX = 0.5f; - tempDefinition.anchorY = 0.5f; - - // add the new definition - tempAtlas->addLetterDefinition(tempDefinition); - } - - // add the texture (only one texture for now) - - Texture2D *tempTexture = TextureCache::getInstance()->addImage(theConfig->getAtlasName()); - if (!tempTexture) - return 0; - - // add the texture - tempAtlas->addTexture(*tempTexture, 0); - return tempAtlas; + return nullptr; } NS_CC_END diff --git a/cocos2dx/label_nodes/CCFontAtlasFactory.h b/cocos2dx/label_nodes/CCFontAtlasFactory.h index ab1a1da700..f1b785f4c1 100644 --- a/cocos2dx/label_nodes/CCFontAtlasFactory.h +++ b/cocos2dx/label_nodes/CCFontAtlasFactory.h @@ -28,6 +28,7 @@ #include "cocos2d.h" #include "CCFontAtlas.h" + NS_CC_BEGIN class CC_DLL FontAtlasFactory @@ -39,15 +40,6 @@ public: static FontAtlas * createAtlasFromFNT(const char* fntFilePath); private: - - static const char * getGlyphCollection(GlyphCollection glyphs); - - // carloX: this needs to be moved somewhere else, but it's good enough for now - static FontAtlas * createFontAtlasFromFNTConfig(CCBMFontConfiguration *theConfig); - - static const char *glyphASCII; - static const char *glyphNEHE; - }; NS_CC_END diff --git a/cocos2dx/label_nodes/CCFontDefinition.cpp b/cocos2dx/label_nodes/CCFontDefinition.cpp index 09502c941e..777162fe62 100644 --- a/cocos2dx/label_nodes/CCFontDefinition.cpp +++ b/cocos2dx/label_nodes/CCFontDefinition.cpp @@ -27,19 +27,27 @@ NS_CC_BEGIN +const int FontDefinitionTTF::_DEFAUL_ATALS_TEXTURE_SIZE = 1024; FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) { } -FontDefinitionTTF* FontDefinitionTTF::create(const char *fontName, int fontSize, const char *letters, int textureSize ) +FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) { + if (textureSize == 0) + textureSize = _DEFAUL_ATALS_TEXTURE_SIZE; + FontDefinitionTTF *ret = new FontDefinitionTTF; if(!ret) return 0; - if ( ret->initDefinition( fontName, fontSize, letters, textureSize ) ) + const char *pGlyph = font->getCurrentGlyphCollection(); + if (!pGlyph) + return nullptr; + + if ( ret->initDefinition(font, pGlyph, textureSize ) ) { return ret; } @@ -102,17 +110,15 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) if (tempDef.validDefinition) { - tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); - tempDef.width = letterWidth + currentGlyph.getPadding(); - tempDef.height = (letterHeight - 1); - tempDef.U = (posXUV - 1); - tempDef.V = posYUV; - - tempDef.offsetX = currentGlyph.getRect().origin.x; - tempDef.offsetY = currentGlyph.getRect().origin.y; - - tempDef.textureID = cPages; - tempDef.commonLineHeight = currentGlyph.getCommonHeight(); + tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); + tempDef.width = letterWidth + currentGlyph.getPadding(); + tempDef.height = (letterHeight - 1); + tempDef.U = (posXUV - 1); + tempDef.V = posYUV; + tempDef.offsetX = currentGlyph.getRect().origin.x; + tempDef.offsetY = currentGlyph.getRect().origin.y; + tempDef.textureID = cPages; + tempDef.commonLineHeight = currentGlyph.getCommonHeight(); // take from pixels to points tempDef.width = tempDef.width / CC_CONTENT_SCALE_FACTOR(); @@ -125,15 +131,15 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) } else { - tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); - tempDef.commonLineHeight = 0; - tempDef.width = 0; - tempDef.height = 0; - tempDef.U = 0; - tempDef.V = 0; - tempDef.offsetX = 0; - tempDef.offsetY = 0; - tempDef.textureID = 0; + tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); + tempDef.commonLineHeight = 0; + tempDef.width = 0; + tempDef.height = 0; + tempDef.U = 0; + tempDef.V = 0; + tempDef.offsetX = 0; + tempDef.offsetY = 0; + tempDef.textureID = 0; } @@ -156,14 +162,14 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) return true; } -bool FontDefinitionTTF::initDefinition(const char *fontName, int fontSize, const char *letters, int textureSize) +bool FontDefinitionTTF::initDefinition(cocos2d::Font *font, const char *letters, int textureSize) { // preare texture/image stuff _textImages = new TextImage(); if (!_textImages) return false; - if (!_textImages->initWithString(letters, textureSize, textureSize, fontName, fontSize, true)) + if (!_textImages->initWithString(letters, textureSize, textureSize, font, true)) { delete _textImages; _textImages = 0; @@ -182,50 +188,32 @@ void FontDefinitionTTF::addLetterDefinition(FontLetterDefinition &defToAdd) } } -FontLetterDefinition & FontDefinitionTTF::getLetterDefinition(unsigned short int theLetter) -{ - return _fontLettersDefinitionUTF16[theLetter]; -} - -Texture2D * FontDefinitionTTF::getTexture(int index) -{ - TextFontPagesDef *pPages = _textImages->getPages(); - - if (!pPages) - return nullptr; - - return pPages->getPageAt(index)->getPageTexture(); -} - -int FontDefinitionTTF::getNumTextures() -{ - TextFontPagesDef *pPages = _textImages->getPages(); - if (pPages) - { - return pPages->getNumPages(); - } - - return 0; -} - FontAtlas * FontDefinitionTTF::createFontAtlas() { - FontAtlas *retAtlas = new FontAtlas( *_textImages->getFont() ); + int numTextures = 0; + TextFontPagesDef *pPages = _textImages->getPages(); + + if (pPages) + numTextures = pPages->getNumPages(); + else + return nullptr; + + if (!numTextures) + return nullptr; + + FontAtlas *retAtlas = new FontAtlas(*_textImages->getFont()); if (!retAtlas) return 0; - // add all the textures - int numTextures = getNumTextures(); - if (!numTextures) - return 0; - - for (int c = 0; caddTexture(*getTexture(c), c); + for (int c = 0; c < numTextures; ++c) + { + TextFontPagesDef *pPages = _textImages->getPages(); + retAtlas->addTexture(*(pPages->getPageAt(c)->getPageTexture()), c); + } // set the common line height - retAtlas->setCommonLineHeight(getCommonLineHeight() * 0.8); - + retAtlas->setCommonLineHeight(_commonLineHeight * 0.8); for( auto &item: _fontLettersDefinitionUTF16 ) { diff --git a/cocos2dx/label_nodes/CCFontDefinition.h b/cocos2dx/label_nodes/CCFontDefinition.h index 3229b4b21a..cd1d8c8ef3 100644 --- a/cocos2dx/label_nodes/CCFontDefinition.h +++ b/cocos2dx/label_nodes/CCFontDefinition.h @@ -31,20 +31,13 @@ NS_CC_BEGIN -#define DEFAULT_ATLAS_TEXTURE_SIZE 1024 - /** */ class CC_DLL FontDefinitionTTF : public Object { public: - - static FontDefinitionTTF* create(const char *fontName, int fontSize, const char *letters, int textureSize = DEFAULT_ATLAS_TEXTURE_SIZE); - FontLetterDefinition & getLetterDefinition(unsigned short int theLetter); - Texture2D * getTexture(int index); - int getNumTextures(); - Font * getFont() { return _textImages->getFont(); } - float getCommonLineHeight() { return _commonLineHeight; } + + static FontDefinitionTTF* create(Font *font, int textureSize = 0); FontAtlas * createFontAtlas(); private: @@ -52,13 +45,14 @@ private: FontDefinitionTTF(); ~FontDefinitionTTF(); - bool initDefinition(const char *fontName, int fontSize, const char *letters, int textureSize); + bool initDefinition(Font *font, const char *letters, int textureSize); bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); void addLetterDefinition(FontLetterDefinition &defToAdd); TextImage * _textImages; std::map _fontLettersDefinitionUTF16; float _commonLineHeight; + static const int _DEFAUL_ATALS_TEXTURE_SIZE; }; diff --git a/cocos2dx/label_nodes/CCFontFNT.cpp b/cocos2dx/label_nodes/CCFontFNT.cpp index 84384bcb2d..f980656d2b 100644 --- a/cocos2dx/label_nodes/CCFontFNT.cpp +++ b/cocos2dx/label_nodes/CCFontFNT.cpp @@ -7,10 +7,34 @@ // #include "CCFontFNT.h" - +#include "CCFontAtlas.h" NS_CC_BEGIN +FontFNT * FontFNT::create(const char* fntFilePath) +{ + CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath); + if (!newConf) + return nullptr; + + // add the texture + Texture2D *tempTexture = TextureCache::getInstance()->addImage(newConf->getAtlasName()); + if ( !tempTexture ) + { + delete newConf; + return nullptr; + } + + FontFNT *tempFont = new FontFNT(newConf); + + if (!tempFont) + { + delete newConf; + return nullptr; + } + + return tempFont; +} FontFNT::~FontFNT() { @@ -100,4 +124,75 @@ Rect FontFNT::getRectForChar(unsigned short theChar) return getRectForCharInternal(theChar); } +FontAtlas * FontFNT::createFontAtlas() +{ + FontAtlas *tempAtlas = new FontAtlas(*this); + if (!tempAtlas) + return nullptr; + + // check that everything is fine with the BMFontCofniguration + if (!_configuration->_fontDefDictionary) + return nullptr; + + int numGlyphs = _configuration->_characterSet->size(); + if (!numGlyphs) + return nullptr; + + if (_configuration->_commonHeight == 0) + return nullptr; + + // commone height + tempAtlas->setCommonLineHeight(_configuration->_commonHeight); + + + ccBMFontDef fontDef; + tFontDefHashElement *current_element, *tmp; + + // Purge uniform hash + HASH_ITER(hh, _configuration->_fontDefDictionary, current_element, tmp) + { + + FontLetterDefinition tempDefinition; + + fontDef = current_element->fontDef; + Rect tempRect; + + tempRect = fontDef.rect; + tempRect = CC_RECT_PIXELS_TO_POINTS(tempRect); + + tempDefinition.letteCharUTF16 = fontDef.charID; + + tempDefinition.offsetX = fontDef.xOffset; + tempDefinition.offsetY = fontDef.yOffset; + + tempDefinition.U = tempRect.origin.x; + tempDefinition.V = tempRect.origin.y; + + tempDefinition.width = tempRect.size.width; + tempDefinition.height = tempRect.size.height; + + //carloX: only one texture supported FOR NOW + tempDefinition.textureID = 0; + + tempDefinition.anchorX = 0.5f; + tempDefinition.anchorY = 0.5f; + + // add the new definition + tempAtlas->addLetterDefinition(tempDefinition); + } + + // add the texture (only one texture for now) + + Texture2D *tempTexture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); + if (!tempTexture) + return 0; + + // add the texture + tempAtlas->addTexture(*tempTexture, 0); + + // done + return tempAtlas; +} + + NS_CC_END \ No newline at end of file diff --git a/cocos2dx/label_nodes/CCFontFNT.h b/cocos2dx/label_nodes/CCFontFNT.h index a8db12020a..9e6a654095 100644 --- a/cocos2dx/label_nodes/CCFontFNT.h +++ b/cocos2dx/label_nodes/CCFontFNT.h @@ -35,10 +35,16 @@ class FontFNT : public Font public: + static FontFNT * create(const char* fntFilePath); + + virtual Size* getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters) override; + virtual Rect getRectForChar(unsigned short theChar) override; + virtual FontAtlas *createFontAtlas() override; + +protected: + FontFNT(CCBMFontConfiguration *theContfig) : _configuration(theContfig) {} virtual ~FontFNT(); - virtual Size* getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters); - virtual Rect getRectForChar(unsigned short theChar); private: diff --git a/cocos2dx/label_nodes/CCFontFreeType.cpp b/cocos2dx/label_nodes/CCFontFreeType.cpp index 01c86f1d90..bc82ac686e 100644 --- a/cocos2dx/label_nodes/CCFontFreeType.cpp +++ b/cocos2dx/label_nodes/CCFontFreeType.cpp @@ -23,10 +23,12 @@ ****************************************************************************/ #include -#include "cocos2d.h" + #include "support/ccUTF8.h" #include "CCFontFreeType.h" #include "CCTextImage.h" +#include "CCFont.h" +#include "CCFontDefinition.h" NS_CC_BEGIN @@ -34,7 +36,29 @@ NS_CC_BEGIN FT_Library FontFreeType::_FTlibrary; bool FontFreeType::_FTInitialized = false; - +FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) +{ + if( glyphs == GlyphCollection::DYNAMIC ) + { + log("ERROR: GlyphCollection::DYNAMIC is not supported yet!"); + return nullptr; + } + + FontFreeType *tempFont = new FontFreeType(); + + if (!tempFont) + return nullptr; + + tempFont->setCurrentGlyphCollection(glyphs, customGlyphs); + + if( !tempFont->createFontObject(fontName, fontSize)) + { + delete tempFont; + return nullptr; + } + + return tempFont; +} bool FontFreeType::initFreeType() { @@ -111,6 +135,21 @@ FontFreeType::~FontFreeType() // TO DO } +FontAtlas * FontFreeType::createFontAtlas() +{ + FontDefinitionTTF *def = 0; + def = FontDefinitionTTF::create(this); + + if(!def) + return nullptr; + + FontAtlas *atlas = def->createFontAtlas(); + + // release the font definition, we don't need it anymore + def->release(); + return atlas; +} + bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) { if (!_fontRef) @@ -276,7 +315,7 @@ int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsign if (!_fontRef) return 0; - bool hasKerning = FT_HAS_KERNING( _fontRef ); + bool hasKerning = FT_HAS_KERNING( _fontRef ) != 0; if (!hasKerning) return 0; diff --git a/cocos2dx/label_nodes/CCFontFreeType.h b/cocos2dx/label_nodes/CCFontFreeType.h index f6e7273452..a0fc6e1d3f 100644 --- a/cocos2dx/label_nodes/CCFontFreeType.h +++ b/cocos2dx/label_nodes/CCFontFreeType.h @@ -25,9 +25,11 @@ #ifndef _FontFreetype_h_ #define _FontFreetype_h_ -#include "CCFont.h" #include #include + +#include "CCFont.h" + #include FT_FREETYPE_H NS_CC_BEGIN @@ -36,19 +38,24 @@ class CC_DLL FontFreeType : public Font { public: + static FontFreeType * create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); + + virtual FontAtlas * createFontAtlas() override; + virtual Size * getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters) override; + virtual GlyphDef * getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text = false) override; + unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) override; + virtual int getFontMaxHeight() override; + virtual int getLetterPadding() override; + + +protected: + FontFreeType(); virtual ~FontFreeType(); - - virtual Size * getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters); - - virtual bool createFontObject(const std::string &fontName, int fontSize); - virtual GlyphDef * getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text = false); - unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight); - virtual int getFontMaxHeight(); - virtual int getLetterPadding(); + bool createFontObject(const std::string &fontName, int fontSize); private: - + bool initFreeType(); void shutdownFreeType(); FT_Library getFTLibrary(); @@ -60,10 +67,8 @@ private: static FT_Library _FTlibrary; static bool _FTInitialized; - FT_Face _fontRef; const int _letterPadding; - std::string _fontName; }; diff --git a/cocos2dx/label_nodes/CCFontRender.h b/cocos2dx/label_nodes/CCFontRender.h deleted file mode 100644 index 5c7bf62807..0000000000 --- a/cocos2dx/label_nodes/CCFontRender.h +++ /dev/null @@ -1,51 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _FontRender_h_ -#define _FontRender_h_ - -NS_CC_BEGIN - -// FWD -class Font; -class TextPageDef; - -class CC_DLL FontRender -{ - -public: - - FontRender(Font *pFont) { _font = pFont; } - virtual ~FontRender() {} - virtual unsigned char * preparePageGlyphData(TextPageDef *thePage) = 0; - -protected: - - Font * _font; -}; - -NS_CC_END - - -#endif diff --git a/cocos2dx/label_nodes/CCFontRenderFreeType.cpp b/cocos2dx/label_nodes/CCFontRenderFreeType.cpp deleted file mode 100644 index b471da6135..0000000000 --- a/cocos2dx/label_nodes/CCFontRenderFreeType.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "cocos2d.h" -#include "CCTextImage.h" -#include "CCFontRenderFreeType.h" - -#include -#include FT_FREETYPE_H - -//#define _DEBUG_FONTS_ -#ifdef _DEBUG_FONTS_ -#include "CCImage.h" -#endif - - -NS_CC_BEGIN - -bool FontRenderFreeType::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) -{ - if (!_font) - return false; - - unsigned char *sourceBitmap = 0; - int sourceWidth = 0; - int sourceHeight = 0; - - // get the glyph's bitmap - sourceBitmap = _font->getGlyphBitmap(charToRender, sourceWidth, sourceHeight); - - if(!sourceBitmap) - return false; - - int iX = posX; - int iY = posY; - - for (int y = 0; y < sourceHeight; ++y) - { - int bitmap_y = y * sourceWidth; - - for (int x = 0; x < sourceWidth; ++x) - { - unsigned char cTemp = sourceBitmap[bitmap_y + x]; - - // the final pixel - int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp; - *(int*) &destMemory[(iX + ( iY * destSize ) ) * 4] = iTemp; - - iX += 1; - } - - iX = posX; - iY += 1; - } - - //everything good - return true; -} - -unsigned char * FontRenderFreeType::preparePageGlyphData(TextPageDef *thePage) -{ - if (!thePage) - return 0; - - if (!_font) - return 0; - - if (thePage->getNumLines() == 0) - return NULL; - - int pageWidth = thePage->getWidth(); - int pageHeight = thePage->getHeight(); - - // prepare memory and clean to 0 - int sizeInBytes = (pageWidth * pageHeight * 4); - unsigned char* data = new unsigned char[sizeInBytes]; - - if (!data) - return 0; - - memset(data, 0, sizeInBytes); - - int numLines = thePage->getNumLines(); - - for (int c = 0; cgetLineAt(c); - - float origX = _font->getLetterPadding(); - float origY = pCurrentLine->getY(); - - int numGlyphToRender = pCurrentLine->getNumGlyph(); - - for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph) - { - GlyphDef currGlyph = pCurrentLine->getGlyphAt(cglyph); - renderCharAt(currGlyph.getUTF8Letter(), origX, origY, data, pageWidth); - origX += (currGlyph.getRect().size.width + _font->getLetterPadding()); - } - } - -#ifdef _DEBUG_FONTS_ - static int counter = 0; - char outFilename[512]; - sprintf(outFilename,"carlottone%d", counter); - ++counter; - Image *pImage = new Image; - pImage->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false); - pImage->saveToFile(outFilename); -#endif - - // we are done here - return data; -} - - -NS_CC_END \ No newline at end of file diff --git a/cocos2dx/label_nodes/CCFontRenderFreeType.h b/cocos2dx/label_nodes/CCFontRenderFreeType.h deleted file mode 100644 index 41e50fbee5..0000000000 --- a/cocos2dx/label_nodes/CCFontRenderFreeType.h +++ /dev/null @@ -1,48 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _FontRenderFreeType_h_ -#define _FontRenderFreeType_h_ - -#include "CCFontRender.h" - -NS_CC_BEGIN - -class CC_DLL FontRenderFreeType : public FontRender -{ -public: - - FontRenderFreeType(Font *pFont): FontRender(pFont) {} - virtual ~FontRenderFreeType() {} - virtual unsigned char * preparePageGlyphData(TextPageDef *thePage); - -private: - - bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); - -}; - -NS_CC_END - -#endif diff --git a/cocos2dx/label_nodes/CCLabel.cpp b/cocos2dx/label_nodes/CCLabel.cpp index 553b4e05f4..345c62c138 100644 --- a/cocos2dx/label_nodes/CCLabel.cpp +++ b/cocos2dx/label_nodes/CCLabel.cpp @@ -23,66 +23,747 @@ ****************************************************************************/ #include "CCLabel.h" -#include "CCStringBMFont.h" -#include "CCStringTTF.h" #include "CCFontDefinition.h" -#include "CCFontCache.h" #include "CCFontAtlasCache.h" +#include "CCLabelTextFormatter.h" NS_CC_BEGIN -Label* Label::createWithTTF( const char* label, const char* fntFilePath, int fontSize, GlyphCollection glyphs, int lineSize, const char *customGlyphs ) +Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs ) { - FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasTTF(fntFilePath, fontSize, glyphs, customGlyphs); + FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath, fontSize, glyphs, customGlyphs); + if (!tempAtlas) return nullptr; - + // create the actual label - StringTTF* templabel = StringTTF::create(tempAtlas, TextHAlignment::CENTER, lineSize); + Label* templabel = Label::createWithAtlas(tempAtlas, alignment, lineSize); if (templabel) { - templabel->setText(label, lineSize, TextHAlignment::CENTER, false); + templabel->setText(label, lineSize, alignment, false); return templabel; } - + return nullptr; + + return 0; } -Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, int lineSize) +Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment, int lineSize) { + FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); - + if (!tempAtlas) return 0; - StringTTF* templabel = StringTTF::create(tempAtlas, TextHAlignment::CENTER, lineSize); + Label* templabel = Label::createWithAtlas(tempAtlas, alignment, lineSize); if (templabel) { - templabel->setText(label, lineSize, TextHAlignment::CENTER, false); + templabel->setText(label, lineSize, alignment, false); return templabel; } else { return 0; } + + return 0; +} + +Label* Label::createWithAtlas(FontAtlas *pAtlas, TextHAlignment alignment, int lineSize) +{ + Label *ret = new Label(pAtlas, alignment); + + if (!ret) + return 0; + + if( ret->init() ) + { + ret->autorelease(); + return ret; + } + else + { + delete ret; + return 0; + } + + return ret; +} + +Label::Label(FontAtlas *pAtlas, TextHAlignment alignment): _currentUTF8String(0), +_originalUTF8String(0), +_fontAtlas(pAtlas), +_alignment(alignment), +_lineBreakWithoutSpaces(false), +_advances(0), +_displayedColor(Color3B::WHITE), +_realColor(Color3B::WHITE), +_cascadeColorEnabled(true), +_cascadeOpacityEnabled(true), +_displayedOpacity(255), +_realOpacity(255), +_isOpacityModifyRGB(false) +{ +} + +Label::~Label() +{ + if (_currentUTF8String) + delete [] _currentUTF8String; + + if (_advances) + delete [] _advances; + + if (_fontAtlas) + FontAtlasCache::releaseFontAtlas(_fontAtlas); +} + +bool Label::init() +{ + return true; +} + +void Label::setString(const char *stringToRender) +{ + setText(stringToRender, _width, TextHAlignment::CENTER, false); +} + +bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) +{ + if (!_fontAtlas) + return false; + + // carloX + // reset the string + resetCurrentString(); + + + _width = lineWidth; + _alignment = alignment; + _lineBreakWithoutSpaces = lineBreakWithoutSpaces; + + // release all the sprites + moveAllSpritesToCache(); + + // store locally common line height + _commonLineHeight = _fontAtlas->getCommonLineHeight(); + if (_commonLineHeight <= 0) + return false; + + int numLetter = 0; + unsigned short* utf16String = cc_utf8_to_utf16(stringToRender); + if(!utf16String) + return false; + + numLetter = cc_wcslen(utf16String); + SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), numLetter); + _cascadeColorEnabled = true; + + // + setCurrentString(utf16String); + setOriginalString(utf16String); + + // align text + alignText(); + + // done here + return true; +} + +void Label::setAlignment(TextHAlignment alignment) +{ + // store the new alignment + if (alignment != _alignment) + { + // store + _alignment = alignment; + + // reset the string + resetCurrentString(); + + // need to align text again + alignText(); + } +} + +void Label::setWidth(float width) +{ + if (width != _width) + { + // store + _width = width; + + + // reset the string + resetCurrentString(); + + // need to align text again + alignText(); + } +} + +void Label::setLineBreakWithoutSpace(bool breakWithoutSpace) +{ + if (breakWithoutSpace != _lineBreakWithoutSpaces) + { + // store + _lineBreakWithoutSpaces = breakWithoutSpace; + + // need to align text again + alignText(); + } +} + +void Label::setScale(float scale) +{ + Node::setScale(scale); + alignText(); +} + +void Label::setScaleX(float scaleX) +{ + Node::setScaleX(scaleX); + alignText(); +} + +void Label::setScaleY(float scaleY) +{ + Node::setScaleY(scaleY); + alignText(); +} + +void Label::alignText() +{ + hideAllLetters(); + LabelTextFormatter::createStringSprites(this); + + if( LabelTextFormatter::multilineText(this) ) + { + hideAllLetters(); + LabelTextFormatter::createStringSprites(this); + } + + LabelTextFormatter::alignText(this); +} + +void Label::hideAllLetters() +{ + Object* Obj = NULL; + CCARRAY_FOREACH(&_spriteArray, Obj) + { + ((Sprite *)Obj)->setVisible(false); + } + + CCARRAY_FOREACH(&_spriteArrayCache, Obj) + { + ((Sprite *)Obj)->setVisible(false); + } +} + +bool Label::computeAdvancesForString(unsigned short int *stringToRender) +{ + if (_advances) + { + delete [] _advances; + _advances = 0; + } + + Font &theFont = _fontAtlas->getFont(); + + int letterCount = 0; + _advances = theFont.getAdvancesForTextUTF16(stringToRender, letterCount); + + if(!_advances) + return false; + else + return true; +} + +bool Label::setOriginalString(unsigned short *stringToSet) +{ + if (_originalUTF8String) + { + delete [] _originalUTF8String; + _originalUTF8String = 0; + } + + int newStringLenght = cc_wcslen(stringToSet); + _originalUTF8String = new unsigned short int [newStringLenght + 1]; + memset(_originalUTF8String, 0, (newStringLenght + 1) * 2); + memcpy(_originalUTF8String, stringToSet, (newStringLenght * 2)); + _originalUTF8String[newStringLenght] = 0; + + return true; +} + +bool Label::setCurrentString(unsigned short *stringToSet) +{ + // set the new string + if (_currentUTF8String) + { + delete [] _currentUTF8String; + _currentUTF8String = 0; + } + // + _currentUTF8String = stringToSet; + // compute the advances + return computeAdvancesForString(stringToSet); +} + +void Label::resetCurrentString() +{ + if ((!_currentUTF8String) && (!_originalUTF8String)) + return; + + // set the new string + if (_currentUTF8String) + { + delete [] _currentUTF8String; + _currentUTF8String = 0; + } + + int stringLenght = cc_wcslen(_originalUTF8String); + _currentUTF8String = new unsigned short int [stringLenght + 1]; + memcpy(_currentUTF8String, _originalUTF8String, stringLenght * 2); + _currentUTF8String[stringLenght] = 0; + +} + +Sprite * Label::createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture) +{ + Rect uvRect; + uvRect.size.height = theDefinition.height; + uvRect.size.width = theDefinition.width; + uvRect.origin.x = theDefinition.U; + uvRect.origin.y = theDefinition.V; + + SpriteFrame *pFrame = SpriteFrame::createWithTexture(theTexture, uvRect); + Sprite *tempSprite = getSprite(); + + if (!tempSprite) + return 0; + + tempSprite->initWithSpriteFrame(pFrame); + tempSprite->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); + tempSprite->setBatchNode(this); + + // Apply label properties + tempSprite->setOpacityModifyRGB(_isOpacityModifyRGB); + + // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on + tempSprite->updateDisplayedColor(_displayedColor); + tempSprite->updateDisplayedOpacity(_displayedOpacity); + + + return tempSprite; +} + +Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture) +{ + if (!spriteToUpdate) + { + return 0; + } + else + { + Rect uvRect; + uvRect.size.height = theDefinition.height; + uvRect.size.width = theDefinition.width; + uvRect.origin.x = theDefinition.U; + uvRect.origin.y = theDefinition.V; + + SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect); + if (frame) + { + spriteToUpdate->setTexture(theTexture); + spriteToUpdate->setDisplayFrame(frame); + spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); + spriteToUpdate->setBatchNode(this); + } + + return spriteToUpdate; + } +} + +Sprite * Label::getSpriteForLetter(unsigned short int newLetter) +{ + if (!_fontAtlas) + return 0; + + FontLetterDefinition tempDefinition; + bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition); + if (validDefinition) + { + Sprite *newSprite = createNewSpriteFromLetterDefinition(tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) ); + this->addChild(newSprite); + return newSprite; + } + else + { + return 0; + } } -Label::Label() +Sprite * Label::updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter) { + if (!spriteToUpdate || !_fontAtlas) + return 0; + else + { + FontLetterDefinition tempDefinition; + bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition); + if (validDefinition) + { + Sprite *pNewSprite = updateSpriteWithLetterDefinition(spriteToUpdate, tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) ); + return pNewSprite; + } + else + { + return 0; + } + } } -Label::~Label() +void Label::moveAllSpritesToCache() { + Object* pObj = NULL; + CCARRAY_FOREACH(&_spriteArray, pObj) + { + ((Sprite *)pObj)->removeFromParent(); + _spriteArrayCache.addObject(pObj); + } + + _spriteArray.removeAllObjects(); +} + +Sprite * Label::getSprite() +{ + if (_spriteArrayCache.count()) + { + Sprite *retSprite = (Sprite *) _spriteArrayCache.lastObject(); + _spriteArrayCache.removeLastObject(); + return retSprite; + } + else + { + Sprite *retSprite = new Sprite; + return retSprite; + } +} + +///// PROTOCOL STUFF + +Sprite * Label::getSpriteChild(int ID) +{ + Object* pObj = NULL; + CCARRAY_FOREACH(&_spriteArray, pObj) + { + Sprite *pSprite = (Sprite *)pObj; + if ( pSprite->getTag() == ID) + { + return pSprite; + } + } + return 0; +} + +Array * Label::getChildrenLetters() +{ + return &_spriteArray; +} + +Sprite * Label::getSpriteForChar(unsigned short int theChar, int spriteIndexHint) +{ + // ret sprite + Sprite *retSprite = 0; + + // look for already existing sprites + retSprite = getSpriteChild(spriteIndexHint); + + if (!retSprite) + { + retSprite = getSpriteForLetter(theChar); + if (!retSprite) + return 0; + + if (retSprite) + retSprite->setTag(spriteIndexHint); + + _spriteArray.addObject(retSprite); + } + + // the sprite is now visible + retSprite->setVisible(true); + + // set the right texture letter to the sprite + updateSpriteForLetter(retSprite, theChar); + + // we are done here + return retSprite; +} + +float Label::getLetterPosXLeft( Sprite* sp ) +{ + float scaleX = _scaleX; + return sp->getPosition().x * scaleX - (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x); +} + +float Label::getLetterPosXRight( Sprite* sp ) +{ + float scaleX = _scaleX; + return sp->getPosition().x * scaleX + (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x); +} + +int Label::getCommonLineHeight() +{ + return _commonLineHeight; +} + +int Label::getKerningForCharsPair(unsigned short first, unsigned short second) +{ + return 0; +} + +int Label::getXOffsetForChar(unsigned short c) +{ + FontLetterDefinition tempDefinition; + bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); + if (!validDefinition) + return -1; + + return (tempDefinition.offsetX); +} + +int Label::getYOffsetForChar(unsigned short c) +{ + FontLetterDefinition tempDefinition; + bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); + if (!validDefinition) + return -1; + + return (tempDefinition.offsetY); +} + +int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) +{ + if (_advances) + { + // not that advance contains the X offset already + FontLetterDefinition tempDefinition; + bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); + if (!validDefinition) + return -1; + + return (_advances[hintPositionInString].width); + } + else + { + return -1; + } +} + +Rect Label::getRectForChar(unsigned short c) +{ + return _fontAtlas->getFont().getRectForChar(c); +} + +// string related stuff +int Label::getStringNumLines() +{ + int quantityOfLines = 1; + + unsigned int stringLen = _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0; + if (stringLen == 0) + return (-1); + + // count number of lines + for (unsigned int i = 0; i < stringLen - 1; ++i) + { + unsigned short c = _currentUTF8String[i]; + if (c == '\n') + { + quantityOfLines++; + } + } + + return quantityOfLines; +} + +int Label::getStringLenght() +{ + return _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0; +} + +unsigned short Label::getCharAtStringPosition(int position) +{ + return _currentUTF8String[position]; +} + +unsigned short * Label::getUTF8String() +{ + return _currentUTF8String; +} + +void Label::assignNewUTF8String(unsigned short *newString) +{ + setCurrentString(newString); +} + +TextHAlignment Label::getTextAlignment() +{ + return _alignment; +} + +// label related stuff +float Label::getMaxLineWidth() +{ + return _width; +} + +bool Label::breakLineWithoutSpace() +{ + return _lineBreakWithoutSpaces; +} + +Size Label::getLabelContentSize() +{ + return getContentSize(); +} + +void Label::setLabelContentSize(const Size &newSize) +{ + setContentSize(newSize); } -// TESTING STUFF THAT NEEDS TO GO //////////////////////////////////////////////////////////////// -Label* Label::createWithBMFontOLD( const char* label, const char* bmfontFilePath, int lineSize) +// RGBA protocol + + +bool Label::isOpacityModifyRGB() const { - return StringBMFont::create(label, bmfontFilePath, lineSize); + return _isOpacityModifyRGB; } -////////////////////////////////////////////////////////////////////////////////////////////////// + +void Label::setOpacityModifyRGB(bool isOpacityModifyRGB) +{ + _isOpacityModifyRGB = isOpacityModifyRGB; + if (_children && _children->count() != 0) + { + Object* child; + CCARRAY_FOREACH(_children, child) + { + Node* pNode = static_cast( child ); + if (pNode) + { + RGBAProtocol *pRGBAProtocol = dynamic_cast(pNode); + if (pRGBAProtocol) + { + pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB); + } + } + } + } +} + +unsigned char Label::getOpacity() const +{ + return _realOpacity; +} + +unsigned char Label::getDisplayedOpacity() const +{ + return _displayedOpacity; +} + +void Label::setOpacity(GLubyte opacity) +{ + _displayedOpacity = _realOpacity = opacity; + + if( _cascadeOpacityEnabled ) { + GLubyte parentOpacity = 255; + RGBAProtocol* pParent = dynamic_cast(_parent); + if (pParent && pParent->isCascadeOpacityEnabled()) + { + parentOpacity = pParent->getDisplayedOpacity(); + } + this->updateDisplayedOpacity(parentOpacity); + } +} +void Label::updateDisplayedOpacity(GLubyte parentOpacity) +{ + _displayedOpacity = _realOpacity * parentOpacity/255.0; + + Object* pObj; + CCARRAY_FOREACH(_children, pObj) + { + Sprite *item = static_cast( pObj ); + item->updateDisplayedOpacity(_displayedOpacity); + } +} + +bool Label::isCascadeOpacityEnabled() const +{ + return false; +} + +void Label::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) +{ + _cascadeOpacityEnabled = cascadeOpacityEnabled; +} + +const Color3B& Label::getColor(void) const +{ + return _realColor; +} + +const Color3B& Label::getDisplayedColor() const +{ + return _displayedColor; +} + +void Label::setColor(const Color3B& color) +{ + _displayedColor = _realColor = color; + + if( _cascadeColorEnabled ) + { + Color3B parentColor = Color3B::WHITE; + RGBAProtocol* pParent = dynamic_cast(_parent); + + if (pParent && pParent->isCascadeColorEnabled()) + parentColor = pParent->getDisplayedColor(); + + updateDisplayedColor(parentColor); + } +} + +void Label::updateDisplayedColor(const Color3B& parentColor) +{ + _displayedColor.r = _realColor.r * parentColor.r/255.0; + _displayedColor.g = _realColor.g * parentColor.g/255.0; + _displayedColor.b = _realColor.b * parentColor.b/255.0; + + Object* pObj; + CCARRAY_FOREACH(_children, pObj) + { + Sprite *item = static_cast( pObj ); + item->updateDisplayedColor(_displayedColor); + } +} + +bool Label::isCascadeColorEnabled() const +{ + return false; +} + +void Label::setCascadeColorEnabled(bool cascadeColorEnabled) +{ + _cascadeColorEnabled = cascadeColorEnabled; +} + NS_CC_END \ No newline at end of file diff --git a/cocos2dx/label_nodes/CCLabel.h b/cocos2dx/label_nodes/CCLabel.h index 80fff701a6..fe1d16b742 100644 --- a/cocos2dx/label_nodes/CCLabel.h +++ b/cocos2dx/label_nodes/CCLabel.h @@ -27,6 +27,8 @@ #define _COCOS2D_CCLABEL_H_ #include "sprite_nodes/CCSpriteBatchNode.h" +#include "CCLabelTextFormatProtocol.h" +#include "ccTypes.h" NS_CC_BEGIN @@ -39,33 +41,126 @@ enum class GlyphCollection { }; -class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAProtocol +//fwd +struct FontLetterDefinition; +class FontAtlas; + + + +class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAProtocol, public LabelTextFormatProtocol { public: - static Label* createWithTTF( const char* label, const char* fntFilePath, int fontSize, GlyphCollection glyphs = GlyphCollection::NEHE, int lineSize = 0, const char *customGlyphs = 0 ); - static Label* createWithBMFont( const char* label, const char* bmfontFilePath, int lineSize = 0 ); + // static create + static Label* createWithTTF( const char* label, const char* fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0 ); - virtual ~Label(); - Label(); + static Label* createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0 ); - virtual void setAlignment(TextHAlignment alignment) = 0; - virtual void setWidth(float width) = 0; - virtual void setLineBreakWithoutSpace(bool breakWithoutSpace) = 0; - virtual void setScale(float scale) = 0; - virtual void setScaleX(float scaleX) = 0; - virtual void setScaleY(float scaleY) = 0; + bool setText(const char *stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); + virtual void setString(const char *stringToRender); + virtual void setAlignment(TextHAlignment alignment); + virtual void setWidth(float width); + virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); + virtual void setScale(float scale); + virtual void setScaleX(float scaleX); + virtual void setScaleY(float scaleY); + + // RGBAProtocol + virtual bool isOpacityModifyRGB() const; + virtual void setOpacityModifyRGB(bool isOpacityModifyRGB); + virtual void setOpacity(GLubyte opacity); + virtual void updateDisplayedOpacity(GLubyte parentOpacity); + virtual bool isCascadeOpacityEnabled() const; + virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled); + virtual void setColor(const Color3B& color); + virtual void updateDisplayedColor(const Color3B& parentColor); + virtual bool isCascadeColorEnabled() const; + virtual void setCascadeColorEnabled(bool cascadeColorEnabled); + virtual const Color3B& getColor(void) const; + virtual const Color3B& getDisplayedColor() const; + virtual unsigned char getOpacity() const; + virtual unsigned char getDisplayedOpacity() const; - // needs to go - TEST STUFF ///////////////////////////////////////////////////////////////////////// - static Label* createWithBMFontOLD( const char* label, const char* bmfontFilePath, int lineSize = 0); - ///////////////////////////////////////////////////////////////////////////////////////////////////// + // CCLabelTextFormat protocol implementation + virtual Sprite * getSpriteChild(int ID); + virtual Array * getChildrenLetters(); + virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint); + virtual float getLetterPosXLeft( Sprite* sp ); + virtual float getLetterPosXRight( Sprite* sp ); + + + // font related stuff + virtual int getCommonLineHeight(); + virtual int getKerningForCharsPair(unsigned short first, unsigned short second); + virtual int getXOffsetForChar(unsigned short c); + virtual int getYOffsetForChar(unsigned short c); + virtual int getAdvanceForChar(unsigned short c, int hintPositionInString); + virtual Rect getRectForChar(unsigned short c) ; + + // string related stuff + virtual int getStringNumLines(); + virtual int getStringLenght(); + virtual unsigned short getCharAtStringPosition(int position); + virtual unsigned short * getUTF8String(); + virtual void assignNewUTF8String(unsigned short *newString); + virtual TextHAlignment getTextAlignment(); + + // label related stuff + virtual float getMaxLineWidth() ; + virtual bool breakLineWithoutSpace(); + virtual Size getLabelContentSize(); + virtual void setLabelContentSize(const Size &newSize); + + // carloX + const char * getString() const { return "not implemented"; } private: + Label(FontAtlas *pAtlas, TextHAlignment alignment); + ~Label(); + + static Label* createWithAtlas(FontAtlas *pAtlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0); + + bool init(); + + void alignText(); + void hideAllLetters(); + void moveAllSpritesToCache(); + + bool computeAdvancesForString(unsigned short int *stringToRender); + bool setCurrentString(unsigned short *stringToSet); + bool setOriginalString(unsigned short *stringToSet); + void resetCurrentString(); + + Sprite * getSprite(); + Sprite * createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture); + Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture); + Sprite * getSpriteForLetter(unsigned short int newLetter); + Sprite * updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter); + + Array _spriteArray; + Array _spriteArrayCache; + float _commonLineHeight; + bool _lineBreakWithoutSpaces; + float _width; + TextHAlignment _alignment; + unsigned short int * _currentUTF8String; + unsigned short int * _originalUTF8String; + Size * _advances; + FontAtlas * _fontAtlas; + Color3B _displayedColor; + Color3B _realColor; + bool _cascadeColorEnabled; + bool _cascadeOpacityEnabled; + unsigned char _displayedOpacity; + unsigned char _realOpacity; + bool _isOpacityModifyRGB; + }; + NS_CC_END #endif /*__COCOS2D_CCLABEL_H */ diff --git a/cocos2dx/label_nodes/CCLabelTextFormatProtocol.h b/cocos2dx/label_nodes/CCLabelTextFormatProtocol.h index ba43e167ef..f553a4c167 100644 --- a/cocos2dx/label_nodes/CCLabelTextFormatProtocol.h +++ b/cocos2dx/label_nodes/CCLabelTextFormatProtocol.h @@ -32,33 +32,33 @@ class CC_DLL LabelTextFormatProtocol public: // sprite related stuff - virtual cocos2d::Sprite * getSpriteChild(int ID) = 0; - virtual cocos2d::Array * getChildrenLetters() = 0; - virtual cocos2d::Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint) = 0; - virtual float getLetterPosXLeft( cocos2d::Sprite* sp ) = 0; - virtual float getLetterPosXRight( cocos2d::Sprite* sp ) = 0; + virtual cocos2d::Sprite *getSpriteChild(int ID) = 0; + virtual cocos2d::Array *getChildrenLetters() = 0; + virtual cocos2d::Sprite *getSpriteForChar(unsigned short int theChar, int spriteIndexHint) = 0; + virtual float getLetterPosXLeft( cocos2d::Sprite* sp ) = 0; + virtual float getLetterPosXRight( cocos2d::Sprite* sp ) = 0; // font related stuff - virtual int getCommonLineHeight() = 0; - virtual int getKerningForCharsPair(unsigned short first, unsigned short second) = 0; - virtual int getXOffsetForChar(unsigned short c) = 0; - virtual int getYOffsetForChar(unsigned short c) = 0; - virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) = 0; - virtual cocos2d::Rect getRectForChar(unsigned short c) = 0; + virtual int getCommonLineHeight() = 0; + virtual int getKerningForCharsPair(unsigned short first, unsigned short second) = 0; + virtual int getXOffsetForChar(unsigned short c) = 0; + virtual int getYOffsetForChar(unsigned short c) = 0; + virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) = 0; + virtual cocos2d::Rect getRectForChar(unsigned short c) = 0; // string related stuff - virtual int getStringNumLines() = 0; - virtual int getStringLenght() = 0; - virtual unsigned short getCharAtStringPosition(int position) = 0; - virtual unsigned short * getUTF8String() = 0; - virtual void assignNewUTF8String(unsigned short *newString) = 0; - virtual TextHAlignment getTextAlignment() = 0; + virtual int getStringNumLines() = 0; + virtual int getStringLenght() = 0; + virtual unsigned short getCharAtStringPosition(int position) = 0; + virtual unsigned short * getUTF8String() = 0; + virtual void assignNewUTF8String(unsigned short *newString) = 0; + virtual TextHAlignment getTextAlignment() = 0; // label related stuff - virtual float getMaxLineWidth() = 0; - virtual bool breakLineWithoutSpace() = 0; - virtual cocos2d::Size getLabelContentSize() = 0; - virtual void setLabelContentSize(const Size &newSize) = 0; + virtual float getMaxLineWidth() = 0; + virtual bool breakLineWithoutSpace() = 0; + virtual cocos2d::Size getLabelContentSize() = 0; + virtual void setLabelContentSize(const Size &newSize) = 0; }; diff --git a/cocos2dx/label_nodes/CCLabelTextFormatter.cpp b/cocos2dx/label_nodes/CCLabelTextFormatter.cpp index 2e739832d1..48e58f02d8 100644 --- a/cocos2dx/label_nodes/CCLabelTextFormatter.cpp +++ b/cocos2dx/label_nodes/CCLabelTextFormatter.cpp @@ -224,7 +224,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) vector last_line; for (int ctr = 0; ctr <= str_len; ++ctr) { - unsigned char currentChar = theLabel->getCharAtStringPosition(ctr); + unsigned short int currentChar = theLabel->getCharAtStringPosition(ctr); if (currentChar == '\n' || currentChar == 0) { @@ -301,7 +301,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) unsigned short prev = -1; - Size tmpSize = Size::ZERO; + Size tmpSize = Size::ZERO; int longestLine = 0; unsigned int totalHeight = 0; diff --git a/cocos2dx/label_nodes/CCStringBMFont.cpp b/cocos2dx/label_nodes/CCStringBMFont.cpp deleted file mode 100644 index 3b549a3b57..0000000000 --- a/cocos2dx/label_nodes/CCStringBMFont.cpp +++ /dev/null @@ -1,733 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2011 Zynga Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Use any of these editors to generate BMFonts: -http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) -http://www.n4te.com/hiero/hiero.jnlp (Free, Java) -http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) -http://www.angelcode.com/products/bmfont/ (Free, Windows only) - -****************************************************************************/ -#include "CCStringBMFont.h" -#include "cocoa/CCString.h" -#include "cocoa/CCDictionary.h" -#include "CCConfiguration.h" -#include "CCLabelTextFormatter.h" -#include "draw_nodes/CCDrawingPrimitives.h" -#include "sprite_nodes/CCSprite.h" -//#include "support/CCPointExtension.h" -#include "platform/CCFileUtils.h" -#include "CCDirector.h" -#include "textures/CCTextureCache.h" -#include "support/ccUTF8.h" - -using namespace std; - -NS_CC_BEGIN - - -// The return value needs to be deleted by CC_SAFE_DELETE_ARRAY. -static unsigned short* copyUTF16StringNN(unsigned short* str) -{ - int length = str ? cc_wcslen(str) : 0; - unsigned short* ret = new unsigned short[length+1]; - for (int i = 0; i < length; ++i) { - ret[i] = str[i]; - } - ret[length] = 0; - return ret; -} - -// -//CCLabelBMFont -// - -//LabelBMFont - Purge Cache -void StringBMFont::purgeCachedData() -{ - FNTConfigRemoveCache(); -} - -StringBMFont * StringBMFont::create() -{ - StringBMFont * pRet = new StringBMFont(); - if (pRet && pRet->init()) - { - pRet->autorelease(); - return pRet; - } - CC_SAFE_DELETE(pRet); - return NULL; -} - -StringBMFont * StringBMFont::create(const char *str, const char *fntFile, float width, TextHAlignment alignment) -{ - return StringBMFont::create(str, fntFile, width, alignment, Point::ZERO); -} - -StringBMFont * StringBMFont::create(const char *str, const char *fntFile, float width) -{ - return StringBMFont::create(str, fntFile, width, TextHAlignment::LEFT, Point::ZERO); -} - -StringBMFont * StringBMFont::create(const char *str, const char *fntFile) -{ - return StringBMFont::create(str, fntFile, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); -} - -//LabelBMFont - Creation & Init -StringBMFont *StringBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = kTextAlignmentLeft*/, Point imageOffset/* = Point::ZERO*/) -{ - StringBMFont *pRet = new StringBMFont(); - if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset)) - { - pRet->autorelease(); - return pRet; - } - CC_SAFE_DELETE(pRet); - return NULL; -} - -bool StringBMFont::init() -{ - return initWithString(NULL, NULL, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO); -} - -bool StringBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = kTextAlignmentLeft*/, Point imageOffset/* = Point::ZERO*/) -{ - CCAssert(!_configuration, "re-init is no longer supported"); - CCAssert( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for StringBMFont"); - - Texture2D *texture = NULL; - - if (fntFile) - { - CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile); - if (!newConf) - { - CCLOG("cocos2d: WARNING. StringBMFont: Impossible to create font. Please check file: '%s'", fntFile); - release(); - return false; - } - - newConf->retain(); - CC_SAFE_RELEASE(_configuration); - _configuration = newConf; - - _fntFile = fntFile; - - texture = TextureCache::getInstance()->addImage(_configuration->getAtlasName()); - } - else - { - texture = new Texture2D(); - texture->autorelease(); - } - - if (theString == NULL) - { - theString = ""; - } - - if (SpriteBatchNode::initWithTexture(texture, strlen(theString))) - { - _width = width; - _alignment = alignment; - - _displayedOpacity = _realOpacity = 255; - _displayedColor = _realColor = Color3B::WHITE; - _cascadeOpacityEnabled = true; - _cascadeColorEnabled = true; - - _contentSize = Size::ZERO; - - _isOpacityModifyRGB = _textureAtlas->getTexture()->hasPremultipliedAlpha(); - _anchorPoint = Point(0.5f, 0.5f); - - _imageOffset = imageOffset; - - _reusedChar = new Sprite(); - _reusedChar->initWithTexture(_textureAtlas->getTexture(), Rect(0, 0, 0, 0), false); - _reusedChar->setBatchNode(this); - - this->setString(theString); - - return true; - } - return false; -} - -StringBMFont::StringBMFont() -: _string(NULL) -, _initialString(NULL) -, _alignment(TextHAlignment::CENTER) -, _width(-1.0f) -, _configuration(NULL) -, _lineBreakWithoutSpaces(false) -, _imageOffset(Point::ZERO) -, _reusedChar(NULL) -, _displayedOpacity(255) -, _realOpacity(255) -, _displayedColor(Color3B::WHITE) -, _realColor(Color3B::WHITE) -, _cascadeColorEnabled(true) -, _cascadeOpacityEnabled(true) -, _isOpacityModifyRGB(false) -{ - -} - -StringBMFont::~StringBMFont() -{ - CC_SAFE_RELEASE(_reusedChar); - CC_SAFE_DELETE_ARRAY(_string); - CC_SAFE_DELETE_ARRAY(_initialString); - CC_SAFE_RELEASE(_configuration); -} - -// StringBMFont - Atlas generation -int StringBMFont::kerningAmountForFirst(unsigned short first, unsigned short second) -{ - int ret = 0; - unsigned int key = (first<<16) | (second & 0xffff); - - if( _configuration->_kerningDictionary ) { - tKerningHashElement *element = NULL; - HASH_FIND_INT(_configuration->_kerningDictionary, &key, element); - if(element) - ret = element->amount; - } - return ret; -} - -const char* StringBMFont::getString(void) const -{ - return _initialStringUTF8.c_str(); -} - -//StringBMFont - RGBAProtocol protocol -const Color3B& StringBMFont::getColor() const -{ - return _realColor; -} - -const Color3B& StringBMFont::getDisplayedColor() const -{ - return _displayedColor; -} - -void StringBMFont::setColor(const Color3B& color) -{ - _displayedColor = _realColor = color; - - if( _cascadeColorEnabled ) { - Color3B parentColor = Color3B::WHITE; - RGBAProtocol* pParent = dynamic_cast(_parent); - if (pParent && pParent->isCascadeColorEnabled()) - { - parentColor = pParent->getDisplayedColor(); - } - this->updateDisplayedColor(parentColor); - } -} - -GLubyte StringBMFont::getOpacity(void) const -{ - return _realOpacity; -} - -GLubyte StringBMFont::getDisplayedOpacity(void) const -{ - return _displayedOpacity; -} - -/** Override synthesized setOpacity to recurse items */ -void StringBMFont::setOpacity(GLubyte opacity) -{ - _displayedOpacity = _realOpacity = opacity; - - if( _cascadeOpacityEnabled ) { - GLubyte parentOpacity = 255; - RGBAProtocol* pParent = dynamic_cast(_parent); - if (pParent && pParent->isCascadeOpacityEnabled()) - { - parentOpacity = pParent->getDisplayedOpacity(); - } - this->updateDisplayedOpacity(parentOpacity); - } -} - -void StringBMFont::setOpacityModifyRGB(bool var) -{ - _isOpacityModifyRGB = var; - if (_children && _children->count() != 0) - { - Object* child; - CCARRAY_FOREACH(_children, child) - { - Node* pNode = static_cast( child ); - if (pNode) - { - RGBAProtocol *pRGBAProtocol = dynamic_cast(pNode); - if (pRGBAProtocol) - { - pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB); - } - } - } - } -} -bool StringBMFont::isOpacityModifyRGB() const -{ - return _isOpacityModifyRGB; -} - -void StringBMFont::updateDisplayedOpacity(GLubyte parentOpacity) -{ - _displayedOpacity = _realOpacity * parentOpacity/255.0; - - Object* pObj; - CCARRAY_FOREACH(_children, pObj) - { - Sprite *item = static_cast( pObj ); - item->updateDisplayedOpacity(_displayedOpacity); - } -} - -void StringBMFont::updateDisplayedColor(const Color3B& parentColor) -{ - _displayedColor.r = _realColor.r * parentColor.r/255.0; - _displayedColor.g = _realColor.g * parentColor.g/255.0; - _displayedColor.b = _realColor.b * parentColor.b/255.0; - - Object* pObj; - CCARRAY_FOREACH(_children, pObj) - { - Sprite *item = static_cast( pObj ); - item->updateDisplayedColor(_displayedColor); - } -} - -bool StringBMFont::isCascadeColorEnabled() const -{ - return false; -} - -void StringBMFont::setCascadeColorEnabled(bool cascadeColorEnabled) -{ - _cascadeColorEnabled = cascadeColorEnabled; -} - -bool StringBMFont::isCascadeOpacityEnabled() const -{ - return false; -} - -void StringBMFont::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) -{ - _cascadeOpacityEnabled = cascadeOpacityEnabled; -} - -// StringBMFont - AnchorPoint -void StringBMFont::setAnchorPoint(const Point& point) -{ - if( ! point.equals(_anchorPoint)) - { - SpriteBatchNode::setAnchorPoint(point); - updateLabel(); - } -} - -// StringBMFont - Alignment -void StringBMFont::setAlignment(TextHAlignment alignment) -{ - this->_alignment = alignment; - updateLabel(); -} - -void StringBMFont::setWidth(float width) -{ - this->_width = width; - updateLabel(); -} - -void StringBMFont::setLineBreakWithoutSpace( bool breakWithoutSpace ) -{ - _lineBreakWithoutSpaces = breakWithoutSpace; - updateLabel(); -} - -void StringBMFont::setScale(float scale) -{ - SpriteBatchNode::setScale(scale); - updateLabel(); -} - -void StringBMFont::setScaleX(float scaleX) -{ - SpriteBatchNode::setScaleX(scaleX); - updateLabel(); -} - -void StringBMFont::setScaleY(float scaleY) -{ - SpriteBatchNode::setScaleY(scaleY); - updateLabel(); -} - -float StringBMFont::getLetterPosXLeft( Sprite* sp ) -{ - return sp->getPosition().x * _scaleX - (sp->getContentSize().width * _scaleX * sp->getAnchorPoint().x); -} - -float StringBMFont::getLetterPosXRight( Sprite* sp ) -{ - return sp->getPosition().x * _scaleX + (sp->getContentSize().width * _scaleX * sp->getAnchorPoint().x); -} - -// StringBMFont - FntFile -void StringBMFont::setFntFile(const char* fntFile) -{ - if (fntFile != NULL && strcmp(fntFile, _fntFile.c_str()) != 0 ) - { - CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile); - - CCAssert( newConf, "CCStringBMFont: Impossible to create font. Please check file"); - - _fntFile = fntFile; - - CC_SAFE_RETAIN(newConf); - CC_SAFE_RELEASE(_configuration); - _configuration = newConf; - - this->setTexture(TextureCache::getInstance()->addImage(_configuration->getAtlasName())); - LabelTextFormatter::createStringSprites(this); - } -} - -const char* StringBMFont::getFntFile() -{ - return _fntFile.c_str(); -} - - -//StringBMFont - Debug draw -#if CC_LabelBMFontNew_DEBUG_DRAW -void StringBMFont::draw() -{ - SpriteBatchNode::draw(); - const Size& s = this->getContentSize(); - Point vertices[4]={ - ccp(0,0),ccp(s.width,0), - ccp(s.width,s.height),ccp(0,s.height), - }; - ccDrawPoly(vertices, 4, true); -} - -#endif // CC_LABELBMFONT_DEBUG_DRAW - - -int StringBMFont::getCommonLineHeight() -{ - if (_configuration) - { - return _configuration->_commonHeight; - } - else - { - return -1; - } -} - -int StringBMFont::getKerningForCharsPair(unsigned short first, unsigned short second) -{ - return this->kerningAmountForFirst(first, second); -} - -ccBMFontDef StringBMFont::getFontDefForChar(unsigned short int theChar) -{ - ccBMFontDef fontDef; - tFontDefHashElement *element = NULL; - unsigned int key = theChar; - - HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element); - - if (element) - { - fontDef = element->fontDef; - } - - return fontDef; -} - -// return a sprite for rendering one letter -Sprite * StringBMFont::getSpriteForChar(unsigned short int theChar, int spriteIndexHint) -{ - Rect rect; - ccBMFontDef fontDef; - Sprite *pRetSprite = 0; - - // unichar is a short, and an int is needed on HASH_FIND_INT - tFontDefHashElement *element = NULL; - unsigned int key = theChar; - - HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element); - - if (! element) - { - return 0; - } - - fontDef = element->fontDef; - - rect = fontDef.rect; - rect = CC_RECT_PIXELS_TO_POINTS(rect); - - rect.origin.x += _imageOffset.x; - rect.origin.y += _imageOffset.y; - - //bool hasSprite = true; - pRetSprite = (Sprite*)(this->getChildByTag(spriteIndexHint)); - - if(pRetSprite ) - { - // Reusing previous Sprite - pRetSprite->setVisible(true); - } - else - { - pRetSprite = new Sprite(); - pRetSprite->initWithTexture(_textureAtlas->getTexture(), rect); - addChild(pRetSprite, spriteIndexHint, spriteIndexHint); - pRetSprite->release(); - - // Apply label properties - pRetSprite->setOpacityModifyRGB(_isOpacityModifyRGB); - - // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on - pRetSprite->updateDisplayedColor(_displayedColor); - pRetSprite->updateDisplayedOpacity(_displayedOpacity); - } - - // updating previous sprite - pRetSprite->setTextureRect(rect, false, rect.size); - return pRetSprite; -} - -int StringBMFont::getStringNumLines() -{ - int quantityOfLines = 1; - - unsigned int stringLen = _string ? cc_wcslen(_string) : 0; - if (stringLen == 0) - return (-1); - - // count number of lines - for (unsigned int i = 0; i < stringLen - 1; ++i) - { - unsigned short c = _string[i]; - if (c == '\n') - { - quantityOfLines++; - } - } - - return quantityOfLines; -} - -// need cross implementation -int StringBMFont::getStringLenght() -{ - return _string ? cc_wcslen(_string) : 0; -} - -unsigned short StringBMFont::getCharAtStringPosition(int position) -{ - return _string[position]; -} - -int StringBMFont::getXOffsetForChar(unsigned short c) -{ - ccBMFontDef fontDef = getFontDefForChar(c); - return fontDef.xOffset; -} - -int StringBMFont::getYOffsetForChar(unsigned short c) -{ - ccBMFontDef fontDef = getFontDefForChar(c); - return fontDef.yOffset; -} - -Rect StringBMFont::getRectForChar(unsigned short c) -{ - ccBMFontDef fontDef = getFontDefForChar(c); - return fontDef.rect; -} - -int StringBMFont::getAdvanceForChar(unsigned short c, int hintPositionInString) -{ - ccBMFontDef fontDef = getFontDefForChar(c); - return fontDef.xAdvance; -} - -void StringBMFont::setLabelContentSize(const Size &newSize) -{ - setContentSize(newSize); -} - -void StringBMFont::createStringSprites() -{ - LabelTextFormatter::createStringSprites(this); -} - -void StringBMFont::setString(const char *newString) -{ - // store initial string in char8 format - _initialStringUTF8 = newString; - - // update the initial string if needed - unsigned short* utf16String = cc_utf8_to_utf16(newString); - unsigned short* tmp = _initialString; - _initialString = copyUTF16StringNN(utf16String); - - CC_SAFE_DELETE_ARRAY(tmp); - CC_SAFE_DELETE_ARRAY(utf16String); - - // do the rest of the josb - updateLabel(); -} - -void StringBMFont::setCString(const char *label) -{ - setString(label); -} - -void StringBMFont::updateLabel() -{ - if ( _initialString!=0 ) - { - // set the new string - CC_SAFE_DELETE_ARRAY(_string); - _string = copyUTF16StringNN(_initialString); - - // hide all the letters and create or recicle sprites for the new letters - updateLetterSprites(); - - // format the text on more than line - multilineText(); - - // align the text (left - center - right) - alignText(); - } -} - -void StringBMFont::updateLetterSprites() -{ - // hide all the letters - hideStringSprites(); - - // create new letters sprites - createStringSprites(); -} - -void StringBMFont::hideStringSprites() -{ - if (_children && _children->count() != 0) - { - Object* child; - CCARRAY_FOREACH(_children, child) - { - Node* pNode = (Node*) child; - if (pNode) - { - pNode->setVisible(false); - } - } - } -} - -void StringBMFont::multilineText() -{ - if (_width > 0) - { - // format on more than one line - LabelTextFormatter::multilineText(this); - - // hide all the letter sprites and create/reclaim letters sprite with new position - updateLetterSprites(); - } -} - -void StringBMFont::alignText() -{ - if (_alignment != TextHAlignment::LEFT) - { - LabelTextFormatter::alignText(this); - } -} - -unsigned short * StringBMFont::getUTF8String() -{ - return _string; -} - -Sprite * StringBMFont::getSpriteChild(int ID) -{ - return (Sprite*)this->getChildByTag(ID); -} - -float StringBMFont::getMaxLineWidth() -{ - return _width; -} - -TextHAlignment StringBMFont::getTextAlignment() -{ - return _alignment; -} - -Array* StringBMFont::getChildrenLetters() -{ - return _children; -} - -void StringBMFont::assignNewUTF8String(unsigned short *newString) -{ - CC_SAFE_DELETE_ARRAY(_string); - _string = newString; -} - -Size StringBMFont::getLabelContentSize() -{ - return getContentSize(); -} - -bool StringBMFont::breakLineWithoutSpace() -{ - return _lineBreakWithoutSpaces; -} - - -NS_CC_END diff --git a/cocos2dx/label_nodes/CCStringBMFont.h b/cocos2dx/label_nodes/CCStringBMFont.h deleted file mode 100644 index cf9c6d0988..0000000000 --- a/cocos2dx/label_nodes/CCStringBMFont.h +++ /dev/null @@ -1,204 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2011 Zynga Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Use any of these editors to generate BMFonts: - http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) - http://www.n4te.com/hiero/hiero.jnlp (Free, Java) - http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) - http://www.angelcode.com/products/bmfont/ (Free, Windows only) - -****************************************************************************/ -#ifndef __CCBITMAP_FONT_ATLAS_H__NEW_ -#define __CCBITMAP_FONT_ATLAS_H__NEW_ - -#include "sprite_nodes/CCSpriteBatchNode.h" -#include "support/data_support/uthash.h" -#include "CCLabelBMFont.h" -#include "CCLabelTextFormatProtocol.h" -#include -#include -#include -#include -#include "CCLabel.h" - -NS_CC_BEGIN - -class CC_DLL StringBMFont: public Label, public LabelTextFormatProtocol -{ -public: - StringBMFont(); - - virtual ~StringBMFont(); - /** Purges the cached data. - Removes from memory the cached configurations and the atlas name dictionary. - @since v0.99.3 - */ - static void purgeCachedData(); - - /** creates a bitmap font atlas with an initial string and the FNT file */ - static StringBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment, Point imageOffset); - - static StringBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment); - - static StringBMFont * create(const char *str, const char *fntFile, float width); - - static StringBMFont * create(const char *str, const char *fntFile); - - /** Creates an label. - */ - static StringBMFont * create(); - - bool init(); - /** init a bitmap font atlas with an initial string and the FNT file */ - bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO); - - /** updates the font chars based on the string to render */ - // super method - virtual void setString(const char *newString); - - virtual const char* getString(void) const; - virtual void setCString(const char *label); - virtual void setAnchorPoint(const Point& var); - virtual void updateLabel(); - virtual void setAlignment(TextHAlignment alignment); - virtual void setWidth(float width); - virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); - virtual void setScale(float scale); - virtual void setScaleX(float scaleX); - virtual void setScaleY(float scaleY); - - // RGBAProtocol - virtual bool isOpacityModifyRGB() const; - virtual void setOpacityModifyRGB(bool isOpacityModifyRGB); - virtual GLubyte getOpacity() const; - virtual GLubyte getDisplayedOpacity() const; - virtual void setOpacity(GLubyte opacity); - virtual void updateDisplayedOpacity(GLubyte parentOpacity); - virtual bool isCascadeOpacityEnabled() const; - virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled); - virtual const Color3B& getColor(void) const; - virtual const Color3B& getDisplayedColor() const; - virtual void setColor(const Color3B& color); - virtual void updateDisplayedColor(const Color3B& parentColor); - virtual bool isCascadeColorEnabled() const; - virtual void setCascadeColorEnabled(bool cascadeColorEnabled); - - - // StringBMFont protocol stuff - virtual Sprite * getSpriteChild(int ID); - virtual Array * getChildrenLetters(); - virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint); - virtual int getCommonLineHeight(); - virtual int getKerningForCharsPair(unsigned short first, unsigned short second); - virtual int getXOffsetForChar(unsigned short c); - virtual int getYOffsetForChar(unsigned short c); - virtual int getAdvanceForChar(unsigned short c, int hintPositionInString); - virtual Rect getRectForChar(unsigned short c); - float getLetterPosXLeft( Sprite* sp ); - float getLetterPosXRight( Sprite* sp ); - virtual int getStringNumLines(); - virtual int getStringLenght(); - virtual unsigned short getCharAtStringPosition(int position); - virtual unsigned short * getUTF8String(); - virtual void assignNewUTF8String(unsigned short *newString); - virtual float getMaxLineWidth(); - virtual bool breakLineWithoutSpace(); - virtual TextHAlignment getTextAlignment(); - virtual Size getLabelContentSize(); - virtual void setLabelContentSize(const Size &newSize); - - - void setFntFile(const char* fntFile); - const char* getFntFile(); - -#if CC_LABELBMFONT_DEBUG_DRAW - virtual void draw(); -#endif // CC_LABELBMFONT_DEBUG_DRAW - -private: - char * atlasNameFromFntFile(const char *fntFile); - int kerningAmountForFirst(unsigned short first, unsigned short second); - - // some more new stuff - void alignText(); - void multilineText(); - ccBMFontDef getFontDefForChar(unsigned short int theChar); - void createStringSprites(); - void hideStringSprites(); - void updateLetterSprites(); - - -protected: - - // string to render - unsigned short* _string; - - // name of fntFile - std::string _fntFile; - - // initial string without line breaks - unsigned short* _initialString; - std::string _initialStringUTF8; - - // alignment of all lines - TextHAlignment _alignment; - // max width until a line break is added - float _width; - - CCBMFontConfiguration *_configuration; - - bool _lineBreakWithoutSpaces; - // offset of the texture atlas - Point _imageOffset; - - // reused char - Sprite *_reusedChar; - - // texture RGBA - GLubyte _displayedOpacity; - GLubyte _realOpacity; - Color3B _displayedColor; - Color3B _realColor; - bool _cascadeColorEnabled; - bool _cascadeOpacityEnabled; - /** conforms to RGBAProtocol protocol */ - bool _isOpacityModifyRGB; - -}; - -/** Free function that parses a FNT file a place it on the cache -*/ -CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file ); -/** Purges the FNT config cache -*/ -CC_DLL void FNTConfigRemoveCache( void ); - -// end of GUI group -/// @} -/// @} - -NS_CC_END - -#endif //__CCBITMAP_FONT_ATLAS_H__ diff --git a/cocos2dx/label_nodes/CCStringTTF.cpp b/cocos2dx/label_nodes/CCStringTTF.cpp deleted file mode 100644 index 54454da87d..0000000000 --- a/cocos2dx/label_nodes/CCStringTTF.cpp +++ /dev/null @@ -1,671 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "cocos2d.h" -#include "CCStringTTF.h" -#include "CCFont.h" -#include "CCLabelTextFormatter.h" -#include "CCFontAtlasCache.h" - -NS_CC_BEGIN - -StringTTF::StringTTF(FontAtlas *pAtlas, TextHAlignment alignment): _currentUTF8String(0), - _originalUTF8String(0), - _fontAtlas(pAtlas), - _alignment(alignment), - _lineBreakWithoutSpaces(false), - _advances(0), - _displayedColor(Color3B::WHITE), - _realColor(Color3B::WHITE), - _cascadeColorEnabled(true) -{ -} - -StringTTF* StringTTF::create(FontAtlas *pAtlas, TextHAlignment alignment, int lineSize) -{ - StringTTF *ret = new StringTTF(pAtlas, alignment); - - if (!ret) - return nullptr; - - if( ret->init() ) - { - ret->autorelease(); - return ret; - } - else - { - delete ret; - return nullptr; - } - - return ret; -} - -StringTTF::~StringTTF() -{ - if (_currentUTF8String) - { - delete [] _currentUTF8String; - _currentUTF8String = 0; - } - - if (_advances) - { - delete [] _advances; - _advances = 0; - } - - if (_fontAtlas) - { - FontAtlasCache::releaseFontAtlas(_fontAtlas); - } -} - -bool StringTTF::init() -{ - return true; -} - -void StringTTF::setString(const char *stringToRender) -{ - setText(stringToRender, 0, TextHAlignment::CENTER, false); -} - -bool StringTTF::setText(const char *stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) -{ - if (!_fontAtlas) - return false; - - _width = lineWidth; - _alignment = alignment; - _lineBreakWithoutSpaces = lineBreakWithoutSpaces; - - // release all the sprites - moveAllSpritesToCache(); - - // store locally common line height - _commonLineHeight = _fontAtlas->getCommonLineHeight(); - if (_commonLineHeight <= 0) - return false; - - int numLetter = 0; - unsigned short* utf16String = cc_utf8_to_utf16(stringToRender); - if(!utf16String) - return false; - - numLetter = cc_wcslen(utf16String); - SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), numLetter); - _cascadeColorEnabled = true; - - // - setCurrentString(utf16String); - setOriginalString(utf16String); - - // align text - alignText(); - - // done here - return true; -} - -void StringTTF::setAlignment(TextHAlignment alignment) -{ - // store the new alignment - if (alignment != _alignment) - { - // store - _alignment = alignment; - - // reset the string - resetCurrentString(); - - // need to align text again - alignText(); - } -} - -void StringTTF::setWidth(float width) -{ - if (width != _width) - { - // store - _width = width; - - // need to align text again - alignText(); - } -} - -void StringTTF::setLineBreakWithoutSpace(bool breakWithoutSpace) -{ - if (breakWithoutSpace != _lineBreakWithoutSpaces) - { - // store - _lineBreakWithoutSpaces = breakWithoutSpace; - - // need to align text again - alignText(); - } -} - -void StringTTF::setScale(float scale) -{ - Node::setScale(scale); - alignText(); -} - -void StringTTF::setScaleX(float scaleX) -{ - Node::setScaleX(scaleX); - alignText(); -} - -void StringTTF::setScaleY(float scaleY) -{ - Node::setScaleY(scaleY); - alignText(); -} - -void StringTTF::alignText() -{ - hideAllLetters(); - LabelTextFormatter::createStringSprites(this); - - if( LabelTextFormatter::multilineText(this) ) - { - hideAllLetters(); - LabelTextFormatter::createStringSprites(this); - } - - LabelTextFormatter::alignText(this); -} - -void StringTTF::hideAllLetters() -{ - Object* Obj = NULL; - CCARRAY_FOREACH(&_spriteArray, Obj) - { - ((Sprite *)Obj)->setVisible(false); - } - - CCARRAY_FOREACH(&_spriteArrayCache, Obj) - { - ((Sprite *)Obj)->setVisible(false); - } -} - -bool StringTTF::computeAdvancesForString(unsigned short int *stringToRender) -{ - if (_advances) - { - delete [] _advances; - _advances = 0; - } - - Font &theFont = _fontAtlas->getFont(); - - int letterCount = 0; - _advances = theFont.getAdvancesForTextUTF16(stringToRender, letterCount); - - if(!_advances) - return false; - else - return true; -} - -bool StringTTF::setOriginalString(unsigned short *stringToSet) -{ - if (_originalUTF8String) - { - delete [] _originalUTF8String; - _originalUTF8String = 0; - } - - int newStringLenght = cc_wcslen(stringToSet); - _originalUTF8String = new unsigned short int [newStringLenght + 1]; - memset(_originalUTF8String, 0, (newStringLenght + 1) * 2); - memcpy(_originalUTF8String, stringToSet, (newStringLenght * 2)); - _originalUTF8String[newStringLenght] = 0; - - return true; -} - -bool StringTTF::setCurrentString(unsigned short *stringToSet) -{ - // set the new string - if (_currentUTF8String) - { - delete [] _currentUTF8String; - _currentUTF8String = 0; - } - // - _currentUTF8String = stringToSet; - // compute the advances - return computeAdvancesForString(stringToSet); -} - -void StringTTF::resetCurrentString() -{ - // set the new string - if (_currentUTF8String) - { - delete [] _currentUTF8String; - _currentUTF8String = 0; - } - - int stringLenght = cc_wcslen(_originalUTF8String); - _currentUTF8String = new unsigned short int [stringLenght + 1]; - memcpy(_currentUTF8String, _originalUTF8String, stringLenght * 2); - _currentUTF8String[stringLenght] = 0; - -} - -Sprite * StringTTF::createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture) -{ - Rect uvRect; - uvRect.size.height = theDefinition.height; - uvRect.size.width = theDefinition.width; - uvRect.origin.x = theDefinition.U; - uvRect.origin.y = theDefinition.V; - - SpriteFrame *pFrame = SpriteFrame::createWithTexture(theTexture, uvRect); - Sprite *tempSprite = getSprite(); - - if (!tempSprite) - return nullptr; - - tempSprite->initWithSpriteFrame(pFrame); - tempSprite->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); - tempSprite->setBatchNode(this); - - return tempSprite; -} - -Sprite * StringTTF::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture) -{ - if (!spriteToUpdate) - { - return nullptr; - } - else - { - Rect uvRect; - uvRect.size.height = theDefinition.height; - uvRect.size.width = theDefinition.width; - uvRect.origin.x = theDefinition.U; - uvRect.origin.y = theDefinition.V; - - SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect); - if (frame) - { - spriteToUpdate->setTexture(theTexture); - spriteToUpdate->setDisplayFrame(frame); - spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); - spriteToUpdate->setBatchNode(this); - } - - return spriteToUpdate; - } -} - -Sprite * StringTTF::getSpriteForLetter(unsigned short int newLetter) -{ - if (!_fontAtlas) - return nullptr; - - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition); - if (validDefinition) - { - Sprite *newSprite = createNewSpriteFromLetterDefinition(tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) ); - this->addChild(newSprite); - return newSprite; - } - else - { - return nullptr; - } -} - -Sprite * StringTTF::updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter) -{ - if (!spriteToUpdate || !_fontAtlas) - return nullptr; - - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition); - if (validDefinition) - { - Sprite *pNewSprite = updateSpriteWithLetterDefinition(spriteToUpdate, tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) ); - return pNewSprite; - } - else - { - return nullptr; - } - -} - -void StringTTF::moveAllSpritesToCache() -{ - Object* pObj = NULL; - CCARRAY_FOREACH(&_spriteArray, pObj) - { - ((Sprite *)pObj)->removeFromParent(); - _spriteArrayCache.addObject(pObj); - } - - _spriteArray.removeAllObjects(); -} - -Sprite * StringTTF::getSprite() -{ - if (_spriteArrayCache.count()) - { - Sprite *retSprite = (Sprite *) _spriteArrayCache.lastObject(); - _spriteArrayCache.removeLastObject(); - return retSprite; - } - else - { - Sprite *retSprite = new Sprite; - return retSprite; - } -} - -///// PROTOCOL STUFF - -Sprite * StringTTF::getSpriteChild(int ID) -{ - Object* pObj = NULL; - CCARRAY_FOREACH(&_spriteArray, pObj) - { - Sprite *pSprite = (Sprite *)pObj; - if ( pSprite->getTag() == ID) - { - return pSprite; - } - } - return nullptr; -} - -Array * StringTTF::getChildrenLetters() -{ - return &_spriteArray; -} - -Sprite * StringTTF::getSpriteForChar(unsigned short int theChar, int spriteIndexHint) -{ - // ret sprite - Sprite *retSprite = 0; - - // look for already existing sprites - retSprite = getSpriteChild(spriteIndexHint); - - if (!retSprite) - { - retSprite = getSpriteForLetter(theChar); - if (!retSprite) - return nullptr; - - if (retSprite) - retSprite->setTag(spriteIndexHint); - - _spriteArray.addObject(retSprite); - } - - // the sprite is now visible - retSprite->setVisible(true); - - // set the right texture letter to the sprite - updateSpriteForLetter(retSprite, theChar); - - // we are done here - return retSprite; -} - -float StringTTF::getLetterPosXLeft( Sprite* sp ) -{ - float scaleX = _scaleX; - return sp->getPosition().x * scaleX - (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x); -} - -float StringTTF::getLetterPosXRight( Sprite* sp ) -{ - float scaleX = _scaleX; - return sp->getPosition().x * scaleX + (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x); -} - -int StringTTF::getCommonLineHeight() -{ - return _commonLineHeight; -} - -int StringTTF::getKerningForCharsPair(unsigned short first, unsigned short second) -{ - return 0; -} - -int StringTTF::getXOffsetForChar(unsigned short c) -{ - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); - if (!validDefinition) - return -1; - - return (tempDefinition.offsetX); -} - -int StringTTF::getYOffsetForChar(unsigned short c) -{ - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); - if (!validDefinition) - return -1; - - return (tempDefinition.offsetY); -} - -int StringTTF::getAdvanceForChar(unsigned short c, int hintPositionInString) -{ - if (_advances) - { - // not that advance contains the X offset already - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); - if (!validDefinition) - return -1; - - return (_advances[hintPositionInString].width - tempDefinition.offsetX); - } - else - { - return -1; - } -} - -Rect StringTTF::getRectForChar(unsigned short c) -{ - return _fontAtlas->getFont().getRectForChar(c); -} - -// string related stuff -int StringTTF::getStringNumLines() -{ - int quantityOfLines = 1; - - unsigned int stringLen = _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0; - if (stringLen == 0) - return (-1); - - // count number of lines - for (unsigned int i = 0; i < stringLen - 1; ++i) - { - unsigned short c = _currentUTF8String[i]; - if (c == '\n') - { - quantityOfLines++; - } - } - - return quantityOfLines; -} - -int StringTTF::getStringLenght() -{ - return _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0; -} - -unsigned short StringTTF::getCharAtStringPosition(int position) -{ - return _currentUTF8String[position]; -} - -unsigned short * StringTTF::getUTF8String() -{ - return _currentUTF8String; -} - -void StringTTF::assignNewUTF8String(unsigned short *newString) -{ - setCurrentString(newString); -} - -TextHAlignment StringTTF::getTextAlignment() -{ - return _alignment; -} - -// label related stuff -float StringTTF::getMaxLineWidth() -{ - return _width; -} - -bool StringTTF::breakLineWithoutSpace() -{ - return _lineBreakWithoutSpaces; -} - -Size StringTTF::getLabelContentSize() -{ - return getContentSize(); -} - -void StringTTF::setLabelContentSize(const Size &newSize) -{ - setContentSize(newSize); -} - - -// RGBA protocol - - -bool StringTTF::isOpacityModifyRGB() const -{ - return false; -} - -void StringTTF::setOpacityModifyRGB(bool isOpacityModifyRGB) -{ -} - -unsigned char StringTTF::getOpacity() const -{ - return 0; -} - -unsigned char StringTTF::getDisplayedOpacity() const -{ - return 0; -} - -void StringTTF::setOpacity(GLubyte opacity) -{ -} -void StringTTF::updateDisplayedOpacity(GLubyte parentOpacity) -{ -} - -bool StringTTF::isCascadeOpacityEnabled() const -{ - return false; -} - -void StringTTF::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) -{ -} - -const Color3B& StringTTF::getColor(void) const -{ - return _realColor; -} - -const Color3B& StringTTF::getDisplayedColor() const -{ - return _displayedColor; -} - -void StringTTF::setColor(const Color3B& color) -{ - _displayedColor = _realColor = color; - - if( _cascadeColorEnabled ) - { - Color3B parentColor = Color3B::WHITE; - RGBAProtocol* pParent = dynamic_cast(_parent); - - if (pParent && pParent->isCascadeColorEnabled()) - parentColor = pParent->getDisplayedColor(); - - updateDisplayedColor(parentColor); - } -} - -void StringTTF::updateDisplayedColor(const Color3B& parentColor) -{ - _displayedColor.r = _realColor.r * parentColor.r/255.0; - _displayedColor.g = _realColor.g * parentColor.g/255.0; - _displayedColor.b = _realColor.b * parentColor.b/255.0; - - Object* pObj; - CCARRAY_FOREACH(_children, pObj) - { - Sprite *item = static_cast( pObj ); - item->updateDisplayedColor(_displayedColor); - } -} - -bool StringTTF::isCascadeColorEnabled() const -{ - return false; -} - -void StringTTF::setCascadeColorEnabled(bool cascadeColorEnabled) -{ - _cascadeColorEnabled = cascadeColorEnabled; -} - -NS_CC_END diff --git a/cocos2dx/label_nodes/CCStringTTF.h b/cocos2dx/label_nodes/CCStringTTF.h deleted file mode 100644 index 7e6108608e..0000000000 --- a/cocos2dx/label_nodes/CCStringTTF.h +++ /dev/null @@ -1,146 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _StringTTF_h -#define _StringTTF_h - -#include "CCFontDefinition.h" -#include "CCLabelTextFormatProtocol.h" -#include "CCLabel.h" -#include "CCFontAtlas.h" - -NS_CC_BEGIN - -class CC_DLL StringTTF : public Label, public LabelTextFormatProtocol -{ -public: - - static StringTTF* create(FontAtlas *pAtlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0); - - // main interface - bool setText(const char *stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); - void setString(const char *stringToRender); - const char* getString() const { return "not implemented"; } - - virtual void setAlignment(TextHAlignment alignment); - virtual void setWidth(float width); - virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); - virtual void setScale(float scale); - virtual void setScaleX(float scaleX); - virtual void setScaleY(float scaleY); - - - // RGBAProtocol - virtual bool isOpacityModifyRGB() const; - virtual void setOpacityModifyRGB(bool isOpacityModifyRGB); - virtual unsigned char getOpacity() const; - virtual unsigned char getDisplayedOpacity() const; - virtual void setOpacity(GLubyte opacity); - virtual void updateDisplayedOpacity(GLubyte parentOpacity); - virtual bool isCascadeOpacityEnabled() const; - virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled); - virtual const Color3B& getColor(void) const; - virtual const Color3B& getDisplayedColor() const; - virtual void setColor(const Color3B& color); - virtual void updateDisplayedColor(const Color3B& parentColor); - virtual bool isCascadeColorEnabled() const; - virtual void setCascadeColorEnabled(bool cascadeColorEnabled); - - - // CCLabelTextFormat protocol implementation - - // sprite related stuff - virtual Sprite * getSpriteChild(int ID); - virtual Array * getChildrenLetters(); - virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint); - virtual float getLetterPosXLeft( Sprite* sp ); - virtual float getLetterPosXRight( Sprite* sp ); - - // font related stuff - virtual int getCommonLineHeight(); - virtual int getKerningForCharsPair(unsigned short first, unsigned short second); - virtual int getXOffsetForChar(unsigned short c); - virtual int getYOffsetForChar(unsigned short c); - virtual int getAdvanceForChar(unsigned short c, int hintPositionInString); - virtual Rect getRectForChar(unsigned short c) ; - - // string related stuff - virtual int getStringNumLines(); - virtual int getStringLenght(); - virtual unsigned short getCharAtStringPosition(int position); - virtual unsigned short * getUTF8String(); - virtual void assignNewUTF8String(unsigned short *newString); - virtual TextHAlignment getTextAlignment(); - - // label related stuff - virtual float getMaxLineWidth() ; - virtual bool breakLineWithoutSpace(); - virtual Size getLabelContentSize(); - virtual void setLabelContentSize(const Size &newSize); - - -private: - - // - StringTTF(FontAtlas *pAtlas, TextHAlignment alignment = TextHAlignment::LEFT); - ~StringTTF(); - - bool init(); - - void alignText(); - void hideAllLetters(); - void moveAllSpritesToCache(); - - bool computeAdvancesForString(unsigned short int *stringToRender); - bool setCurrentString(unsigned short *stringToSet); - bool setOriginalString(unsigned short *stringToSet); - void resetCurrentString(); - - Sprite * getSprite(); - Sprite * createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture); - Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture); - Sprite * getSpriteForLetter(unsigned short int newLetter); - Sprite * updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter); - - Array _spriteArray; - Array _spriteArrayCache; - float _commonLineHeight; - bool _lineBreakWithoutSpaces; - float _width; - TextHAlignment _alignment; - unsigned short int * _currentUTF8String; - unsigned short int * _originalUTF8String; - Size * _advances; - FontAtlas * _fontAtlas; - Color3B _displayedColor; - Color3B _realColor; - bool _cascadeColorEnabled; - -}; - -NS_CC_END - -#endif - - diff --git a/cocos2dx/label_nodes/CCTextImage.cpp b/cocos2dx/label_nodes/CCTextImage.cpp index e8480f07d5..485668ad40 100644 --- a/cocos2dx/label_nodes/CCTextImage.cpp +++ b/cocos2dx/label_nodes/CCTextImage.cpp @@ -30,7 +30,7 @@ #include "cocos2d.h" #include "CCTextImage.h" #include "CCFontFreeType.h" -#include "CCFontRenderFreeType.h" +#include "CCFont.h" NS_CC_BEGIN @@ -91,8 +91,6 @@ bool TextPageDef::generatePageTexture(bool releasePageData) int dataLenght = (_width * _height * 4); bool textureCreated = _pageTexture->initWithData(_pageData, dataLenght, Texture2D::PixelFormat::RGBA8888, _width, _height, imageSize); -// _pageTexture->setPremultipliedAlpha(true); - // release the page data if requested if ( releasePageData && textureCreated ) { @@ -132,7 +130,7 @@ TextFontPagesDef::~TextFontPagesDef() } } -TextImage::TextImage(): _font(0), _fontRender(0), _fontPages(0) +TextImage::TextImage(): _font(0), _fontPages(0) { } @@ -143,37 +141,38 @@ TextImage::~TextImage() if (_font) _font->release(); - - if (_fontRender) - delete _fontRender; } -bool TextImage::initWithString(const char * pText, int nWidth, int nHeight, const char * pFontName, int nSize, bool releaseRAWData) +bool TextImage::initWithString(const char *text, int nWidth, int nHeight, cocos2d::Font* font, bool releaseRAWData) { - // carloX bool textIsUTF16 = false; - // create the reference to the font we want to use - if ( !createFontRef(pFontName, nSize) ) - return false; + if (_font) + { + _font->release(); + _font = 0; + } + + // carloX + _font = font; // generate the glyphs for the requested text (glyphs are latter's bounding boxes) - if ( !generateTextGlyphs(pText) ) + if ( !generateTextGlyphs(text) ) return false; - + Size constrainSize; unsigned short int *strUTF16 = 0; - int stringNumChars; + int stringNumChars; if ( textIsUTF16 ) { - strUTF16 = (unsigned short int *)pText; + strUTF16 = (unsigned short int *)text; stringNumChars = cc_wcslen(strUTF16); } else { // string needs to go to unicode - strUTF16 = _font->getUTF16Text(pText, stringNumChars); + strUTF16 = _font->getUTF16Text(text, stringNumChars); } if (!strUTF16 || !stringNumChars) @@ -189,6 +188,8 @@ bool TextImage::initWithString(const char * pText, int nWidth, int nHeight, cons // actually create the needed images return createImageDataFromPages(_fontPages, releaseRAWData); + + return true; } bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight) @@ -321,48 +322,6 @@ int TextImage::getNumGlyphsFittingInSize(std::map return numChar; } -bool TextImage::createFontRef(const char *fontName, int fontSize) -{ - if (_font) - { - _font->release(); - _font = 0; - } - - // carloX - _font = new FontFreeType(); - - if (!_font) - return false; - - _font->retain(); - - if( !_font->createFontObject(fontName, fontSize)) - return false; - - return true; -} - -bool TextImage::createFontRender() -{ - if (!_font) - return false; - - if (_fontRender) - { - delete _fontRender; - _fontRender = 0; - } - - // carloX - _fontRender = new FontRenderFreeType(_font); - - if (!_fontRender) - return false; - - return true; -} - bool TextImage::addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16) { if (!_font) @@ -445,19 +404,104 @@ bool TextImage::createImageDataFromPages(TextFontPagesDef *thePages, bool releas unsigned char * TextImage::preparePageGlyphData(TextPageDef *thePage) { - if ( !_fontRender ) + return renderGlyphData(thePage); +} + +unsigned char * TextImage::renderGlyphData(TextPageDef *thePage) +{ + if (!thePage) + return 0; + + if (!_font) + return 0; + + if (thePage->getNumLines() == 0) + return NULL; + + int pageWidth = thePage->getWidth(); + int pageHeight = thePage->getHeight(); + + // prepare memory and clean to 0 + int sizeInBytes = (pageWidth * pageHeight * 4); + unsigned char* data = new unsigned char[sizeInBytes]; + + if (!data) + return 0; + + memset(data, 0, sizeInBytes); + + int numLines = thePage->getNumLines(); + + for (int c = 0; cgetLineAt(c); + + float origX = _font->getLetterPadding(); + float origY = pCurrentLine->getY(); + + int numGlyphToRender = pCurrentLine->getNumGlyph(); + + for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph) + { + GlyphDef currGlyph = pCurrentLine->getGlyphAt(cglyph); + renderCharAt(currGlyph.getUTF8Letter(), origX, origY, data, pageWidth); + origX += (currGlyph.getRect().size.width + _font->getLetterPadding()); + } } - if (_fontRender) +#ifdef _DEBUG_FONTS_ + static int counter = 0; + char outFilename[512]; + sprintf(outFilename,"testIMG%d", counter); + ++counter; + Image *pImage = new Image; + pImage->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false); + pImage->saveToFile(outFilename); +#endif + + // we are done here + return data; +} + +bool TextImage::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) +{ + if (!_font) + return false; + + unsigned char *sourceBitmap = 0; + int sourceWidth = 0; + int sourceHeight = 0; + + // get the glyph's bitmap + sourceBitmap = _font->getGlyphBitmap(charToRender, sourceWidth, sourceHeight); + + if(!sourceBitmap) + return false; + + int iX = posX; + int iY = posY; + + for (int y = 0; y < sourceHeight; ++y) { - return _fontRender->preparePageGlyphData(thePage); - } - else - { - return 0; + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + unsigned char cTemp = sourceBitmap[bitmap_y + x]; + + // the final pixel + int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp; + *(int*) &destMemory[(iX + ( iY * destSize ) ) * 4] = iTemp; + + iX += 1; + } + + iX = posX; + iY += 1; } + + //everything good + return true; } NS_CC_END diff --git a/cocos2dx/label_nodes/CCTextImage.h b/cocos2dx/label_nodes/CCTextImage.h index f8b980bb7a..3c92615260 100644 --- a/cocos2dx/label_nodes/CCTextImage.h +++ b/cocos2dx/label_nodes/CCTextImage.h @@ -25,11 +25,13 @@ #ifndef _TextImage_h_ #define _TextImage_h_ -#include "CCFontRender.h" -#include "CCFont.h" +//#include "CCFont.h" +#include NS_CC_BEGIN +class Font; + /** @brief GlyphDef defines one single glyph (character) in a text image * * it defines the bounding box for the glyph in the texture page, the character the padding (spacing) between characters @@ -161,27 +163,27 @@ public: TextImage(); ~TextImage(); - bool initWithString(const char *pText, int nWidth, int nHeight, const char * pFontName, int nSize, bool releaseRAWData = true); + bool initWithString(const char *text, int nWidth, int nHeight, Font* font, bool releaseRAWData = true); + TextFontPagesDef * getPages() { return _fontPages; } Font * getFont() { return _font; } private: - unsigned char * preparePageGlyphData(TextPageDef *thePage); bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true); - bool createFontRender(); bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false); - bool createFontRef(const char *fontName, int size); bool generateTextGlyphs(const char * pText); int getNumGlyphsFittingInSize(std::map &glyphDefs, unsigned short int *strUTF8, Font *pFont, Size *constrainSize, int &outNewSize); bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight); + unsigned char * preparePageGlyphData(TextPageDef *thePage); + + // glyph rendering + unsigned char * renderGlyphData(TextPageDef *thePage); + bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); std::map _textGlyphs; TextFontPagesDef * _fontPages; - Font * _font; - FontRender * _fontRender; - - + Font * _font; }; diff --git a/cocos2dx/platform/blackberry/CCImage.cpp b/cocos2dx/platform/blackberry/CCImage.cpp deleted file mode 100644 index 3c08d2e438..0000000000 --- a/cocos2dx/platform/blackberry/CCImage.cpp +++ /dev/null @@ -1,442 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -#define __CC_PLATFORM_IMAGE_CPP__ -#include "platform/CCImageCommon_cpp.h" - -#include -#include -#include -#include -#include -#include "platform/CCImage.h" -#include "platform/CCFileUtils.h" -#include "platform/CCCommon.h" -#include "CCStdC.h" -#include "ft2build.h" -#include FT_FREETYPE_H - -#define szFont_kenning 2 - -#define SHIFT6(num) (num>>6) - -using namespace std; - -struct TextLine { - int iLineWidth; - wchar_t* text; -}; - -NS_CC_BEGIN - -class BitmapDC -{ -public: - BitmapDC() - { - libError = FT_Init_FreeType( &library ); - iInterval = szFont_kenning; - _data = NULL; - reset(); - } - - ~BitmapDC(void) - { - FT_Done_FreeType(library); - } - - void reset() { - iMaxLineWidth = 0; - iMaxLineHeight = 0; - size_t size = vLines.size(); - for (int i=0; iglyph->metrics.horiAdvance - face->glyph->metrics.horiBearingX - face->glyph->metrics.width))/*-iInterval*/;//TODO interval - iMaxLineWidth = MAX(iMaxLineWidth, oTempLine.iLineWidth); - - vLines.push_back(oTempLine); - } - - bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight) { - int iError = 0; - int iCurXCursor, iCurYCursor; - const char* pText = sText; - - FT_UInt unicode = utf8((char**)&pText); - iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT); - if (iError) { - return false; - } - iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX); - - FT_UInt cLastCh = 0; - - pText = sText; - size_t text_len = 0; - wchar_t* text_buf = (wchar_t*) malloc(sizeof(wchar_t) * strlen(sText)); - while (unicode=utf8((char**)&pText)) { - if (unicode == '\n') { - buildLine(text_buf, text_len, face, iCurXCursor, cLastCh); - text_len = 0; - - iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT); - if (iError) { - free(text_buf); - return false; - } - iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX); - continue; - } - - iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT); - - if (iError) { - free(text_buf); - return false; - } - - //check its width - //divide it when exceeding - if ((iMaxWidth > 0 - && iCurXCursor + SHIFT6(face->glyph->metrics.width) - > iMaxWidth)) { - buildLine(text_buf, text_len, face , iCurXCursor, cLastCh); - text_len = 0; - - iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX); - } - - cLastCh = unicode; - text_buf[text_len] = unicode; - ++text_len; - iCurXCursor += SHIFT6(face->glyph->metrics.horiAdvance) + iInterval; - } - - if (iError) { - free(text_buf); - return false; - } - - buildLine(text_buf, text_len, face, iCurXCursor, cLastCh); - free(text_buf); - - return true; - } - - /** - * compute the start pos of every line - * - * return >0 represent the start x pos of the line - * while -1 means fail - * - */ - int computeLineStart(FT_Face face, Image::TextAlign eAlignMask, char cText, - int iLineIndex) { - int iRet; - int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, cText), - FT_LOAD_DEFAULT); - if (iError) { - return -1; - } - - if (eAlignMask == Image::kAlignCenter) { - iRet = (iMaxLineWidth - vLines[iLineIndex].iLineWidth) / 2 - - SHIFT6(face->glyph->metrics.horiBearingX ); - - } else if (eAlignMask == Image::kAlignRight) { - iRet = (iMaxLineWidth - vLines[iLineIndex].iLineWidth) - - SHIFT6(face->glyph->metrics.horiBearingX ); - } else { - // left or other situation - iRet = -SHIFT6(face->glyph->metrics.horiBearingX ); - } - return iRet; - } - - int computeLineStartY( FT_Face face, Image::TextAlign eAlignMask, int txtHeight, int borderHeight ){ - int iRet; - if (eAlignMask == Image::kAlignCenter || eAlignMask == Image::kAlignLeft || - eAlignMask == Image::kAlignRight ) { - //vertical center - iRet = (borderHeight - txtHeight)/2 + SHIFT6(face->size->metrics.ascender); - - } else if (eAlignMask == Image::kAlignBottomRight || - eAlignMask == Image::kAlignBottom || - eAlignMask == Image::kAlignBottomLeft ) { - //vertical bottom - iRet = borderHeight - txtHeight + SHIFT6(face->size->metrics.ascender); - } else { - // left or other situation - iRet = SHIFT6(face->size->metrics.ascender); - } - return iRet; - } - - bool getBitmap(const char *text, int nWidth, int nHeight, Image::TextAlign eAlignMask, const char * pFontName, float fontSize) { - FT_Face face; - FT_Error iError; - - const char* pText = text; - //data will be deleted by Image - // if (_data) { - // delete _data; - // } - - int iCurXCursor, iCurYCursor; - bool bRet = false; - if (libError) { - return false; - } - do { - //CCLog(" ---- FT_New_Face with pFontName = %s", pFontName); - iError = FT_New_Face( library, pFontName, 0, &face ); - - if (iError) { - //no valid font found use default - //CCLog(" ---- no valid font, use default %s", pFontName); - iError = FT_New_Face( library, "/usr/fonts/font_repository/monotype/arial.ttf", 0, &face ); - } - CC_BREAK_IF(iError); - - //select utf8 charmap - iError = FT_Select_Charmap(face,FT_ENCODING_UNICODE); - CC_BREAK_IF(iError); - - iError = FT_Set_Pixel_Sizes(face, fontSize,fontSize); - CC_BREAK_IF(iError); - - iError = divideString(face, text, nWidth, nHeight)?0:1; - - //compute the final line width - iMaxLineWidth = MAX(iMaxLineWidth, nWidth); - - iMaxLineHeight = (face->size->metrics.ascender >> 6) - - (face->size->metrics.descender >> 6); - iMaxLineHeight *= vLines.size(); - - int txtHeight = iMaxLineHeight; - - //compute the final line height - iMaxLineHeight = MAX(iMaxLineHeight, nHeight); - _data = new unsigned char[iMaxLineWidth * iMaxLineHeight*4]; -// iCurYCursor = SHIFT6(face->size->metrics.ascender); - iCurYCursor = computeLineStartY( face, eAlignMask, txtHeight, iMaxLineHeight ); - - memset(_data,0, iMaxLineWidth * iMaxLineHeight*4); - - size_t lines = vLines.size(); - for (size_t i = 0; i < lines; i++) { - const wchar_t* text_ptr = vLines[i].text; - - //initialize the origin cursor - iCurXCursor = computeLineStart(face, eAlignMask, text_ptr[0], i); - - size_t text_len = wcslen(text_ptr); - for (size_t i=0; iglyph->bitmap; - - int yoffset = iCurYCursor - (face->glyph->metrics.horiBearingY >> 6); - int xoffset = iCurXCursor + (face->glyph->metrics.horiBearingX >> 6); - for (int i = 0; i < bitmap.rows; ++i) { - for (int j = 0; j < bitmap.width; ++j) { - unsigned char cTemp = bitmap.buffer[i * bitmap.width + j]; - if (cTemp == 0) continue; - - // if it has gray>0 we set show it as 1, o otherwise - int iY = yoffset + i; - int iX = xoffset + j; - - if (iY>=iMaxLineHeight) { - //exceed the height truncate - continue; - } - -// _data[(iY * iMaxLineWidth + iX) * 4 + 3] = -// bitmap.buffer[i * bitmap.width + j] ? -// 0xff : 0;//alpha -// _data[(iY * iMaxLineWidth + iX) * 4 + 1] = -// bitmap.buffer[i * bitmap.width + j];//R -// _data[(iY * iMaxLineWidth + iX) * 4 + 2] = -// bitmap.buffer[i * bitmap.width + j];//G -// _data[(iY * iMaxLineWidth + iX) * 4 + 0] = -// bitmap.buffer[i * bitmap.width + j];//B - - int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp; - *(int*) &_data[(iY * iMaxLineWidth + iX) * 4 + 0] = iTemp; - } - } - //step to next glyph - iCurXCursor += (face->glyph->metrics.horiAdvance >> 6) - + iInterval; - - pText++; - } - iCurYCursor += (face->size->metrics.ascender >> 6) - - (face->size->metrics.descender >> 6); - } - //print all image bitmap - // for (int i = 0; i < iMaxLineHeight; i++) { - // for (int j = 0; j < iMaxLineWidth; j++) { - // printf("%d", - // _data[(i * iMaxLineWidth + j) * 4] ? 1 : 0); - // } - // printf("\n"); - // } - - // free face - FT_Done_Face(face); - face = NULL; - - //clear all lines - vLines.clear(); - - //success; - if (iError) { - bRet = false; - } else - bRet = true; - }while(0); - - return bRet; - } - -public: - FT_Library library; - unsigned char *_data; - int libError; - vector vLines; - int iInterval; - int iMaxLineWidth; - int iMaxLineHeight; -}; - -static BitmapDC& sharedBitmapDC() -{ - static BitmapDC s_BmpDC; - return s_BmpDC; -} - -bool Image::initWithString( - const char * pText, - int nWidth/* = 0*/, - int nHeight/* = 0*/, - TextAlign eAlignMask/* = kAlignCenter*/, - const char * pFontName/* = nil*/, - int nSize/* = 0*/) -{ - bool bRet = false; - do - { - CC_BREAK_IF(! pText); - BitmapDC &dc = sharedBitmapDC(); - - std::string fullFontName = pFontName; - std::string lowerCasePath = fullFontName; - std::transform(lowerCasePath.begin(), lowerCasePath.end(), lowerCasePath.begin(), ::tolower); - - if ( lowerCasePath.find(".ttf") != std::string::npos ) { - fullFontName = FileUtils::getInstance()->fullPathForFilename(pFontName); - } - //CCLog("-----pText=%s and Font File is %s nWidth= %d,nHeight=%d",pText,fullFontName.c_str(),nWidth,nHeight); - - CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, fullFontName.c_str(), nSize)); - //CCLog("---- dc.getBitmap is Succesfull..."); - - // assign the dc._data to _data in order to save time - _data = dc._data; - CC_BREAK_IF(! _data); - - _width = (short)dc.iMaxLineWidth; - _height = (short)dc.iMaxLineHeight; - _preMulti = true; - _renderFormat = Texture2D::PixelFormat::RGBA8888; - - bRet = true; - - dc.reset(); - - } while (0); - - return bRet; -} - -NS_CC_END - diff --git a/cocos2dx/proj.emscripten/Makefile b/cocos2dx/proj.emscripten/Makefile index 718d7259c3..0413932507 100644 --- a/cocos2dx/proj.emscripten/Makefile +++ b/cocos2dx/proj.emscripten/Makefile @@ -52,18 +52,14 @@ SOURCES = ../actions/CCAction.cpp \ ../label_nodes/CCFontAtlas.cpp \ ../label_nodes/CCFontAtlasCache.cpp \ ../label_nodes/CCFontAtlasFactory.cpp \ -../label_nodes/CCFontCache.cpp \ ../label_nodes/CCFontDefinition.cpp \ ../label_nodes/CCFontFNT.cpp \ ../label_nodes/CCFontFreeType.cpp \ -../label_nodes/CCFontRenderFreeType.cpp \ ../label_nodes/CCLabel.cpp \ ../label_nodes/CCLabelAtlas.cpp \ ../label_nodes/CCLabelBMFont.cpp \ ../label_nodes/CCLabelTTF.cpp \ ../label_nodes/CCLabelTextFormatter.cpp \ -../label_nodes/CCStringBMFont.cpp \ -../label_nodes/CCStringTTF.cpp \ ../label_nodes/CCTextImage.cpp \ ../layers_scenes_transitions_nodes/CCLayer.cpp \ ../layers_scenes_transitions_nodes/CCScene.cpp \ diff --git a/cocos2dx/proj.linux/Makefile b/cocos2dx/proj.linux/Makefile index 04c127cc94..0d5f8df909 100644 --- a/cocos2dx/proj.linux/Makefile +++ b/cocos2dx/proj.linux/Makefile @@ -49,18 +49,14 @@ SOURCES = ../actions/CCAction.cpp \ ../label_nodes/CCFontAtlas.cpp \ ../label_nodes/CCFontAtlasCache.cpp \ ../label_nodes/CCFontAtlasFactory.cpp \ -../label_nodes/CCFontCache.cpp \ ../label_nodes/CCFontDefinition.cpp \ ../label_nodes/CCFontFNT.cpp \ ../label_nodes/CCFontFreeType.cpp \ -../label_nodes/CCFontRenderFreeType.cpp \ ../label_nodes/CCLabel.cpp \ ../label_nodes/CCLabelAtlas.cpp \ ../label_nodes/CCLabelBMFont.cpp \ ../label_nodes/CCLabelTTF.cpp \ ../label_nodes/CCLabelTextFormatter.cpp \ -../label_nodes/CCStringBMFont.cpp \ -../label_nodes/CCStringTTF.cpp \ ../label_nodes/CCTextImage.cpp \ ../layers_scenes_transitions_nodes/CCLayer.cpp \ ../layers_scenes_transitions_nodes/CCScene.cpp \ diff --git a/cocos2dx/proj.win32/cocos2d.vcxproj b/cocos2dx/proj.win32/cocos2d.vcxproj index 5f5a799554..2f6b612477 100644 --- a/cocos2dx/proj.win32/cocos2d.vcxproj +++ b/cocos2dx/proj.win32/cocos2d.vcxproj @@ -178,18 +178,14 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir - - - - @@ -334,16 +330,12 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir - - - - diff --git a/cocos2dx/proj.win32/cocos2d.vcxproj.filters b/cocos2dx/proj.win32/cocos2d.vcxproj.filters index 260f7c51f4..40bf2c4c95 100644 --- a/cocos2dx/proj.win32/cocos2d.vcxproj.filters +++ b/cocos2dx/proj.win32/cocos2d.vcxproj.filters @@ -485,9 +485,6 @@ label_nodes - - label_nodes - label_nodes @@ -497,21 +494,12 @@ label_nodes - - label_nodes - label_nodes label_nodes - - label_nodes - - - label_nodes - label_nodes @@ -1018,12 +1006,6 @@ label_nodes - - label_nodes - - - label_nodes - label_nodes @@ -1033,12 +1015,6 @@ label_nodes - - label_nodes - - - label_nodes - label_nodes diff --git a/cocos2dx/textures/CCTextureCache.cpp b/cocos2dx/textures/CCTextureCache.cpp index f034997930..f421f71e18 100644 --- a/cocos2dx/textures/CCTextureCache.cpp +++ b/cocos2dx/textures/CCTextureCache.cpp @@ -142,7 +142,7 @@ void TextureCache::addImageAsync(const char *path, Object *target, SEL_CallFuncO if (_asyncStructQueue == NULL) { _asyncStructQueue = new queue(); - _imageInfoQueue = new queue(); + _imageInfoQueue = new queue(); // create a new thread to load images _loadingThread = new std::thread(&TextureCache::loadImage, this); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp index 5050ea73b0..0e0599b0fa 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp @@ -69,15 +69,6 @@ static std::function createFunctions[] = CL(LabelTTFAlignment), CL(LabelBMFontBounds), CL(TTFFontShadowAndStroke), - CL(NewLabelTTFTestLongLine), - // CL(NewLabelTTFTestUnicode), - CL(NewLabelTTFColorTest), - CL(NewLabelTTFFontsTest), - CL(NewLabelTTFAlignment), - CL(NewLabelTTFUnicode), - CL(NewLabelBMFontTest), -// CL(NewLabelFontDefTest), - // should be moved to another test CL(Atlas1), }; @@ -357,12 +348,13 @@ LabelTTFAlignment::LabelTTFAlignment() LabelTTF* ttf0 = LabelTTF::create("Alignment 0\nnew line", "Helvetica", 12, Size(256, 32), TextHAlignment::LEFT); + ttf0->setPosition(Point(s.width/2,(s.height/6)*2)); ttf0->setAnchorPoint(Point(0.5f,0.5f)); this->addChild(ttf0); - + LabelTTF* ttf1 = LabelTTF::create("Alignment 1\nnew line", "Helvetica", 12, - Size(245, 32), TextHAlignment::CENTER); + Size(245, 32), TextHAlignment::CENTER); ttf1->setPosition(Point(s.width/2,(s.height/6)*3)); ttf1->setAnchorPoint(Point(0.5f,0.5f)); this->addChild(ttf1); @@ -452,7 +444,6 @@ void Atlas3::step(float dt) LabelBMFont *label3 = (LabelBMFont*) getChildByTag(kTagBitmapAtlas3); label3->setString(string); - } std::string Atlas3::title() @@ -1620,321 +1611,3 @@ void LabelBMFontBounds::draw() }; DrawPrimitives::drawPoly(vertices, 4, true); } - -LabelBMFontNewTest::LabelBMFontNewTest() -{ - Size s = Director::getInstance()->getWinSize(); - - LayerColor *layer = LayerColor::create(Color4B(128,128,128,255)); - addChild(layer, -10); - - // LabelBMFont - label1 = StringBMFont::create("Testing Glyph Designer", "fonts/boundsTestFont.fnt"); - - addChild(label1); - label1->setPosition(Point(s.width/2, s.height/2)); -} - -void LabelBMFontNewTest::draw() -{ -} -std::string LabelBMFontNewTest::title() -{ - return "New LabelBMFont"; -} - -std::string LabelBMFontNewTest::subtitle() -{ - return "Testing the new LabelBMFont"; -} - -/// - -// -// NewLabelTTFTestLongLine -// -NewLabelTTFTestLongLine::NewLabelTTFTestLongLine() -{ - Size size = Director::getInstance()->getWinSize(); - - // Long sentence - auto label1 = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 28, GlyphCollection::NEHE, size.width); - label1->setPosition( Point(size.width/2, size.height/2) ); - label1->setAnchorPoint(Point(0.5, 1.0)); - addChild(label1); -} - -std::string NewLabelTTFTestLongLine::title() -{ - return "Label() using TTF"; -} - -std::string NewLabelTTFTestLongLine::subtitle() -{ - return "Uses the new Label() with TTF. Testing auto-wrapping"; -} - -// -// NewLabelTTFColorTest -// -NewLabelTTFColorTest::NewLabelTTFColorTest() -{ - Size size = Director::getInstance()->getWinSize(); - - // Green - auto label1 = Label::createWithTTF("Green", "fonts/arial.ttf", 35, GlyphCollection::NEHE, size.width); - label1->setPosition( Point(size.width/2, size.height/5 * 1.5) ); - label1->setColor( Color3B::GREEN ); - label1->setAnchorPoint(Point(0.5, 0.5)); - addChild(label1); - - // Red - auto label2 = Label::createWithTTF("Red", "fonts/arial.ttf", 35, GlyphCollection::NEHE, size.width); - label2->setPosition( Point(size.width/2, size.height/5 * 2.0) ); - label2->setColor( Color3B::RED ); - label2->setAnchorPoint(Point(0.5, 0.5)); - addChild(label2); - - // Blue - auto label3 = Label::createWithTTF("Blue", "fonts/arial.ttf", 35, GlyphCollection::NEHE, size.width); - label3->setPosition( Point(size.width/2, size.height/5 * 2.5) ); - label3->setColor( Color3B::BLUE ); - label3->setAnchorPoint(Point(0.5, 0.5)); - addChild(label3); -} - -std::string NewLabelTTFColorTest::title() -{ - return "Label() using TTF with color"; -} - -std::string NewLabelTTFColorTest::subtitle() -{ - return "Uses the new Label() with TTF. Testing Color"; -} - -// -// NewLabelTTFColorTest -// -NewLabelTTFAlignment::NewLabelTTFAlignment() -{ - Size size = Director::getInstance()->getWinSize(); - - _label = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 45, GlyphCollection::NEHE, size.width); - _label->setPosition( Point(size.width/2, size.height/2) ); - _label->setAnchorPoint(Point(0.5, 0.5)); - - - - Menu *menu = Menu::create( - MenuItemFont::create("Left", CC_CALLBACK_1(NewLabelTTFAlignment::setAlignmentLeft, this)), - MenuItemFont::create("Center", CC_CALLBACK_1(NewLabelTTFAlignment::setAlignmentCenter, this)), - MenuItemFont::create("Right", CC_CALLBACK_1(NewLabelTTFAlignment::setAlignmentRight, this)), - NULL); - - menu->alignItemsVerticallyWithPadding(4); - menu->setPosition(Point(50, size.height / 4 )); - - addChild(_label); - this->addChild(menu); -} - -void NewLabelTTFAlignment::updateAlignment() -{ - if (_label) - { - _label->setAlignment(_horizAlign); - } -} - -void NewLabelTTFAlignment::setAlignmentLeft(Object* sender) -{ - _horizAlign = TextHAlignment::LEFT; - this->updateAlignment(); -} - -void NewLabelTTFAlignment::setAlignmentCenter(Object* sender) -{ - _horizAlign = TextHAlignment::CENTER; - this->updateAlignment(); -} - -void NewLabelTTFAlignment::setAlignmentRight(Object* sender) -{ - _horizAlign = TextHAlignment::RIGHT; - this->updateAlignment(); -} - -std::string NewLabelTTFAlignment::title() -{ - return "Label() using TTF alignment"; -} - -std::string NewLabelTTFAlignment::subtitle() -{ - return "Uses the new Label() with TTF. Testing alignment"; -} - -// -// NewLabelTTF unicode test -// -NewLabelTTFUnicode::NewLabelTTFUnicode() -{ - Dictionary *strings = Dictionary::createWithContentsOfFile("fonts/strings.xml"); - const char *chinese = static_cast(strings->objectForKey("chinese1"))->_string.c_str(); - - //const char *russian = static_cast(strings->objectForKey("russian"))->_string.c_str(); - //const char *spanish = static_cast(strings->objectForKey("spanish"))->_string.c_str(); - //const char *japanese = static_cast(strings->objectForKey("japanese"))->_string.c_str(); - - Size size = Director::getInstance()->getWinSize(); - - float vStep = size.height/9; - float vSize = size.height; - - - // Spanish - auto label1 = Label::createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 45, GlyphCollection::ASCII, size.width); - label1->setPosition( Point(size.width/2, vSize - (vStep * 4.5)) ); - label1->setAnchorPoint(Point(0.5, 0.5)); - addChild(label1); - - // German - auto label2 = Label::createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 45, GlyphCollection::ASCII, size.width); - label2->setPosition( Point(size.width/2, vSize - (vStep * 5.5)) ); - label2->setAnchorPoint(Point(0.5, 0.5)); - addChild(label2); - - // chinese - auto label3 = Label::createWithTTF(chinese, "fonts/wt021.ttf", 45, GlyphCollection::CUSTOM, size.width, chinese); - label3->setPosition( Point(size.width/2, vSize - (vStep * 6.5)) ); - label3->setAnchorPoint(Point(0.5, 0.5)); - addChild(label3); -} - -std::string NewLabelTTFUnicode::title() -{ - return "Label() using TTF with unicode"; -} - -std::string NewLabelTTFUnicode::subtitle() -{ - return "Uses the new Label() with TTF. Testing unicode"; -} - - -// -// NewLabelTTFFontsTest -// -NewLabelTTFFontsTest::NewLabelTTFFontsTest() -{ - const char *ttfpaths[] = { - "fonts/A Damn Mess.ttf", - "fonts/Abberancy.ttf", - "fonts/Abduction.ttf", - "fonts/American Typewriter.ttf", - "fonts/Paint Boy.ttf", - "fonts/Schwarzwald Regular.ttf", - "fonts/Scissor Cuts.ttf", - }; -#define arraysize(ar) (sizeof(ar) / sizeof(ar[0])) - - Size size = Director::getInstance()->getWinSize(); - - for(int i=0;i < arraysize(ttfpaths); ++i) { - auto label = Label::createWithTTF( ttfpaths[i], ttfpaths[i], 40, GlyphCollection::NEHE); - if( label ) { - - label->setPosition( Point(size.width/2, ((size.height * 0.6)/arraysize(ttfpaths) * i) + (size.height/5))); - addChild(label); - - label->setAnchorPoint(Point(0.5, 0.5)); - } else { - log("ERROR: Cannot load: %s", ttfpaths[i]); - } - } -} - -std::string NewLabelTTFFontsTest::title() -{ - return "Label() using different TTF files"; -} - -std::string NewLabelTTFFontsTest::subtitle() -{ - //return "Uses the new Label() with non standard TTF files"; - return ""; -} - -// -// NEW LABEL with BMFont -// -NewLabelBMFontTest::NewLabelBMFontTest() -{ - Size size = Director::getInstance()->getWinSize(); - - auto label1 = Label::createWithBMFont("Hello World, this is testing the new Label using fnt file", "fonts/bitmapFontTest2.fnt", size.width); - label1->setPosition( Point(size.width/2, size.height/2) ); - label1->setAnchorPoint(Point(0.5, 0.5)); - addChild(label1); -} - -std::string NewLabelBMFontTest::title() -{ - return "Label() using BMFont"; -} - -std::string NewLabelBMFontTest::subtitle() -{ - return "Uses the new Label() with BMFont"; -} - - - -// -/// NEW LABEL with BMFont -// -NewLabelBMFontTestOld::NewLabelBMFontTestOld() -{ - Size size = Director::getInstance()->getWinSize(); - - label = Label::createWithBMFontOLD("Hello world, this uses new label with FTN file", "fonts/bitmapFontTest2.fnt", size.width); - label->setPosition( Point(size.width/2, size.height/2) ); - label->setAnchorPoint(Point(0.5, 0.5)); - label->retain(); - addChild(label); -} - -NewLabelBMFontTestOld::~NewLabelBMFontTestOld() -{ - CC_SAFE_RELEASE(label); -} - -std::string NewLabelBMFontTestOld::title() -{ - return "Label() using BMFont OLD"; -} - -std::string NewLabelBMFontTestOld::subtitle() -{ - return "Uses the new Label() with BMFont OLD"; -} - - - -// -// NEW LABEL with FontDefinition -// -NewLabelFontDefTest::NewLabelFontDefTest() -{ -} - -std::string NewLabelFontDefTest::title() -{ - return "NOT IMPLEMENTED YET"; -} - -std::string NewLabelFontDefTest::subtitle() -{ - return "NOT IMPLEMENTED YET"; -} diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h index ea8fa1bdf5..9143361beb 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h @@ -316,38 +316,6 @@ private: LabelBMFont *label1; }; -class LabelBMFontNewTest : public AtlasDemo -{ -public: - LabelBMFontNewTest(); - - virtual void draw(); - virtual std::string title(); - virtual std::string subtitle(); -private: - StringBMFont *label1; -}; - -class NewLabelTTFTestLongLine : public AtlasDemo -{ -public: - - NewLabelTTFTestLongLine(); - - virtual std::string title(); - virtual std::string subtitle(); -}; - -class NewLabelTTFColorTest : public AtlasDemo -{ -public: - - NewLabelTTFColorTest(); - - virtual std::string title(); - virtual std::string subtitle(); -}; - class NewLabelTTFUnicode : public AtlasDemo { public: @@ -358,38 +326,6 @@ public: virtual std::string subtitle(); }; -class NewLabelTTFAlignment : public AtlasDemo -{ -public: - - NewLabelTTFAlignment(); - virtual std::string title(); - virtual std::string subtitle(); - -private: - - void setAlignmentLeft(Object* sender); - void setAlignmentCenter(Object* sender); - void setAlignmentRight(Object* sender); - void updateAlignment(); - - Label * _label; - TextHAlignment _horizAlign; - -}; - - -class NewLabelTTFFontsTest : public AtlasDemo -{ -public: - - NewLabelTTFFontsTest(); - - virtual std::string title(); - virtual std::string subtitle(); -}; - - class NewLabelBMFontTest : public AtlasDemo { public: @@ -402,22 +338,6 @@ public: private: }; - -class NewLabelBMFontTestOld : public AtlasDemo -{ -public: - - NewLabelBMFontTestOld(); - ~NewLabelBMFontTestOld(); - - virtual std::string title(); - virtual std::string subtitle(); - -private: - Label *label; -}; - - class NewLabelFontDefTest : public AtlasDemo { public: diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp new file mode 100644 index 0000000000..efcd45e149 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -0,0 +1,1138 @@ + #include "LabelTestNew.h" +#include "../testResource.h" + +enum { + kTagTileMap = 1, + kTagSpriteManager = 1, + kTagAnimation1 = 1, + kTagBitmapAtlas1 = 1, + kTagBitmapAtlas2 = 2, + kTagBitmapAtlas3 = 3, +}; + +enum { + kTagSprite1, + kTagSprite2, + kTagSprite3, + kTagSprite4, + kTagSprite5, + kTagSprite6, + kTagSprite7, + kTagSprite8, +}; + +//------------------------------------------------------------------ +// +// AtlasDemoNew +// +//------------------------------------------------------------------ + +enum +{ + IDC_NEXT = 100, + IDC_BACK, + IDC_RESTART +}; + +Layer* nextAtlasActionNew(); +Layer* backAtlasActionNew(); +Layer* restartAtlasActionNew(); + +static int sceneIdx = -1; + +static std::function createFunctions[] = +{ + CL(LabelFNTColorAndOpacity), + CL(LabelFNTSpriteActions), + CL(LabelFNTPadding), + CL(LabelFNTOffset), + CL(LabelFNTColor), + CL(LabelFNTHundredLabels), + CL(LabelFNTMultiLine), + CL(LabelFNTandTTFEmpty), + CL(LabelFNTRetina), + CL(LabelFNTGlyphDesigner), + CL(LabelTTFUnicodeChinese), + CL(LabelFNTUnicodeChinese), + CL(LabelFNTMultiLineAlignment), + CL(LabelFNTUNICODELanguages), + CL(LabelTTFAlignmentNew), + CL(LabelFNTBounds), + CL(LabelTTFLongLineWrapping), + CL(LabelTTFColor), + CL(LabelTTFFontsTestNew), + CL(LabelTTFDynamicAlignment), + CL(LabelTTFUnicodeNew), + CL(LabelBMFontTestNew) +}; + +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + +Layer* nextAtlasActionNew() +{ + sceneIdx++; + sceneIdx = sceneIdx % MAX_LAYER; + + Layer* layer = (createFunctions[sceneIdx])(); + layer->autorelease(); + + return layer; +} + +Layer* backAtlasActionNew() +{ + sceneIdx--; + int total = MAX_LAYER; + if( sceneIdx < 0 ) + sceneIdx += total; + + Layer* layer = (createFunctions[sceneIdx])(); + layer->autorelease(); + + return layer; +} + +Layer* restartAtlasActionNew() +{ + Layer* layer = (createFunctions[sceneIdx])(); + layer->autorelease(); + + return layer; +} + +void AtlasTestSceneNew::runThisTest() +{ + sceneIdx = -1; + Layer* layer = nextAtlasActionNew(); + addChild(layer); + + Director::getInstance()->replaceScene(this); +} + +AtlasDemoNew::AtlasDemoNew(void) +{ +} + +AtlasDemoNew::~AtlasDemoNew(void) +{ +} + +std::string AtlasDemoNew::title() +{ + return "No title"; +} + +std::string AtlasDemoNew::subtitle() +{ + return ""; +} + +void AtlasDemoNew::onEnter() +{ + BaseTest::onEnter(); +} + +void AtlasDemoNew::restartCallback(Object* sender) +{ + Scene* s = new AtlasTestSceneNew(); + s->addChild(restartAtlasActionNew()); + + Director::getInstance()->replaceScene(s); + s->release(); +} + +void AtlasDemoNew::nextCallback(Object* sender) +{ + Scene* s = new AtlasTestSceneNew(); + s->addChild( nextAtlasActionNew() ); + Director::getInstance()->replaceScene(s); + s->release(); +} + +void AtlasDemoNew::backCallback(Object* sender) +{ + Scene* s = new AtlasTestSceneNew(); + s->addChild( backAtlasActionNew() ); + Director::getInstance()->replaceScene(s); + s->release(); +} + +LabelTTFAlignmentNew::LabelTTFAlignmentNew() +{ + Size s = Director::getInstance()->getWinSize(); + + Label* ttf0 = Label::createWithTTF("Alignment 0\nnew line", "fonts/tahoma.ttf", 32); + ttf0->setAlignment(TextHAlignment::LEFT); + ttf0->setPosition(Point(s.width/2,(s.height/6)*2 - 30)); + ttf0->setAnchorPoint(Point(0.5f,0.5f)); + this->addChild(ttf0); + + Label* ttf1 = Label::createWithTTF("Alignment 1\nnew line", "fonts/tahoma.ttf", 32); + ttf1->setAlignment(TextHAlignment::CENTER); + ttf1->setPosition(Point(s.width/2,(s.height/6)*3 - 30)); + ttf1->setAnchorPoint(Point(0.5f,0.5f)); + this->addChild(ttf1); + + Label* ttf2 = Label::createWithTTF("Alignment 2\nnew line", "fonts/tahoma.ttf", 32); + ttf1->setAlignment(TextHAlignment::RIGHT); + ttf2->setPosition(Point(s.width/2,(s.height/6)*4 - 30)); + ttf2->setAnchorPoint(Point(0.5f,0.5f)); + this->addChild(ttf2); +} + +std::string LabelTTFAlignmentNew::title() +{ + return "New Label + TTF"; +} + +std::string LabelTTFAlignmentNew::subtitle() +{ + return "Tests alignment values"; +} + +LabelFNTColorAndOpacity::LabelFNTColorAndOpacity() +{ + _time = 0; + + LayerColor* col = LayerColor::create( Color4B(128,128,128,255) ); + addChild(col, -10); + + Label * label1 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); + + label1->setAnchorPoint( Point(0,0) ); + addChild(label1, 0, kTagBitmapAtlas1); + ActionInterval* fade = FadeOut::create(1.0f); + ActionInterval* fade_in = fade->reverse(); + Sequence* seq = Sequence::create(fade, fade_in, NULL); + Action* repeat = RepeatForever::create(seq); + label1->runAction(repeat); + + Label *label2 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); + label2->setAnchorPoint( Point(0.5f, 0.5f) ); + label2->setColor( Color3B::RED ); + addChild(label2, 0, kTagBitmapAtlas2); + label2->runAction( repeat->clone() ); + + Label* label3 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); + label3->setAnchorPoint( Point(1,1) ); + addChild(label3, 0, kTagBitmapAtlas3); + + label1->setPosition( VisibleRect::leftBottom() ); + label2->setPosition( VisibleRect::center() ); + label3->setPosition( VisibleRect::rightTop() ); + + schedule( schedule_selector(LabelFNTColorAndOpacity::step) );//:@selector(step:)]; +} + +void LabelFNTColorAndOpacity::step(float dt) +{ + _time += dt; + char string[15] = {0}; + sprintf(string, "%2.2f Test j", _time); + + Label *label1 = (Label*) getChildByTag(kTagBitmapAtlas1); + label1->setString(string); + + Label *label2 = (Label*) getChildByTag(kTagBitmapAtlas2); + label2->setString(string); + + Label *label3 = (Label*) getChildByTag(kTagBitmapAtlas3); + label3->setString(string); +} + +std::string LabelFNTColorAndOpacity::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTColorAndOpacity::subtitle() +{ + return "Testing opacity + tint"; +} + +LabelFNTSpriteActions::LabelFNTSpriteActions() +{ + _time = 0; + + // Upper Label + Label *label = Label::createWithBMFont("Bitmap Font Atlas", "fonts/bitmapFontTest.fnt"); + addChild(label); + + Size s = Director::getInstance()->getWinSize(); + + label->setPosition( Point(s.width/2, s.height/2) ); + label->setAnchorPoint( Point(0.5f, 0.5f) ); + + + Sprite* BChar = (Sprite*) label->getChildByTag(0); + Sprite* FChar = (Sprite*) label->getChildByTag(7); + Sprite* AChar = (Sprite*) label->getChildByTag(12); + + + ActionInterval* rotate = RotateBy::create(2, 360); + Action* rot_4ever = RepeatForever::create(rotate); + + ActionInterval* scale = ScaleBy::create(2, 1.5f); + ActionInterval* scale_back = scale->reverse(); + Sequence* scale_seq = Sequence::create(scale, scale_back,NULL); + Action* scale_4ever = RepeatForever::create(scale_seq); + + ActionInterval* jump = JumpBy::create(0.5f, Point::ZERO, 60, 1); + Action* jump_4ever = RepeatForever::create(jump); + + ActionInterval* fade_out = FadeOut::create(1); + ActionInterval* fade_in = FadeIn::create(1); + Sequence* seq = Sequence::create(fade_out, fade_in, NULL); + Action* fade_4ever = RepeatForever::create(seq); + + BChar->runAction(rot_4ever); + BChar->runAction(scale_4ever); + FChar->runAction(jump_4ever); + AChar->runAction(fade_4ever); + + + // Bottom Label + Label *label2 = Label::createWithBMFont("00.0", "fonts/bitmapFontTest.fnt"); + addChild(label2, 0, kTagBitmapAtlas2); + label2->setPosition( Point(s.width/2.0f, 80) ); + + Sprite* lastChar = (Sprite*) label2->getChildByTag(1); + lastChar->runAction( rot_4ever->clone() ); + + schedule( schedule_selector(LabelFNTSpriteActions::step), 0.1f); +} + +void LabelFNTSpriteActions::draw() +{ + Size s = Director::getInstance()->getWinSize(); + DrawPrimitives::drawLine( Point(0, s.height/2), Point(s.width, s.height/2) ); + DrawPrimitives::drawLine( Point(s.width/2, 0), Point(s.width/2, s.height) ); +} + +void LabelFNTSpriteActions::step(float dt) +{ + _time += dt; + char string[10] = {0}; + sprintf(string, "%04.1f", _time); + Label* label1 = (Label*) getChildByTag(kTagBitmapAtlas2); + label1->setString(string); +} + +std::string LabelFNTSpriteActions::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTSpriteActions::subtitle() +{ + return "Using fonts as Sprite objects. Some characters should rotate."; +} + +LabelFNTPadding::LabelFNTPadding() +{ + Label *label = Label::createWithBMFont("abcdefg", "fonts/bitmapFontTest4.fnt"); + addChild(label); + + Size s = Director::getInstance()->getWinSize(); + + label->setPosition( Point(s.width/2, s.height/2) ); + label->setAnchorPoint( Point(0.5f, 0.5f) ); +} + +std::string LabelFNTPadding::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTPadding::subtitle() +{ + return "Testing padding"; +} + +LabelFNTOffset::LabelFNTOffset() +{ + Size s = Director::getInstance()->getWinSize(); + + Label* label = NULL; + label = Label::createWithBMFont("FaFeFiFoFu", "fonts/bitmapFontTest5.fnt"); + addChild(label); + label->setPosition( Point(s.width/2, s.height/2+50) ); + label->setAnchorPoint( Point(0.5f, 0.5f) ) ; + + label = Label::createWithBMFont("fafefifofu", "fonts/bitmapFontTest5.fnt"); + addChild(label); + label->setPosition( Point(s.width/2, s.height/2) ); + label->setAnchorPoint( Point(0.5f, 0.5f) ); + + label = Label::createWithBMFont("aeiou", "fonts/bitmapFontTest5.fnt"); + addChild(label); + label->setPosition( Point(s.width/2, s.height/2-50) ); + label->setAnchorPoint( Point(0.5f, 0.5f) ); +} + +std::string LabelFNTOffset::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTOffset::subtitle() +{ + return "Rendering should be OK. Testing offset"; +} + +LabelFNTColor::LabelFNTColor() +{ + Size s = Director::getInstance()->getWinSize(); + + Label* label = NULL; + label = Label::createWithBMFont("Blue", "fonts/bitmapFontTest5.fnt"); + label->setColor( Color3B::BLUE ); + addChild(label); + label->setPosition( Point(s.width/2, s.height/4) ); + label->setAnchorPoint( Point(0.5f, 0.5f) ); + + label = Label::createWithBMFont("Red", "fonts/bitmapFontTest5.fnt"); + addChild(label); + label->setPosition( Point(s.width/2, 2*s.height/4) ); + label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setColor( Color3B::RED ); + + label = Label::createWithBMFont("G", "fonts/bitmapFontTest5.fnt"); + addChild(label); + label->setPosition( Point(s.width/2, 3*s.height/4) ); + label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setColor( Color3B::GREEN ); + label->setString("Green"); +} + +std::string LabelFNTColor::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTColor::subtitle() +{ + return "Testing color"; +} + +LabelFNTHundredLabels::LabelFNTHundredLabels() +{ + // Upper Label + for ( int i=0 ; i < 100;i ++ ) + { + char str[6] = {0}; + sprintf(str, "-%d-", i); + Label* label = Label::createWithBMFont(str, "fonts/bitmapFontTest.fnt"); + addChild(label); + + Size s = Director::getInstance()->getWinSize(); + + Point p = Point( CCRANDOM_0_1() * s.width, CCRANDOM_0_1() * s.height); + label->setPosition( p ); + label->setAnchorPoint(Point(0.5f, 0.5f)); + } +} + +std::string LabelFNTHundredLabels::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTHundredLabels::subtitle() +{ + return "Creating several Labels using the same FNT file; should be fast"; +} + +LabelFNTMultiLine::LabelFNTMultiLine() +{ + Size s; + + // Left + Label* label1 = Label::createWithBMFont(" Multi line\nLeft", "fonts/bitmapFontTest3.fnt"); + label1->setAnchorPoint(Point(0,0)); + addChild(label1, 0, kTagBitmapAtlas1); + + s = label1->getContentSize(); + CCLOG("content size: %.2fx%.2f", s.width, s.height); + + + // Center + Label* label2 = Label::createWithBMFont("Multi line\nCenter", "fonts/bitmapFontTest3.fnt"); + label2->setAnchorPoint(Point(0.5f, 0.5f)); + addChild(label2, 0, kTagBitmapAtlas2); + + s= label2->getContentSize(); + CCLOG("content size: %.2fx%.2f", s.width, s.height); + + // right + Label *label3 = Label::createWithBMFont("Multi line\nRight\nThree lines Three", "fonts/bitmapFontTest3.fnt"); + label3->setAnchorPoint(Point(1, 1)); + addChild(label3, 0, kTagBitmapAtlas3); + + s = label3->getContentSize(); + CCLOG("content size: %.2fx%.2f", s.width, s.height); + + label1->setPosition(VisibleRect::leftBottom()); + label2->setPosition(VisibleRect::center()); + label3->setPosition(VisibleRect::rightTop()); +} + +std::string LabelFNTMultiLine::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTMultiLine::subtitle() +{ + return "Multiline + anchor point"; +} + +LabelFNTandTTFEmpty::LabelFNTandTTFEmpty() +{ + Size s = Director::getInstance()->getWinSize(); + float delta = s.height/4; + + // LabelBMFont + Label *label1 = Label::createWithBMFont("", "fonts/bitmapFontTest3.fnt", TextHAlignment::CENTER, s.width); + addChild(label1, 0, kTagBitmapAtlas1); + label1->setAnchorPoint(Point(0.5f, 0.5f)); + label1->setPosition(Point(s.width/2, delta)); + + // LabelTTF + Label* label2 = Label::createWithTTF("", "fonts/arial.ttf", 48, s.width, TextHAlignment::CENTER,GlyphCollection::NEHE); + addChild(label2, 0, kTagBitmapAtlas2); + label2->setAnchorPoint(Point(0.5f, 0.5f)); + label2->setPosition(Point(s.width/2, delta * 2)); + + + + schedule(schedule_selector(LabelFNTandTTFEmpty::updateStrings), 1.0f); + + setEmpty = false; +} + +void LabelFNTandTTFEmpty::updateStrings(float dt) +{ + auto label1 = static_cast( getChildByTag(kTagBitmapAtlas1) ); + auto label2 = static_cast( getChildByTag(kTagBitmapAtlas2) ); + + if( ! setEmpty ) + { + label1->setString("not empty"); + label2->setString("not empty"); + + setEmpty = true; + } + else + { + label1->setString(""); + label2->setString(""); + + setEmpty = false; + } +} + +std::string LabelFNTandTTFEmpty::title() +{ + return "New Label : .FNT file & .TTF file"; +} + +std::string LabelFNTandTTFEmpty::subtitle() +{ + return "2 empty labels: new Label + .FNT and new Label + .TTF"; +} + +LabelFNTRetina::LabelFNTRetina() +{ + Size s = Director::getInstance()->getWinSize(); + + // LabelBMFont + auto label1 = Label::createWithBMFont("TESTING RETINA DISPLAY", "fonts/konqa32.fnt"); + label1->setAnchorPoint(Point(0.5f, 0.5f)); + addChild(label1); + label1->setPosition(Point(s.width/2, s.height/2)); +} + +std::string LabelFNTRetina::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTRetina::subtitle() +{ + return "loading arista16 or arista16-hd"; +} + +LabelFNTGlyphDesigner::LabelFNTGlyphDesigner() +{ + Size s = Director::getInstance()->getWinSize(); + + auto layer = LayerColor::create(Color4B(128,128,128,255)); + addChild(layer, -10); + + // LabelBMFont + auto label1 = Label::createWithBMFont("Testing Glyph Designer", "fonts/futura-48.fnt"); + label1->setAnchorPoint(Point(0.5f, 0.5f)); + addChild(label1); + label1->setPosition(Point(s.width/2, s.height/2)); +} + +std::string LabelFNTGlyphDesigner::title() +{ + return "New Label + .FNT file"; +} + +std::string LabelFNTGlyphDesigner::subtitle() +{ + return "Testing Glyph Designer: you should see a font with shawdows and outline"; +} + +LabelTTFUnicodeChinese::LabelTTFUnicodeChinese() +{ + auto size = Director::getInstance()->getWinSize(); + // Adding "啊" letter at the end of string to make VS2012 happy, otherwise VS will generate errors + // like "Error 3 error C2146: syntax error : missing ')' before identifier 'label'"; + auto label = Label::createWithTTF("美好的一天啊", "fonts/wt021.ttf", 55, size.width, TextHAlignment::CENTER, GlyphCollection::CUSTOM, "美好的一天啊"); + label->setAnchorPoint(Point(0.5f, 0.5f)); + label->setPosition(Point(size.width / 2, size.height /2)); + this->addChild(label); +} + +std::string LabelTTFUnicodeChinese::title() +{ + return "New Label + .TTF file Chinese"; +} + +string LabelTTFUnicodeChinese::subtitle() +{ + return "Testing new Label + TTF with Chinese character"; +} + +LabelFNTUnicodeChinese::LabelFNTUnicodeChinese() +{ + auto size = Director::getInstance()->getWinSize(); + auto label = Label::createWithBMFont("中国", "fonts/bitmapFontChinese.fnt"); + label->setAnchorPoint(Point(0.5f, 0.5f)); + label->setPosition(Point(size.width / 2, size.height /2)); + this->addChild(label); +} + +string LabelFNTUnicodeChinese::title() +{ + return "New Label + .FNT file Chinese"; +} + +string LabelFNTUnicodeChinese::subtitle() +{ + return "Testing new Label + FNT with Chinese character"; +} + + +/// BitmapFontMultiLineAlignmentNew + +#define LongSentencesExample "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." +#define LineBreaksExample "Lorem ipsum dolor\nsit amet\nconsectetur adipisicing elit\nblah\nblah" +#define MixedExample "ABC\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt\nDEF" + +#define ArrowsMax 0.95 +#define ArrowsMin 0.7 + +#define LeftAlign 0 +#define CenterAlign 1 +#define RightAlign 2 + +#define LongSentences 0 +#define LineBreaks 1 +#define Mixed 2 + +static float alignmentItemPadding = 50; +static float menuItemPaddingCenter = 50; + +LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() +{ + this->setTouchEnabled(true); + + // ask director the the window size + Size size = Director::getInstance()->getWinSize(); + + // create and initialize a Label + this->_labelShouldRetain = Label::createWithBMFont(LongSentencesExample, "fonts/markerFelt.fnt", TextHAlignment::CENTER, size.width/1.5); + //this->_labelShouldRetain = Label::createWithBMFont(LongSentencesExample, "fonts/bitmapFontTest.fnt", TextHAlignment::CENTER, size.width/1.5); + this->_labelShouldRetain->setAnchorPoint(Point(0.5f, 0.5f)); + this->_labelShouldRetain->retain(); + + this->_arrowsBarShouldRetain = Sprite::create("Images/arrowsBar.png"); + this->_arrowsBarShouldRetain->retain(); + this->_arrowsShouldRetain = Sprite::create("Images/arrows.png"); + this->_arrowsShouldRetain->retain(); + + MenuItemFont::setFontSize(20); + auto longSentences = MenuItemFont::create("Long Flowing Sentences", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto lineBreaks = MenuItemFont::create("Short Sentences With Intentional Line Breaks", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto mixed = MenuItemFont::create("Long Sentences Mixed With Intentional Line Breaks", CC_CALLBACK_1(LabelFNTMultiLineAlignment::stringChanged, this)); + auto stringMenu = Menu::create(longSentences, lineBreaks, mixed, NULL); + stringMenu->alignItemsVertically(); + + longSentences->setColor(Color3B::RED); + _lastSentenceItem = longSentences; + longSentences->setTag(LongSentences); + lineBreaks->setTag(LineBreaks); + mixed->setTag(Mixed); + + MenuItemFont::setFontSize(30); + + auto left = MenuItemFont::create("Left", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); + auto center = MenuItemFont::create("Center", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); + auto right = MenuItemFont::create("Right", CC_CALLBACK_1(LabelFNTMultiLineAlignment::alignmentChanged, this)); + auto alignmentMenu = Menu::create(left, center, right, NULL); + alignmentMenu->alignItemsHorizontallyWithPadding(alignmentItemPadding); + + center->setColor(Color3B::RED); + _lastAlignmentItem = center; + left->setTag(LeftAlign); + center->setTag(CenterAlign); + right->setTag(RightAlign); + + // position the label on the center of the screen + this->_labelShouldRetain->setPosition(Point(size.width/2, size.height/2)); + + this->_arrowsBarShouldRetain->setVisible(false); + + float arrowsWidth = (ArrowsMax - ArrowsMin) * size.width; + this->_arrowsBarShouldRetain->setScaleX(arrowsWidth / this->_arrowsBarShouldRetain->getContentSize().width); + this->_arrowsBarShouldRetain->setPosition(Point(((ArrowsMax + ArrowsMin) / 2) * size.width, this->_labelShouldRetain->getPosition().y)); + + this->snapArrowsToEdge(); + + stringMenu->setPosition(Point(size.width/2, size.height - menuItemPaddingCenter)); + alignmentMenu->setPosition(Point(size.width/2, menuItemPaddingCenter+15)); + + this->addChild(this->_labelShouldRetain); + this->addChild(this->_arrowsBarShouldRetain); + this->addChild(this->_arrowsShouldRetain); + this->addChild(stringMenu); + this->addChild(alignmentMenu); +} + +LabelFNTMultiLineAlignment::~LabelFNTMultiLineAlignment() +{ + this->_labelShouldRetain->release(); + this->_arrowsBarShouldRetain->release(); + this->_arrowsShouldRetain->release(); +} + +std::string LabelFNTMultiLineAlignment::title() +{ + return ""; +} + +std::string LabelFNTMultiLineAlignment::subtitle() +{ + return ""; +} + +void LabelFNTMultiLineAlignment::stringChanged(cocos2d::Object *sender) +{ + MenuItemFont *item = (MenuItemFont*)sender; + item->setColor(Color3B::RED); + this->_lastAlignmentItem->setColor(Color3B::WHITE); + this->_lastAlignmentItem = item; + + switch(item->getTag()) + { + case LongSentences: + this->_labelShouldRetain->setString(LongSentencesExample); + break; + case LineBreaks: + this->_labelShouldRetain->setString(LineBreaksExample); + break; + case Mixed: + this->_labelShouldRetain->setString(MixedExample); + break; + + default: + break; + } + + this->snapArrowsToEdge(); +} + +void LabelFNTMultiLineAlignment::alignmentChanged(cocos2d::Object *sender) +{ + MenuItemFont *item = static_cast(sender); + item->setColor(Color3B::RED); + this->_lastAlignmentItem->setColor(Color3B::WHITE); + this->_lastAlignmentItem = item; + + switch(item->getTag()) + { + case LeftAlign: + this->_labelShouldRetain->setAlignment(TextHAlignment::LEFT); + break; + case CenterAlign: + this->_labelShouldRetain->setAlignment(TextHAlignment::CENTER); + break; + case RightAlign: + this->_labelShouldRetain->setAlignment(TextHAlignment::RIGHT); + break; + + default: + break; + } + + this->snapArrowsToEdge(); +} + +void LabelFNTMultiLineAlignment::ccTouchesBegan(cocos2d::Set *touches, cocos2d::Event *event) +{ + Touch *touch = (Touch *)touches->anyObject(); + Point location = touch->getLocationInView(); + + if (this->_arrowsShouldRetain->getBoundingBox().containsPoint(location)) + { + _drag = true; + this->_arrowsBarShouldRetain->setVisible(true); + } +} + +void LabelFNTMultiLineAlignment::ccTouchesEnded(cocos2d::Set *touches, cocos2d::Event *event) +{ + _drag = false; + this->snapArrowsToEdge(); + + this->_arrowsBarShouldRetain->setVisible(false); +} + +void LabelFNTMultiLineAlignment::ccTouchesMoved(cocos2d::Set *touches, cocos2d::Event *event) +{ + if (! _drag) + { + return; + } + + Touch *touch = (Touch *)touches->anyObject(); + Point location = touch->getLocationInView(); + + Size winSize = Director::getInstance()->getWinSize(); + + this->_arrowsShouldRetain->setPosition(Point(MAX(MIN(location.x, ArrowsMax*winSize.width), ArrowsMin*winSize.width), + this->_arrowsShouldRetain->getPosition().y)); + + float labelWidth = fabs(this->_arrowsShouldRetain->getPosition().x - this->_labelShouldRetain->getPosition().x) * 2; + + this->_labelShouldRetain->setWidth(labelWidth); +} + +void LabelFNTMultiLineAlignment::snapArrowsToEdge() +{ + this->_arrowsShouldRetain->setPosition(Point(this->_labelShouldRetain->getPosition().x + this->_labelShouldRetain->getContentSize().width/2, + this->_labelShouldRetain->getPosition().y)); +} + +/// BMFontUnicodeNew +LabelFNTUNICODELanguages::LabelFNTUNICODELanguages() +{ + Dictionary *strings = Dictionary::createWithContentsOfFile("fonts/strings.xml"); + + const char *chinese = static_cast(strings->objectForKey("chinese1"))->_string.c_str(); + const char *japanese = static_cast(strings->objectForKey("japanese"))->_string.c_str(); + const char *russian = static_cast(strings->objectForKey("russian"))->_string.c_str(); + const char *spanish = static_cast(strings->objectForKey("spanish"))->_string.c_str(); + + Size s = Director::getInstance()->getWinSize(); + + auto label1 = Label::createWithBMFont(spanish, "fonts/arial-unicode-26.fnt", TextHAlignment::CENTER, 200); + addChild(label1); + label1->setAnchorPoint(Point(0.5f, 0.5f)); + label1->setPosition(Point(s.width/2, s.height/5*3)); + + auto label2 = Label::createWithBMFont(chinese, "fonts/arial-unicode-26.fnt"); + addChild(label2); + label2->setAnchorPoint(Point(0.5f, 0.5f)); + label2->setPosition(Point(s.width/2, s.height/5*2.5)); + + auto label3 = Label::createWithBMFont(russian, "fonts/arial-26-en-ru.fnt"); + addChild(label3); + label3->setAnchorPoint(Point(0.5f, 0.5f)); + label3->setPosition(Point(s.width/2, s.height/5*2)); + + auto label4 = Label::createWithBMFont(japanese, "fonts/arial-unicode-26.fnt"); + addChild(label4); + label4->setAnchorPoint(Point(0.5f, 0.5f)); + label4->setPosition(Point(s.width/2, s.height/5*1.5)); +} + +std::string LabelFNTUNICODELanguages::title() +{ + return "New Label + .FNT + UNICODE"; +} + +std::string LabelFNTUNICODELanguages::subtitle() +{ + return "You should see 4 differnt labels:\nIn Spanish, Chinese, Russian and Korean"; +} + +LabelFNTBounds::LabelFNTBounds() +{ + Size s = Director::getInstance()->getWinSize(); + + LayerColor *layer = LayerColor::create(Color4B(128,128,128,255)); + addChild(layer, -10); + + // LabelBMFont + label1 = Label::createWithBMFont("Testing Glyph Designer", "fonts/boundsTestFont.fnt", TextHAlignment::CENTER, s.width); + label1->setAnchorPoint(Point(0.5f, 0.5f)); + addChild(label1); + label1->setPosition(Point(s.width/2, s.height/2)); +} + +string LabelFNTBounds::title() +{ + return "New Label + .FNT + Bounds"; +} + +string LabelFNTBounds::subtitle() +{ + return "You should see string enclosed by a box"; +} + +void LabelFNTBounds::draw() +{ + Size labelSize = label1->getContentSize(); + Size origin = Director::getInstance()->getWinSize(); + + origin.width = origin.width / 2 - (labelSize.width / 2); + origin.height = origin.height / 2 - (labelSize.height / 2); + + Point vertices[4]= + { + Point(origin.width, origin.height), + Point(labelSize.width + origin.width, origin.height), + Point(labelSize.width + origin.width, labelSize.height + origin.height), + Point(origin.width, labelSize.height + origin.height) + }; + DrawPrimitives::drawPoly(vertices, 4, true); +} + +LabelTTFLongLineWrapping::LabelTTFLongLineWrapping() +{ + Size size = Director::getInstance()->getWinSize(); + + // Long sentence + auto label1 = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 28, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + label1->setPosition( Point(size.width/2, size.height/2) ); + label1->setAnchorPoint(Point(0.5, 1.0)); + addChild(label1); +} + +std::string LabelTTFLongLineWrapping::title() +{ + return "New Label + .TTF"; +} + +std::string LabelTTFLongLineWrapping::subtitle() +{ + return "Uses the new Label with TTF. Testing auto-wrapping"; +} + +LabelTTFColor::LabelTTFColor() +{ + Size size = Director::getInstance()->getWinSize(); + + // Green + auto label1 = Label::createWithTTF("Green", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + label1->setPosition( Point(size.width/2, size.height/5 * 1.5) ); + label1->setColor( Color3B::GREEN ); + label1->setAnchorPoint(Point(0.5, 0.5)); + addChild(label1); + + // Red + auto label2 = Label::createWithTTF("Red", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + label2->setPosition( Point(size.width/2, size.height/5 * 2.0) ); + label2->setColor( Color3B::RED ); + label2->setAnchorPoint(Point(0.5, 0.5)); + addChild(label2); + + // Blue + auto label3 = Label::createWithTTF("Blue", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + label3->setPosition( Point(size.width/2, size.height/5 * 2.5) ); + label3->setColor( Color3B::BLUE ); + label3->setAnchorPoint(Point(0.5, 0.5)); + addChild(label3); +} + +std::string LabelTTFColor::title() +{ + return "New Label + .TTF"; +} + +std::string LabelTTFColor::subtitle() +{ + return "Uses the new Label with TTF. Testing Color"; +} + +LabelTTFDynamicAlignment::LabelTTFDynamicAlignment() +{ + Size size = Director::getInstance()->getWinSize(); + + _label = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + _label->setPosition( Point(size.width/2, size.height/2) ); + _label->setAnchorPoint(Point(0.5, 0.5)); + + + + Menu *menu = Menu::create( + MenuItemFont::create("Left", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentLeft, this)), + MenuItemFont::create("Center", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentCenter, this)), + MenuItemFont::create("Right", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentRight, this)), + NULL); + + menu->alignItemsVerticallyWithPadding(4); + menu->setPosition(Point(50, size.height / 4 )); + + addChild(_label); + this->addChild(menu); +} + +void LabelTTFDynamicAlignment::updateAlignment() +{ + if (_label) + { + _label->setAlignment(_horizAlign); + } +} + +void LabelTTFDynamicAlignment::setAlignmentLeft(Object* sender) +{ + _horizAlign = TextHAlignment::LEFT; + this->updateAlignment(); +} + +void LabelTTFDynamicAlignment::setAlignmentCenter(Object* sender) +{ + _horizAlign = TextHAlignment::CENTER; + this->updateAlignment(); +} + +void LabelTTFDynamicAlignment::setAlignmentRight(Object* sender) +{ + _horizAlign = TextHAlignment::RIGHT; + this->updateAlignment(); +} + +std::string LabelTTFDynamicAlignment::title() +{ + return "New Label + .TTF"; +} + +std::string LabelTTFDynamicAlignment::subtitle() +{ + return "Uses the new Label with TTF. Testing alignment"; +} + +// +// NewLabelTTF unicode test +// +LabelTTFUnicodeNew::LabelTTFUnicodeNew() +{ + Dictionary *strings = Dictionary::createWithContentsOfFile("fonts/strings.xml"); + const char *chinese = static_cast(strings->objectForKey("chinese1"))->_string.c_str(); + + //const char *russian = static_cast(strings->objectForKey("russian"))->_string.c_str(); + //const char *spanish = static_cast(strings->objectForKey("spanish"))->_string.c_str(); + //const char *japanese = static_cast(strings->objectForKey("japanese"))->_string.c_str(); + + Size size = Director::getInstance()->getWinSize(); + + float vStep = size.height/9; + float vSize = size.height; + + + // Spanish + auto label1 = Label::createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::ASCII); + label1->setPosition( Point(size.width/2, vSize - (vStep * 4.5)) ); + label1->setAnchorPoint(Point(0.5, 0.5)); + addChild(label1); + + // German + auto label2 = Label::createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::ASCII); + label2->setPosition( Point(size.width/2, vSize - (vStep * 5.5)) ); + label2->setAnchorPoint(Point(0.5, 0.5)); + addChild(label2); + + // chinese + auto label3 = Label::createWithTTF(chinese, "fonts/wt021.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::CUSTOM, chinese); + label3->setPosition( Point(size.width/2, vSize - (vStep * 6.5)) ); + label3->setAnchorPoint(Point(0.5, 0.5)); + addChild(label3); +} + +std::string LabelTTFUnicodeNew::title() +{ + return "New Label + TTF unicode"; +} + +std::string LabelTTFUnicodeNew::subtitle() +{ + return "Uses the new Label with TTF. Testing unicode"; +} + +LabelTTFFontsTestNew::LabelTTFFontsTestNew() +{ + const char *ttfpaths[] = { + "fonts/A Damn Mess.ttf", + "fonts/Abberancy.ttf", + "fonts/Abduction.ttf", + "fonts/American Typewriter.ttf", + "fonts/Paint Boy.ttf", + "fonts/Schwarzwald Regular.ttf", + "fonts/Scissor Cuts.ttf", + }; +#define arraysize(ar) (sizeof(ar) / sizeof(ar[0])) + + Size size = Director::getInstance()->getWinSize(); + + for(int i=0;i < arraysize(ttfpaths); ++i) { + auto label = Label::createWithTTF( ttfpaths[i], ttfpaths[i], 40, 0, TextHAlignment::CENTER, GlyphCollection::NEHE); + if( label ) { + + label->setPosition( Point(size.width/2, ((size.height * 0.6)/arraysize(ttfpaths) * i) + (size.height/5))); + addChild(label); + + label->setAnchorPoint(Point(0.5, 0.5)); + } else { + log("ERROR: Cannot load: %s", ttfpaths[i]); + } + } +} + +std::string LabelTTFFontsTestNew::title() +{ + return "New Label + TTF"; +} + +std::string LabelTTFFontsTestNew::subtitle() +{ + return ""; +} + +LabelBMFontTestNew::LabelBMFontTestNew() +{ + Size size = Director::getInstance()->getWinSize(); + + auto label1 = Label::createWithBMFont("Hello World, this is testing the new Label using fnt file", "fonts/bitmapFontTest2.fnt", TextHAlignment::CENTER, size.width); + label1->setPosition( Point(size.width/2, size.height/2) ); + label1->setAnchorPoint(Point(0.5, 0.5)); + addChild(label1); +} + +std::string LabelBMFontTestNew::title() +{ + return "New Label + FNT"; +} + +std::string LabelBMFontTestNew::subtitle() +{ + return "Uses the new Label with .FNT file"; +} + diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h new file mode 100644 index 0000000000..036d04830e --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h @@ -0,0 +1,282 @@ +#ifndef _ATLAS_TEST_NEW_H_ +#define _ATLAS_TEST_NEW_H_ + +#include "../testBasic.h" +#include "../BaseTest.h" + + +class AtlasDemoNew : public BaseTest +{ +protected: + +public: + AtlasDemoNew(void); + ~AtlasDemoNew(void); + + virtual std::string title(); + virtual std::string subtitle(); + virtual void onEnter(); + + void restartCallback(Object* sender); + void nextCallback(Object* sender); + void backCallback(Object* sender); +}; + +class LabelTTFAlignmentNew : public AtlasDemoNew +{ +public: + LabelTTFAlignmentNew(); + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTColorAndOpacity : public AtlasDemoNew +{ + float _time; +public: + LabelFNTColorAndOpacity(); + + virtual void step(float dt); + + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTSpriteActions : public AtlasDemoNew +{ + float _time; +public: + LabelFNTSpriteActions(); + virtual void step(float dt); + virtual void draw(); + + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTPadding : public AtlasDemoNew +{ +public: + LabelFNTPadding(); + virtual std::string title(); + virtual std::string subtitle(); +}; + + +class LabelFNTOffset : public AtlasDemoNew +{ +public: + LabelFNTOffset(); + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTColor : public AtlasDemoNew +{ +public: + LabelFNTColor(); + virtual std::string title(); + + virtual std::string subtitle(); +}; + +class LabelFNTHundredLabels : public AtlasDemoNew +{ +public: + LabelFNTHundredLabels(); + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTMultiLine : public AtlasDemoNew +{ +public: + LabelFNTMultiLine(); + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTandTTFEmpty : public AtlasDemoNew +{ +public: + LabelFNTandTTFEmpty(); + void updateStrings(float dt); + virtual std::string title(); + virtual std::string subtitle(); + +private: + bool setEmpty; +}; + +class LabelFNTRetina : public AtlasDemoNew +{ +public: + LabelFNTRetina(); + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTGlyphDesigner : public AtlasDemoNew +{ +public: + LabelFNTGlyphDesigner(); + virtual std::string title(); + virtual std::string subtitle(); +}; + +class AtlasTestSceneNew : public TestScene +{ +public: + virtual void runThisTest(); +}; + +class LabelTTFUnicodeChinese : public AtlasDemoNew +{ +public: + LabelTTFUnicodeChinese(); + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTUnicodeChinese : public AtlasDemoNew +{ +public: + LabelFNTUnicodeChinese(); + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTMultiLineAlignment : public AtlasDemoNew +{ +public: + LabelFNTMultiLineAlignment(); + ~LabelFNTMultiLineAlignment(); + void snapArrowsToEdge(); + virtual std::string title(); + virtual std::string subtitle(); + void stringChanged(Object *sender); + void alignmentChanged(Object *sender); + virtual void ccTouchesBegan(Set *touches, Event *event); + virtual void ccTouchesEnded(Set *touches, Event *event); + virtual void ccTouchesMoved(Set *touches, Event *event); + +public: + Label *_labelShouldRetain; + Sprite *_arrowsBarShouldRetain; + Sprite *_arrowsShouldRetain; + MenuItemFont *_lastSentenceItem, *_lastAlignmentItem; + bool _drag; +}; + +class LabelFNTUNICODELanguages : public AtlasDemoNew +{ +public: + LabelFNTUNICODELanguages(); + + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelFNTBounds : public AtlasDemoNew +{ +public: + LabelFNTBounds(); + + virtual void draw(); + virtual std::string title(); + virtual std::string subtitle(); +private: + Label *label1; +}; + +class LabelTTFLongLineWrapping : public AtlasDemoNew +{ +public: + + LabelTTFLongLineWrapping(); + + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelTTFColor : public AtlasDemoNew +{ +public: + + LabelTTFColor(); + + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelTTFUnicodeNew : public AtlasDemoNew +{ +public: + + LabelTTFUnicodeNew(); + + virtual std::string title(); + virtual std::string subtitle(); +}; + +class LabelTTFDynamicAlignment : public AtlasDemoNew +{ +public: + + LabelTTFDynamicAlignment(); + virtual std::string title(); + virtual std::string subtitle(); + +private: + + void setAlignmentLeft(Object* sender); + void setAlignmentCenter(Object* sender); + void setAlignmentRight(Object* sender); + void updateAlignment(); + + Label * _label; + TextHAlignment _horizAlign; + +}; + + +class LabelTTFFontsTestNew : public AtlasDemoNew +{ +public: + + LabelTTFFontsTestNew(); + + virtual std::string title(); + virtual std::string subtitle(); +}; + + +class LabelBMFontTestNew : public AtlasDemoNew +{ +public: + + LabelBMFontTestNew(); + + virtual std::string title(); + virtual std::string subtitle(); + +private: +}; + +class LabelFontDefTestNew : public AtlasDemoNew +{ +public: + + LabelFontDefTestNew(); + + virtual std::string title(); + virtual std::string subtitle(); + +private: +}; + + + +// we don't support linebreak mode + +#endif diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index 7846a7332d..a0f777a0fc 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -56,6 +56,7 @@ struct { { "KeypadTest", []() { return new KeypadTestScene(); } }, #endif { "LabelTest", [](){return new AtlasTestScene(); } }, + { "LabelTestNew", [](){return new AtlasTestSceneNew(); } }, { "LayerTest", [](){return new LayerTestScene();} }, { "MenuTest", [](){return new MenuTestScene();} }, { "MotionStreakTest", [](){return new MotionStreakTestScene();} }, diff --git a/samples/Cpp/TestCpp/Classes/tests.h b/samples/Cpp/TestCpp/Classes/tests.h index c9c119f2cd..ea26d0223c 100644 --- a/samples/Cpp/TestCpp/Classes/tests.h +++ b/samples/Cpp/TestCpp/Classes/tests.h @@ -20,6 +20,7 @@ #include "TileMapTest/TileMapTest.h" #include "IntervalTest/IntervalTest.h" #include "LabelTest/LabelTest.h" +#include "LabelTest/LabelTestNew.h" #include "TextInputTest/TextInputTest.h" #include "SpriteTest/SpriteTest.h" #include "SchedulerTest/SchedulerTest.h" diff --git a/samples/Cpp/TestCpp/proj.linux/Makefile b/samples/Cpp/TestCpp/proj.linux/Makefile index 38e1ec789e..5104b1ace8 100644 --- a/samples/Cpp/TestCpp/proj.linux/Makefile +++ b/samples/Cpp/TestCpp/proj.linux/Makefile @@ -65,6 +65,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/KeyboardTest/KeyboardTest.cpp \ ../Classes/KeypadTest/KeypadTest.cpp \ ../Classes/LabelTest/LabelTest.cpp \ + ../Classes/LabelTest/LabelTestNew.cpp \ ../Classes/LayerTest/LayerTest.cpp \ ../Classes/MenuTest/MenuTest.cpp \ ../Classes/MotionStreakTest/MotionStreakTest.cpp \ diff --git a/samples/Cpp/TestCpp/proj.nacl/Makefile b/samples/Cpp/TestCpp/proj.nacl/Makefile index 6dac4828f1..5b08010027 100644 --- a/samples/Cpp/TestCpp/proj.nacl/Makefile +++ b/samples/Cpp/TestCpp/proj.nacl/Makefile @@ -68,6 +68,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/IntervalTest/IntervalTest.cpp \ ../Classes/KeypadTest/KeypadTest.cpp \ ../Classes/LabelTest/LabelTest.cpp \ + ../Classes/LabelTest/LabelTestNew.cpp \ ../Classes/LayerTest/LayerTest.cpp \ ../Classes/MenuTest/MenuTest.cpp \ ../Classes/MotionStreakTest/MotionStreakTest.cpp \ diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index d1d7c02be5..f85811054a 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -156,6 +156,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O + @@ -265,6 +266,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O + diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters index c5bdcb4e17..a3d6cbc6c9 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters @@ -552,6 +552,9 @@ Classes\ExtensionsTest\NetworkTest + + Classes\LabelTest + @@ -1049,5 +1052,8 @@ Classes\ExtensionsTest\NetworkTest + + Classes\LabelTest + \ No newline at end of file diff --git a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id index 543b758f11..0077b8abd6 100644 --- a/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -daaf13ab82feffbd1c8e201d76cb83ed8f2dabca \ No newline at end of file +ca78185e84f3f44b992ff541f2b86e16ea08e830 \ No newline at end of file