Merge branch 'develop' of https://github.com/cocos2d/cocos2d-x into developBugFix

This commit is contained in:
samuele3hu 2014-01-22 15:44:33 +08:00
commit e848167b25
55 changed files with 1508 additions and 2145 deletions

View File

@ -10,11 +10,14 @@ cocos2d-x-3.0beta2 ?.? ?
[NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10%
[NEW] LuaBindings: Bindings-generator supports to bind namespace for lua.
[FIX] Bindings-generator supports Windows again and remove dependency of LLVM since we only need binary(libclang.so/dll).
[FIX] Removes unused files for MAC platform after using glfw3 to create opengl context.
[FIX] Wrong arithmetic of child's position in ParallaxNode::addChild()
[FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work.
[FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile.
[FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong.
[FIX] Label: Crash when using unknown characters.
[FIX] Label: Missing line breaks and wrong alignment.
[FIX] Console: log(format, va_args) is private to prevent possible resolution errors
[FIX] Configuration: dumpInfo() -> getInfo()
[FIX] ControlSlider doesn't support to set selected thumb sprite.

View File

@ -1 +1 @@
df164052374ec5c6ec61d99f36a20cc99638b631
db31f01b55bf1ae19e57e71bae6f58a037bfe5b9

View File

@ -1 +1 @@
986d41d9721f8079f005999caa9fb0053ea11321
ff284ac388641341140f8b6817f2cd26e4f07cf2

View File

@ -234,7 +234,7 @@ void EventDispatcher::visitTarget(Node* node, bool isRootNode)
if (isRootNode)
{
std::vector<int> globalZOrders;
std::vector<float> globalZOrders;
globalZOrders.reserve(_globalZOrderNodeMap.size());
for (const auto& e : _globalZOrderNodeMap)
@ -242,7 +242,7 @@ void EventDispatcher::visitTarget(Node* node, bool isRootNode)
globalZOrders.push_back(e.first);
}
std::sort(globalZOrders.begin(), globalZOrders.end(), [](const int a, const int b){
std::sort(globalZOrders.begin(), globalZOrders.end(), [](const float a, const float b){
return a < b;
});
@ -1166,7 +1166,7 @@ bool EventDispatcher::isEnabled() const
void EventDispatcher::setDirtyForNode(Node* node)
{
// Mark the node dirty only when there was an eventlistener associates with it.
// Mark the node dirty only when there is an eventlistener associated with it.
if (_nodeListenersMap.find(node) != _nodeListenersMap.end())
{
_dirtyNodes.insert(node);

View File

@ -231,7 +231,7 @@ protected:
std::unordered_map<Node*, int> _nodePriorityMap;
/** key: Global Z Order, value: Sorted Nodes */
std::unordered_map<int, std::vector<Node*>> _globalZOrderNodeMap;
std::unordered_map<float, std::vector<Node*>> _globalZOrderNodeMap;
/** The listeners to be added after dispatching event */
std::vector<EventListener*> _toAddedListeners;

View File

@ -41,7 +41,7 @@ class CC_DLL Font : public Object
public:
virtual FontAtlas *createFontAtlas() = 0;
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0;
virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const = 0;
virtual const char* getCurrentGlyphCollection() const;
virtual int getLetterPadding() const { return 0; }

View File

@ -133,7 +133,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tempDef.anchorX = 0.0f;
tempDef.anchorY = 1.0f;
if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect))
if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect,tempDef.xAdvance))
{
tempDef.validDefinition = false;
tempDef.letteCharUTF16 = utf16String[i];
@ -145,6 +145,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tempDef.offsetX = 0;
tempDef.offsetY = 0;
tempDef.textureID = 0;
tempDef.xAdvance = 0;
}
else
{
@ -155,7 +156,6 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tempDef.offsetX = tempRect.origin.x;
tempDef.offsetY = tempRect.origin.y;
tempDef.commonLineHeight = _currentPageLineHeight;
}
fontDefs[utf16String[i]] = tempDef;
}

View File

@ -49,6 +49,7 @@ struct FontLetterDefinition
float anchorX;
float anchorY;
bool validDefinition;
int xAdvance;
};
class CC_DLL FontAtlas : public Object

View File

@ -99,7 +99,7 @@ FontCharMap::~FontCharMap()
}
Size * FontCharMap::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const
int * FontCharMap::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const
{
if (!text)
return 0;
@ -109,14 +109,13 @@ Size * FontCharMap::getAdvancesForTextUTF16(unsigned short *text, int &outNumLet
if (!outNumLetters)
return 0;
Size *sizes = new Size[outNumLetters];
int *sizes = new int[outNumLetters];
if (!sizes)
return 0;
int advance = _itemWidth * CC_CONTENT_SCALE_FACTOR();
for (int c = 0; c < outNumLetters; ++c)
{
sizes[c].width = advance;
sizes[c] = 0;
}
return sizes;
@ -149,10 +148,9 @@ FontAtlas * FontCharMap::createFontAtlas()
tempDefinition.validDefinition = true;
tempDefinition.width = _itemWidth;
tempDefinition.height = _itemHeight;
tempDefinition.xAdvance = _itemWidth * CC_CONTENT_SCALE_FACTOR();
int charId = _mapStartChar;
float itemWidthInPixels = _itemWidth * CC_CONTENT_SCALE_FACTOR();
float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR();
for (int row = 0; row < itemsPerColumn; ++row)
{
for (int col = 0; col < itemsPerRow; ++col)

View File

@ -37,7 +37,7 @@ public:
static FontCharMap * create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontCharMap * create(const std::string& plistFile);
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual Rect getRectForChar(unsigned short theChar) const override;
virtual FontAtlas *createFontAtlas() override;

View File

@ -62,7 +62,7 @@ FontFNT::~FontFNT()
}
Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const
int * FontFNT::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const
{
if (!text)
return 0;
@ -72,39 +72,21 @@ Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters
if (!outNumLetters)
return 0;
Size *sizes = new Size[outNumLetters];
int *sizes = new int[outNumLetters];
if (!sizes)
return 0;
for (int c = 0; c < outNumLetters; ++c)
{
int advance = 0;
int kerning = 0;
advance = getAdvanceForChar(text[c]);
if (c < (outNumLetters-1))
kerning = getHorizontalKerningForChars(text[c], text[c+1]);
sizes[c].width = (advance + kerning);
sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]);
else
sizes[c] = 0;
}
return sizes;
}
int FontFNT::getAdvanceForChar(unsigned short theChar) const
{
tFontDefHashElement *element = nullptr;
// unichar is a short, and an int is needed on HASH_FIND_INT
unsigned int key = theChar;
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
if (! element)
return -1;
return element->fontDef.xAdvance;
}
int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const
{
int ret = 0;
@ -194,9 +176,8 @@ FontAtlas * FontFNT::createFontAtlas()
//carloX: only one texture supported FOR NOW
tempDefinition.textureID = 0;
tempDefinition.anchorX = 0.5f;
tempDefinition.anchorY = 0.5f;
tempDefinition.validDefinition = true;
tempDefinition.xAdvance = fontDef.xAdvance;
// add the new definition
tempAtlas->addLetterDefinition(tempDefinition);
}

View File

@ -39,7 +39,7 @@ public:
static FontFNT * create(const std::string& fntFilePath);
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual Rect getRectForChar(unsigned short theChar) const override;
virtual FontAtlas *createFontAtlas() override;
@ -55,7 +55,6 @@ protected:
private:
int getAdvanceForChar(unsigned short theChar) const;
int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const;
Rect getRectForCharInternal(unsigned short theChar) const;

View File

@ -143,7 +143,7 @@ FontAtlas * FontFreeType::createFontAtlas()
return atlas;
}
bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const
bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect, int &xAdvance) const
{
if (!_fontRef)
return false;
@ -164,10 +164,12 @@ bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const
outRect.size.width = (_fontRef->glyph->metrics.width >> 6);
outRect.size.height = (_fontRef->glyph->metrics.height >> 6);
xAdvance = (static_cast<int>(_fontRef->glyph->metrics.horiAdvance >> 6));
return true;
}
Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const
int * FontFreeType::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const
{
if (!text)
return 0;
@ -177,64 +179,21 @@ Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLe
if (!outNumLetters)
return 0;
Size *sizes = new Size[outNumLetters];
int *sizes = new int[outNumLetters];
if (!sizes)
return 0;
for (int c = 0; c < outNumLetters; ++c)
{
int advance = 0;
int kerning = 0;
advance = getAdvanceForChar(text[c]);
if (c < (outNumLetters-1))
kerning = getHorizontalKerningForChars(text[c], text[c+1]);
sizes[c].width = (advance + kerning);
sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]);
else
sizes[c] = 0;
}
return sizes;
}
int FontFreeType::getAdvanceForChar(unsigned short theChar) const
{
if (!_fontRef)
return 0;
// get the ID to the char we need
int glyph_index = FT_Get_Char_Index(_fontRef, theChar);
if (!glyph_index)
return 0;
// load glyph infos
if (FT_Load_Glyph(_fontRef, glyph_index, FT_LOAD_DEFAULT))
return 0;
// get to the advance for this glyph
return (static_cast<int>(_fontRef->glyph->metrics.horiAdvance >> 6));
}
int FontFreeType::getBearingXForChar(unsigned short theChar) const
{
if (!_fontRef)
return 0;
// get the ID to the char we need
int glyphIndex = FT_Get_Char_Index(_fontRef, theChar);
if (!glyphIndex)
return 0;
// load glyph infos
if (FT_Load_Glyph(_fontRef, glyphIndex, FT_LOAD_DEFAULT))
return 0;
return (static_cast<int>(_fontRef->glyph->metrics.horiBearingX >>6));
}
int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const
{
if (!_fontRef)

View File

@ -50,13 +50,13 @@ public:
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
virtual FontAtlas * createFontAtlas() override;
virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual int * getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override;
unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const override;
virtual int getFontMaxHeight() const override;
virtual int getLetterPadding() const override;
bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const;
bool getBBOXFotChar(unsigned short theChar, Rect &outRect,int &xAdvance) const;
protected:
@ -69,8 +69,6 @@ private:
bool initFreeType();
FT_Library getFTLibrary();
int getAdvanceForChar(unsigned short theChar) const;
int getBearingXForChar(unsigned short theChar) const;
int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const;
static FT_Library _FTlibrary;

View File

@ -193,7 +193,7 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,b
, _alignment(alignment)
, _currentUTF16String(nullptr)
, _originalUTF16String(nullptr)
, _advances(nullptr)
, _horizontalKernings(nullptr)
, _fontAtlas(atlas)
, _isOpacityModifyRGB(true)
, _useDistanceField(useDistanceField)
@ -208,7 +208,7 @@ Label::~Label()
{
delete [] _currentUTF16String;
delete [] _originalUTF16String;
delete [] _advances;
delete [] _horizontalKernings;
if (_fontAtlas)
FontAtlasCache::releaseFontAtlas(_fontAtlas);
@ -226,6 +226,7 @@ bool Label::init()
_reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0));
_reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB);
_reusedLetter->retain();
_reusedLetter->setAnchorPoint(Point::ANCHOR_TOP_LEFT);
}
ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30);
}
@ -474,18 +475,18 @@ void Label::alignText()
}
}
bool Label::computeAdvancesForString(unsigned short int *stringToRender)
bool Label::computeHorizontalKernings(unsigned short int *stringToRender)
{
if (_advances)
if (_horizontalKernings)
{
delete [] _advances;
_advances = 0;
delete [] _horizontalKernings;
_horizontalKernings = 0;
}
int letterCount = 0;
_advances = _fontAtlas->getFont()->getAdvancesForTextUTF16(stringToRender, letterCount);
_horizontalKernings = _fontAtlas->getFont()->getHorizontalKerningForTextUTF16(stringToRender, letterCount);
if(!_advances)
if(!_horizontalKernings)
return false;
else
return true;
@ -519,7 +520,7 @@ bool Label::setCurrentString(unsigned short *stringToSet)
//
_currentUTF16String = stringToSet;
// compute the advances
return computeAdvancesForString(stringToSet);
return computeHorizontalKernings(stringToSet);
}
void Label::resetCurrentString()
@ -558,10 +559,8 @@ Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const F
SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect);
if (frame)
{
spriteToUpdate->setBatchNode(this);
spriteToUpdate->setTexture(theTexture);
spriteToUpdate->setSpriteFrame(frame);
spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
spriteToUpdate->setBatchNode(this);
spriteToUpdate->setSpriteFrame(frame);
}
return spriteToUpdate;
@ -692,8 +691,8 @@ Sprite * Label::getLetter(int ID)
sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect);
sp->setBatchNode(this);
sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY));
sp->setPosition(_lettersInfo[ID].position);
sp->setAnchorPoint(Point::ANCHOR_MIDDLE);
sp->setPosition(Point(_lettersInfo[ID].position.x+uvRect.size.width/2,_lettersInfo[ID].position.y-uvRect.size.height/2));
sp->setOpacity(_realOpacity);
this->addSpriteWithoutQuad(sp, ID, ID);
@ -706,12 +705,12 @@ Sprite * Label::getLetter(int ID)
float Label::getLetterPosXLeft( int index ) const
{
return _lettersInfo[index].position.x * _scaleX - (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX);
return _lettersInfo[index].position.x * _scaleX;
}
float Label::getLetterPosXRight( int index ) const
{
return _lettersInfo[index].position.x * _scaleX + (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX);
return (_lettersInfo[index].position.x + _lettersInfo[index].contentSize.width) * _scaleX;
}
int Label::getCommonLineHeight() const
@ -719,9 +718,16 @@ int Label::getCommonLineHeight() const
return _commonLineHeight;
}
int Label::getKerningForCharsPair(unsigned short first, unsigned short second) const
int Label::getKerningInString(int hintPositionInString) const
{
return 0;
if (_horizontalKernings)
{
return (_horizontalKernings[hintPositionInString]);
}
else
{
return -1;
}
}
int Label::getXOffsetForChar(unsigned short c) const
@ -746,7 +752,7 @@ int Label::getYOffsetForChar(unsigned short c) const
int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const
{
if (_advances)
if (_horizontalKernings)
{
// not that advance contains the X offset already
FontLetterDefinition tempDefinition;
@ -754,7 +760,7 @@ int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const
if (!validDefinition)
return -1;
return (_advances[hintPositionInString].width);
return tempDefinition.xAdvance;
}
else
{

View File

@ -123,7 +123,7 @@ public:
// font related stuff
virtual int getCommonLineHeight() const override;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override;
virtual int getKerningInString(int hintPositionInString) const override;
virtual int getXOffsetForChar(unsigned short c) const override;
virtual int getYOffsetForChar(unsigned short c) const override;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override;
@ -170,7 +170,7 @@ private:
void alignText();
bool computeAdvancesForString(unsigned short int *stringToRender);
bool computeHorizontalKernings(unsigned short int *stringToRender);
bool setCurrentString(unsigned short *stringToSet);
bool setOriginalString(unsigned short *stringToSet);
void resetCurrentString();
@ -189,7 +189,7 @@ private:
TextHAlignment _alignment;
unsigned short int * _currentUTF16String;
unsigned short int * _originalUTF16String;
Size * _advances;
int * _horizontalKernings;
FontAtlas * _fontAtlas;
bool _isOpacityModifyRGB;

View File

@ -61,7 +61,7 @@ public:
// font related stuff
virtual int getCommonLineHeight() const = 0;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const = 0;
virtual int getKerningInString(int hintPositionInString) const = 0;
virtual int getXOffsetForChar(unsigned short c) const = 0;
virtual int getYOffsetForChar(unsigned short c) const = 0;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const = 0;

View File

@ -35,70 +35,39 @@ NS_CC_BEGIN
bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
{
// to do if (m_fWidth > 0)
if (theLabel->getMaxLineWidth())
{
// Step 1: Make multiline
vector<unsigned short> strWhole = cc_utf16_vec_from_utf16_str(theLabel->getUTF8String());
size_t stringLength = strWhole.size();
vector<unsigned short> multiline_string;
multiline_string.reserve( stringLength );
vector<unsigned short> last_word;
last_word.reserve( stringLength );
unsigned int line = 1, i = 0;
bool isStartOfLine = false, isStartOfWord = false;
float startOfLine = -1, startOfWord = -1;
int skip = 0;
int strLen = theLabel->getStringLenght();
std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo();
int tIndex = 0;
int strLen = theLabel->getStringLenght();
auto strWhole = theLabel->getUTF8String();
for (int j = 0; j+skip < strLen; j++)
{
LetterInfo* info = &leterInfo->at(j+skip);
vector<unsigned short> multiline_string;
multiline_string.reserve( strLen );
unsigned int justSkipped = 0;
while (info->def.validDefinition == false)
{
justSkipped++;
tIndex = j+skip+justSkipped;
if(tIndex < strLen)
info = &leterInfo->at( tIndex );
else
break;
}
skip += justSkipped;
tIndex = j + skip;
if (tIndex >= stringLength)
break;
unsigned short character = strWhole[tIndex];
if (!isStartOfWord)
{
startOfWord = theLabel->getLetterPosXLeft( tIndex );
isStartOfWord = true;
}
if (!isStartOfLine)
{
startOfLine = startOfWord;
isStartOfLine = true;
}
// Newline.
if (character == '\n')
vector<unsigned short> last_word;
last_word.reserve( strLen );
unsigned int line = 1;
bool isStartOfLine = false, isStartOfWord = false;
float startOfLine = -1, startOfWord = -1;
int skip = 0;
std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo();
int tIndex = 0;
for (int j = 0; j+skip < strLen; j++)
{
LetterInfo* info = &leterInfo->at(j+skip);
unsigned int justSkipped = 0;
while (info->def.validDefinition == false)
{
justSkipped++;
tIndex = j+skip+justSkipped;
if (strWhole[tIndex-1] == '\n')
{
cc_utf8_trim_ws(&last_word);
last_word.push_back('\n');
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
@ -106,119 +75,102 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
isStartOfLine = false;
startOfWord = -1;
startOfLine = -1;
i += justSkipped;
++line;
if (i >= stringLength)
break;
character = strWhole[i];
if (!startOfWord)
{
startOfWord = theLabel->getLetterPosXLeft( tIndex );
isStartOfWord = true;
}
if (!startOfLine)
{
startOfLine = startOfWord;
isStartOfLine = true;
}
}
// Whitespace.
if (isspace_unicode(character))
if(tIndex < strLen)
{
info = &leterInfo->at( tIndex );
}
else
break;
}
skip += justSkipped;
tIndex = j + skip;
if (tIndex >= strLen)
break;
unsigned short character = strWhole[tIndex];
if (!isStartOfWord)
{
startOfWord = theLabel->getLetterPosXLeft( tIndex );
isStartOfWord = true;
}
if (!isStartOfLine)
{
startOfLine = startOfWord;
isStartOfLine = true;
}
// Whitespace.
if (isspace_unicode(character))
{
last_word.push_back(character);
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
isStartOfWord = false;
startOfWord = -1;
continue;
}
// Out of bounds.
if (theLabel->getLetterPosXRight( tIndex ) - startOfLine > theLabel->getMaxLineWidth())
{
if (!theLabel->breakLineWithoutSpace())
{
last_word.push_back(character);
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
isStartOfWord = false;
startOfWord = -1;
++i;
continue;
}
// Out of bounds.
if (theLabel->getLetterPosXRight( tIndex ) - startOfLine > theLabel->getMaxLineWidth())
{
if (!theLabel->breakLineWithoutSpace())
{
last_word.push_back(character);
int found = cc_utf8_find_last_not_char(multiline_string, ' ');
if (found != -1)
cc_utf8_trim_ws(&multiline_string);
else
multiline_string.clear();
if (multiline_string.size() > 0)
multiline_string.push_back('\n');
++line;
isStartOfLine = false;
startOfLine = -1;
++i;
}
int found = cc_utf8_find_last_not_char(multiline_string, ' ');
if (found != -1)
cc_utf8_trim_ws(&multiline_string);
else
{
cc_utf8_trim_ws(&last_word);
last_word.push_back('\n');
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
isStartOfWord = false;
isStartOfLine = false;
startOfWord = -1;
startOfLine = -1;
++line;
if (i >= stringLength)
break;
if (!startOfWord)
{
startOfWord = theLabel->getLetterPosXLeft( tIndex );
isStartOfWord = true;
}
if (!startOfLine)
{
startOfLine = startOfWord;
isStartOfLine = true;
}
--j;
}
continue;
multiline_string.clear();
if (multiline_string.size() > 0)
multiline_string.push_back('\n');
++line;
isStartOfLine = false;
startOfLine = -1;
}
else
{
// Character is normal.
last_word.push_back(character);
++i;
continue;
cc_utf8_trim_ws(&last_word);
last_word.push_back('\n');
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
last_word.clear();
isStartOfWord = false;
isStartOfLine = false;
startOfWord = -1;
startOfLine = -1;
++line;
--j;
}
}
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
size_t size = multiline_string.size();
unsigned short* strNew = new unsigned short[size + 1];
for (size_t j = 0; j < size; ++j)
else
{
strNew[j] = multiline_string[j];
// Character is normal.
last_word.push_back(character);
}
strNew[size] = 0;
theLabel->assignNewUTF8String(strNew);
return true;
}
else
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
size_t size = multiline_string.size();
unsigned short* strNew = new unsigned short[size + 1];
for (size_t j = 0; j < size; ++j)
{
return false;
strNew[j] = multiline_string[j];
}
strNew[size] = 0;
theLabel->assignNewUTF8String(strNew);
return true;
}
bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
@ -337,7 +289,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
charAdvance = theLabel->getAdvanceForChar(c, i);
charRect = theLabel->getRectForChar(c);
int kerningAmount = theLabel->getKerningForCharsPair(prev, c);
int kerningAmount = theLabel->getKerningInString(i);
if (c == '\n')
{
@ -351,9 +303,8 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
// See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
int yOffset = commonLineHeight - charYOffset;
Point fontPos = Point((float)nextFontPositionX + charXOffset + charRect.size.width * 0.5f + kerningAmount,
(float)nextFontPositionY + yOffset - charRect.size.height * 0.5f);
Point fontPos = Point((float)nextFontPositionX + charXOffset + kerningAmount,
(float)nextFontPositionY + yOffset);
if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false)
{

View File

@ -64,29 +64,12 @@ THE SOFTWARE.
NS_CC_BEGIN
#if CC_USE_ARRAY_VECTOR
bool nodeComparisonLess(const RCPtr<Object>& pp1, const RCPtr<Object>& pp2)
bool nodeComparisonLess(Node* n1, Node* n2)
{
Object *p1 = static_cast<Object*>(pp1);
Object *p2 = static_cast<Object*>(pp2);
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(p2);
return( n1->getLocalZOrder() < n2->getLocalZOrder() ||
( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
);
}
#else
bool nodeComparisonLess(Object* p1, Object* p2)
{
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(p2);
return( n1->getLocalZOrder() < n2->getLocalZOrder() ||
( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
);
}
#endif
// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered.
static int s_globalOrderOfArrival = 1;
@ -232,11 +215,11 @@ void Node::setLocalZOrder(int z)
_eventDispatcher->setDirtyForNode(this);
}
void Node::setGlobalZOrder(float zOrder)
void Node::setGlobalZOrder(float globalZOrder)
{
if (_globalZOrder != zOrder)
if (_globalZOrder != globalZOrder)
{
_globalZOrder = zOrder;
_globalZOrder = globalZOrder;
_eventDispatcher->setDirtyForNode(this);
}
}

View File

@ -1,9 +1,9 @@
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009 Valentin Milea
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2009 Valentin Milea
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
@ -72,11 +72,7 @@ enum {
kNodeOnCleanup
};
#if CC_USE_ARRAY_VECTOR
bool nodeComparisonLess(const RCPtr<Object>& pp1, const RCPtr<Object>& pp2);
#else
bool nodeComparisonLess(Object* p1, Object* p2);
#endif
bool nodeComparisonLess(Node* n1, Node* n2);
class EventListener;
@ -173,9 +169,9 @@ public:
@see `setGlobalZOrder`
@see `setVertexZ`
*/
virtual void setLocalZOrder(int zOrder);
virtual void setLocalZOrder(int localZOrder);
CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int zOrder) { setLocalZOrder(zOrder); }
CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int localZOrder) { setLocalZOrder(localZOrder); }
/* Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing.
*/
virtual void _setLocalZOrder(int z);
@ -208,7 +204,7 @@ public:
@since v3.0
*/
virtual void setGlobalZOrder(float zOrder);
virtual void setGlobalZOrder(float globalZOrder);
/**
* Returns the Node's Global Z Order.
*
@ -535,11 +531,11 @@ public:
* A node which called addChild subsequently will take a larger arrival order,
* If two children have the same Z order, the child with larger arrival order will be drawn later.
*
* @warning This method is used internally for zOrder sorting, don't change this manually
* @warning This method is used internally for localZOrder sorting, don't change this manually
*
* @param orderOfArrival The arrival order.
*/
virtual void setOrderOfArrival(int orderOfArrival);
void setOrderOfArrival(int orderOfArrival);
/**
* Returns the arrival order, indecates which children is added previously.
*
@ -547,7 +543,7 @@ public:
*
* @return The arrival order.
*/
virtual int getOrderOfArrival() const;
int getOrderOfArrival() const;
/** @deprecated No longer needed
@ -595,24 +591,24 @@ public:
*/
virtual void addChild(Node * child);
/**
* Adds a child to the container with a z-order
* Adds a child to the container with a local z-order
*
* If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
*
* @param child A child node
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int)
* @param zOrder Z order for drawing priority. Please refer to `setLocalZOrder(int)`
*/
virtual void addChild(Node * child, int zOrder);
virtual void addChild(Node * child, int localZOrder);
/**
* Adds a child to the container with z order and tag
*
* If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
*
* @param child A child node
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int)
* @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int)
* @param tag A interger to identify the node easily. Please refer to setTag(int)
*/
virtual void addChild(Node* child, int zOrder, int tag);
virtual void addChild(Node* child, int localZOrder, int tag);
/**
* Gets a child from the container with its tag
*
@ -715,9 +711,9 @@ public:
* Reorders a child according to a new z value.
*
* @param child An already added child node. It MUST be already added.
* @param zOrder Z order for drawing priority. Please refer to setZOrder(int)
* @param localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int)
*/
virtual void reorderChild(Node * child, int zOrder);
virtual void reorderChild(Node * child, int localZOrder);
/**
* Sorts the children array once before drawing, instead of every time when a child is added or reordered.
@ -1477,7 +1473,7 @@ protected:
GLProgram *_shaderProgram; ///< OpenGL shader
int _orderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder
int _orderOfArrival; ///< used to preserve sequence while sorting children with the same localZOrder
Scheduler *_scheduler; ///< scheduler used to schedule timers and updates

View File

@ -384,7 +384,6 @@ void ParticleBatchNode::draw(void)
_batchCommand.init(
_globalZOrder,
_textureAtlas->getTexture()->getName(),
_shaderProgram,
_blendFunc,
_textureAtlas,

View File

@ -358,7 +358,6 @@ void SpriteBatchNode::draw()
_batchCommand.init(
_globalZOrder,
_textureAtlas->getTexture()->getName(),
_shaderProgram,
_blendFunc,
_textureAtlas,

View File

@ -22,14 +22,15 @@ 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 <Cocoa/Cocoa.h>
#include "platform/CCCommon.h"
#include "CCEGLView.h"
#define GLFW_EXPOSE_NATIVE_NSGL
#define GLFW_EXPOSE_NATIVE_COCOA
#include "glfw3native.h"
#include <stdarg.h>
#include <stdio.h>
#import "EAGLView.h"
#include <Cocoa/Cocoa.h>
NS_CC_BEGIN
@ -50,7 +51,7 @@ void MessageBox(const char * msg, const char * title)
[alert setInformativeText:tmpTitle];
[alert setAlertStyle:NSWarningAlertStyle];
NSWindow *window = [[CCEAGLView sharedEGLView] window];
id window = glfwGetCocoaWindow(EGLView::getInstance()->getWindow());
[alert beginSheetModalForWindow:window
modalDelegate:[window delegate]
didEndSelector:nil

View File

@ -22,13 +22,14 @@ 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.
****************************************************************************/
#import <Foundation/Foundation.h>
#import "CCDirectorCaller.h"
#import "CCDirector.h"
#import "EAGLView.h"
#import "CCEventDispatcherMac.h"
#include "CCDirector.h"
#include "CCAutoreleasePool.h"
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
static id s_sharedDirectorCaller;
@interface NSObject(CADisplayLink)
@ -82,7 +83,6 @@ static id s_sharedDirectorCaller;
cocos2d::Director::getInstance()->drawScene();
cocos2d::PoolManager::getInstance()->getCurrentPool()->clear();
[[CCEventDispatcher sharedDispatcher] dispatchQueuedEvents];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:nil];
@ -115,21 +115,9 @@ static CVReturn MyDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTime
// All we do here is tell the display it needs a refresh
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// get the opengl view
CCEAGLView *openGLView = [CCEAGLView sharedEGLView];
[openGLView lockOpenGLContext];
// run the main cocos2d loop
cocos2d::Director::getInstance()->mainLoop();
// flush buffer (this line is very important!)
[[openGLView openGLContext] flushBuffer];
[openGLView unlockOpenGLContext];
// send any queued events
[[CCEventDispatcher sharedDispatcher] dispatchQueuedEvents];
[pool release];
}

View File

@ -27,7 +27,6 @@ THE SOFTWARE.
#include <unordered_map>
#include "EAGLView.h"
#include "CCDirector.h"
#include "CCSet.h"
#include "CCTouch.h"

View File

@ -1,277 +0,0 @@
/****************************************************************************
Copyright (c) 2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies 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.
****************************************************************************/
// Only compile this code on Mac. These files should not be included on your iOS project.
// But in case they are included, it won't be compiled.
#import <Availability.h>
#ifndef __CC_EVENT_DISPATCHER_MAC_H__
#define __CC_EVENT_DISPATCHER_MAC_H__
#import <Cocoa/Cocoa.h>
#import "EAGLView.h"
//#import "../../Support/uthash.h" // hack: uthash needs to be imported before utlist to prevent warning
//#import "../../Support/utlist.h"
#import "ccConfig.h"
//NS_CC_BEGIN;
#pragma mark - MouseEventDelegate
/** MouseEventDelegate protocol.
Implement it in your node to receive any of mouse events
*/
@protocol CCMouseEventDelegate <NSObject>
@optional
//
// left
//
/** called when the "mouseDown" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccMouseDown:(NSEvent*)event;
/** called when the "mouseDragged" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccMouseDragged:(NSEvent*)event;
/** called when the "mouseMoved" event is received.
Return YES to avoid propagating the event to other delegates.
By default, "mouseMoved" is disabled. To enable it, send the "setAcceptsMouseMovedEvents:YES" message to the main window.
*/
-(BOOL) ccMouseMoved:(NSEvent*)event;
/** called when the "mouseUp" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccMouseUp:(NSEvent*)event;
//
// right
//
/** called when the "rightMouseDown" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccRightMouseDown:(NSEvent*)event;
/** called when the "rightMouseDragged" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccRightMouseDragged:(NSEvent*)event;
/** called when the "rightMouseUp" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccRightMouseUp:(NSEvent*)event;
//
// other
//
/** called when the "otherMouseDown" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccOtherMouseDown:(NSEvent*)event;
/** called when the "otherMouseDragged" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccOtherMouseDragged:(NSEvent*)event;
/** called when the "otherMouseUp" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccOtherMouseUp:(NSEvent*)event;
//
// scroll wheel
//
/** called when the "scrollWheel" event is received.
Return YES to avoid propagating the event to other delegates.
*/
- (BOOL)ccScrollWheel:(NSEvent *)theEvent;
//
// enter / exit
//
/** called when the "mouseEntered" event is received.
Return YES to avoid propagating the event to other delegates.
*/
- (void)ccMouseEntered:(NSEvent *)theEvent;
/** called when the "mouseExited" event is received.
Return YES to avoid propagating the event to other delegates.
*/
- (void)ccMouseExited:(NSEvent *)theEvent;
@end
#pragma mark - KeyboardEventDelegate
/** KeyboardEventDelegate protocol.
Implement it in your node to receive any of keyboard events
*/
@protocol CCKeyboardEventDelegate <NSObject>
@optional
/** called when the "keyUp" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccKeyUp:(NSEvent*)event;
/** called when the "keyDown" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccKeyDown:(NSEvent*)event;
/** called when the "flagsChanged" event is received.
Return YES to avoid propagating the event to other delegates.
*/
-(BOOL) ccFlagsChanged:(NSEvent*)event;
@end
#pragma mark -
#pragma mark TouchEventDelegate
/** TouchEventDelegate protocol.
Implement it in your node to receive any of touch events
*/
@protocol CCTouchEventDelegate <NSObject>
@optional
/** called when the "touchesBegan" event is received.
Return YES to avoid propagating the event to other delegates.
*/
- (BOOL)ccTouchesBeganWithEvent:(NSEvent *)event;
/** called when the "touchesMoved" event is received.
Return YES to avoid propagating the event to other delegates.
*/
- (BOOL)ccTouchesMovedWithEvent:(NSEvent *)event;
/** called when the "touchesEnded" event is received.
Return YES to avoid propagating the event to other delegates.
*/
- (BOOL)ccTouchesEndedWithEvent:(NSEvent *)event;
/** called when the "touchesCancelled" event is received.
Return YES to avoid propagating the event to other delegates.
*/
- (BOOL)ccTouchesCancelledWithEvent:(NSEvent *)event;
@end
#pragma mark - EventDispatcher
struct _listEntry;
/** EventDispatcher
This is object is responsible for dispatching the events:
- Mouse events
- Keyboard events
- Touch events
Only available on Mac
*/
@interface CCEventDispatcher : NSObject <CCMacEventDelegate> {
BOOL dispatchEvents_;
struct _listEntry *keyboardDelegates_;
struct _listEntry *mouseDelegates_;
struct _listEntry *touchDelegates_;
}
@property (nonatomic, readwrite) BOOL dispatchEvents;
/** EventDispatcher singleton */
+(CCEventDispatcher*) sharedDispatcher;
#pragma mark EventDispatcher - Mouse
/** Adds a mouse delegate to the dispatcher's list.
Delegates with a lower priority value will be called before higher priority values.
All the events will be propgated to all the delegates, unless the one delegate returns YES.
IMPORTANT: The delegate will be retained.
*/
-(void) addMouseDelegate:(id<CCMouseEventDelegate>) delegate priority:(NSInteger)priority;
/** removes a mouse delegate */
-(void) removeMouseDelegate:(id) delegate;
/** Removes all mouse delegates, releasing all the delegates */
-(void) removeAllMouseDelegates;
#pragma mark EventDispatcher - Keyboard
/** Adds a Keyboard delegate to the dispatcher's list.
Delegates with a lower priority value will be called before higher priority values.
All the events will be propgated to all the delegates, unless the one delegate returns YES.
IMPORTANT: The delegate will be retained.
*/
-(void) addKeyboardDelegate:(id<CCKeyboardEventDelegate>) delegate priority:(NSInteger)priority;
/** removes a mouse delegate */
-(void) removeKeyboardDelegate:(id) delegate;
/** Removes all mouse delegates, releasing all the delegates */
-(void) removeAllKeyboardDelegates;
#pragma mark EventDispatcher - Touches
/** Adds a Touch delegate to the dispatcher's list.
Delegates with a lower priority value will be called before higher priority values.
All the events will be propgated to all the delegates, unless the one delegate returns YES.
IMPORTANT: The delegate will be retained.
*/
- (void)addTouchDelegate:(id<CCTouchEventDelegate>)delegate priority:(NSInteger)priority;
/** Removes a touch delegate */
- (void)removeTouchDelegate:(id) delegate;
/** Removes all touch delegates, releasing all the delegates */
- (void)removeAllTouchDelegates;
#pragma mark EventDispatcher - Dispatch Events
#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
-(void) dispatchQueuedEvents;
#endif
@end
//NS_CC_END;
#endif // __CC_EVENT_DISPATCHER_MAC_H__

View File

@ -1,649 +0,0 @@
/****************************************************************************
Copyright (c) 2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies 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.
****************************************************************************/
// Only compile this code on Mac. These files should not be included on your iOS project.
// But in case they are included, it won't be compiled.
#import <Availability.h>
#import "CCEventDispatcherMac.h"
#import "ccConfig.h"
#include "utlist.h"
#include "CCDirector.h"
//NS_CC_BEGIN;
static CCEventDispatcher *sharedDispatcher = nil;
enum {
// mouse
kImplementsMouseDown = 1 << 0,
kImplementsMouseMoved = 1 << 1,
kImplementsMouseDragged = 1 << 2,
kImplementsMouseUp = 1 << 3,
kImplementsRightMouseDown = 1 << 4,
kImplementsRightMouseDragged = 1 << 5,
kImplementsRightMouseUp = 1 << 6,
kImplementsOtherMouseDown = 1 << 7,
kImplementsOtherMouseDragged = 1 << 8,
kImplementsOtherMouseUp = 1 << 9,
kImplementsScrollWheel = 1 << 10,
kImplementsMouseEntered = 1 << 11,
kImplementsMouseExited = 1 << 12,
kImplementsTouchesBegan = 1 << 13,
kImplementsTouchesMoved = 1 << 14,
kImplementsTouchesEnded = 1 << 15,
kImplementsTouchesCancelled = 1 << 16,
// keyboard
kImplementsKeyUp = 1 << 0,
kImplementsKeyDown = 1 << 1,
kImplementsFlagsChanged = 1 << 2,
};
typedef struct _listEntry
{
struct _listEntry *prev, *next;
id delegate;
NSInteger priority;
NSUInteger flags;
} tListEntry;
#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
#define QUEUE_EVENT_MAX 128
struct _eventQueue {
SEL selector;
NSEvent *event;
};
static struct _eventQueue eventQueue[QUEUE_EVENT_MAX];
static int eventQueueCount;
#endif // CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
@implementation CCEventDispatcher
@synthesize dispatchEvents=dispatchEvents_;
+(CCEventDispatcher*) sharedDispatcher
{
@synchronized(self) {
if (sharedDispatcher == nil)
sharedDispatcher = [[self alloc] init]; // assignment not done here
}
return sharedDispatcher;
}
+(id) allocWithZone:(NSZone *)zone
{
@synchronized(self) {
NSAssert(sharedDispatcher == nil, @"Attempted to allocate a second instance of a singleton.");
return [super allocWithZone:zone];
}
return nil; // on subsequent allocation attempts return nil
}
-(id) init
{
if( (self = [super init]) )
{
// events enabled by default
dispatchEvents_ = YES;
// delegates
keyboardDelegates_ = nullptr;
mouseDelegates_ = nullptr;
touchDelegates_ = nullptr;
#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
eventQueueCount = 0;
#endif
}
return self;
}
- (void) dealloc
{
[super dealloc];
}
#pragma mark EventDispatcher - add / remove delegates
-(void) addDelegate:(id)delegate priority:(NSInteger)priority flags:(NSUInteger)flags list:(tListEntry**)list
{
tListEntry *listElement = (tListEntry *)malloc( sizeof(*listElement) );
listElement->delegate = [delegate retain];
listElement->priority = priority;
listElement->flags = flags;
listElement->next = listElement->prev = nullptr;
// empty list ?
if( ! *list ) {
DL_APPEND( *list, listElement );
} else {
BOOL added = NO;
for( tListEntry *elem = *list; elem ; elem = elem->next ) {
if( priority < elem->priority ) {
if( elem == *list )
DL_PREPEND(*list, listElement);
else {
listElement->next = elem;
listElement->prev = elem->prev;
elem->prev->next = listElement;
elem->prev = listElement;
}
added = YES;
break;
}
}
// Not added? priority has the higher value. Append it.
if( !added )
DL_APPEND(*list, listElement);
}
}
-(void) removeDelegate:(id)delegate fromList:(tListEntry**)list
{
tListEntry *entry, *tmp;
// updates with priority < 0
DL_FOREACH_SAFE( *list, entry, tmp ) {
if( entry->delegate == delegate ) {
DL_DELETE( *list, entry );
[delegate release];
free(entry);
break;
}
}
}
-(void) removeAllDelegatesFromList:(tListEntry**)list
{
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( *list, entry, tmp ) {
DL_DELETE( *list, entry );
free(entry);
}
}
-(void) addMouseDelegate:(id<CCMouseEventDelegate>) delegate priority:(NSInteger)priority
{
NSUInteger flags = 0;
flags |= ( [delegate respondsToSelector:@selector(ccMouseDown:)] ? kImplementsMouseDown : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccMouseDragged:)] ? kImplementsMouseDragged : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccMouseMoved:)] ? kImplementsMouseMoved : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccMouseUp:)] ? kImplementsMouseUp : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccRightMouseDown:)] ? kImplementsRightMouseDown : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccRightMouseDragged:)] ? kImplementsRightMouseDragged : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccRightMouseUp:)] ? kImplementsRightMouseUp : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseDown:)] ? kImplementsOtherMouseDown : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseDragged:)] ? kImplementsOtherMouseDragged : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseUp:)] ? kImplementsOtherMouseUp : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccMouseEntered:)] ? kImplementsMouseEntered : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccMouseExited:)] ? kImplementsMouseExited : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccScrollWheel:)] ? kImplementsScrollWheel : 0 );
[self addDelegate:delegate priority:priority flags:flags list:&mouseDelegates_];
}
-(void) removeMouseDelegate:(id) delegate
{
[self removeDelegate:delegate fromList:&mouseDelegates_];
}
-(void) removeAllMouseDelegates
{
[self removeAllDelegatesFromList:&mouseDelegates_];
}
-(void) addKeyboardDelegate:(id<CCKeyboardEventDelegate>) delegate priority:(NSInteger)priority
{
NSUInteger flags = 0;
flags |= ( [delegate respondsToSelector:@selector(ccKeyUp:)] ? kImplementsKeyUp : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccKeyDown:)] ? kImplementsKeyDown : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccFlagsChanged:)] ? kImplementsFlagsChanged : 0 );
[self addDelegate:delegate priority:priority flags:flags list:&keyboardDelegates_];
}
-(void) removeKeyboardDelegate:(id) delegate
{
[self removeDelegate:delegate fromList:&keyboardDelegates_];
}
-(void) removeAllKeyboardDelegates
{
[self removeAllDelegatesFromList:&keyboardDelegates_];
}
-(void) addTouchDelegate:(id<CCTouchEventDelegate>) delegate priority:(NSInteger)priority
{
NSUInteger flags = 0;
flags |= ( [delegate respondsToSelector:@selector(ccTouchesBeganWithEvent:)] ? kImplementsTouchesBegan : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccTouchesMovedWithEvent:)] ? kImplementsTouchesMoved : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccTouchesEndedWithEvent:)] ? kImplementsTouchesEnded : 0 );
flags |= ( [delegate respondsToSelector:@selector(ccTouchesCancelledWithEvent:)] ? kImplementsTouchesCancelled : 0 );
[self addDelegate:delegate priority:priority flags:flags list:&touchDelegates_];
}
-(void) removeTouchDelegate:(id) delegate
{
[self removeDelegate:delegate fromList:&touchDelegates_];
}
-(void) removeAllTouchDelegates
{
[self removeAllDelegatesFromList:&touchDelegates_];
}
#pragma mark EventDispatcher - Mouse events
//
// Mouse events
//
//
// Left
//
- (void)mouseDown:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsMouseDown ) {
void *swallows = [entry->delegate performSelector:@selector(ccMouseDown:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)mouseMoved:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsMouseMoved ) {
void *swallows = [entry->delegate performSelector:@selector(ccMouseMoved:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)mouseDragged:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsMouseDragged ) {
void *swallows = [entry->delegate performSelector:@selector(ccMouseDragged:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)mouseUp:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsMouseUp ) {
void *swallows = [entry->delegate performSelector:@selector(ccMouseUp:) withObject:event];
if( swallows )
break;
}
}
}
}
//
// Mouse Right
//
- (void)rightMouseDown:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsRightMouseDown ) {
void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDown:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)rightMouseDragged:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsRightMouseDragged ) {
void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDragged:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)rightMouseUp:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsRightMouseUp ) {
void *swallows = [entry->delegate performSelector:@selector(ccRightMouseUp:) withObject:event];
if( swallows )
break;
}
}
}
}
//
// Mouse Other
//
- (void)otherMouseDown:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsOtherMouseDown ) {
void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDown:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)otherMouseDragged:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsOtherMouseDragged ) {
void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDragged:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)otherMouseUp:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsOtherMouseUp ) {
void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseUp:) withObject:event];
if( swallows )
break;
}
}
}
}
//
// Scroll Wheel
//
- (void)scrollWheel:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsScrollWheel ) {
void *swallows = [entry->delegate performSelector:@selector(ccScrollWheel:) withObject:event];
if( swallows )
break;
}
}
}
}
//
// Mouse enter / exit
- (void)mouseExited:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsMouseEntered ) {
void *swallows = [entry->delegate performSelector:@selector(ccMouseEntered:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)mouseEntered:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsMouseExited) {
void *swallows = [entry->delegate performSelector:@selector(ccMouseExited:) withObject:event];
if( swallows )
break;
}
}
}
}
#pragma mark EventDispatcher - Keyboard events
// Keyboard events
- (void)keyDown:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
// cocos2d::Director::getInstance()->getKeyboardDispatcher()->dispatchKeyboardEvent(event.keyCode, true);
DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsKeyDown ) {
void *swallows = [entry->delegate performSelector:@selector(ccKeyDown:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)keyUp:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
// cocos2d::Director::getInstance()->getKeyboardDispatcher()->dispatchKeyboardEvent(event.keyCode, false);
DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsKeyUp ) {
void *swallows = [entry->delegate performSelector:@selector(ccKeyUp:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)flagsChanged:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsFlagsChanged ) {
void *swallows = [entry->delegate performSelector:@selector(ccFlagsChanged:) withObject:event];
if( swallows )
break;
}
}
}
}
#pragma mark EventDispatcher - Touch events
- (void)touchesBeganWithEvent:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsTouchesBegan) {
void *swallows = [entry->delegate performSelector:@selector(ccTouchesBeganWithEvent:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)touchesMovedWithEvent:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsTouchesMoved) {
void *swallows = [entry->delegate performSelector:@selector(ccTouchesMovedWithEvent:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)touchesEndedWithEvent:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsTouchesEnded) {
void *swallows = [entry->delegate performSelector:@selector(ccTouchesEndedWithEvent:) withObject:event];
if( swallows )
break;
}
}
}
}
- (void)touchesCancelledWithEvent:(NSEvent *)event
{
if( dispatchEvents_ ) {
tListEntry *entry, *tmp;
DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) {
if ( entry->flags & kImplementsTouchesCancelled) {
void *swallows = [entry->delegate performSelector:@selector(ccTouchesCancelledWithEvent:) withObject:event];
if( swallows )
break;
}
}
}
}
#pragma mark EventDispatcher - queue events
#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
-(void) queueEvent:(NSEvent*)event selector:(SEL)selector
{
NSAssert( eventQueueCount < QUEUE_EVENT_MAX, @"CCEventDispatcher: recompile. Increment QUEUE_EVENT_MAX value");
@synchronized (self) {
eventQueue[eventQueueCount].selector = selector;
eventQueue[eventQueueCount].event = [event copy];
eventQueueCount++;
}
}
-(void) dispatchQueuedEvents
{
@synchronized (self) {
for( int i=0; i < eventQueueCount; i++ ) {
SEL sel = eventQueue[i].selector;
NSEvent *event = eventQueue[i].event;
[self performSelector:sel withObject:event];
[event release];
}
eventQueueCount = 0;
}
}
#endif // CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
//NS_CC_END;
@end

View File

@ -1,39 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies 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 __CC_WINDOW_H__
#define __CC_WINDOW_H__
#import <Cocoa/Cocoa.h>
@interface CCWindow : NSWindow
{
}
- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen;
@end
#endif // __CC_WINDOW_H__

View File

@ -1,82 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies 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.
****************************************************************************/
#import "CCWindow.h"
#import "EAGLView.h"
@implementation CCWindow
- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen
{
int styleMask = fullscreen ? NSBackingStoreBuffered : ( NSTitledWindowMask | NSClosableWindowMask );
self = [self initWithContentRect:frame
styleMask:styleMask
backing:NSBackingStoreBuffered
defer:YES];
if (self != nil)
{
if(fullscreen)
{
[self setLevel:NSMainMenuWindowLevel+1];
[self setHidesOnDeactivate:YES];
[self setHasShadow:NO];
}
[self setAcceptsMouseMovedEvents:NO];
[self setOpaque:YES];
}
return self;
}
- (BOOL) canBecomeKeyWindow
{
return YES;
}
- (BOOL) canBecomeMainWindow
{
return YES;
}
- (void) keyDown:(NSEvent *)event
{
// exit fullscreen if user pressed esc
if([event keyCode] == 53)
{
CCEAGLView* eaglView = [CCEAGLView sharedEGLView];
// cancel full screen
if( [eaglView isFullScreen] )
[eaglView setFullScreen:NO];
// let another responder take it
else
[super keyDown:event];
}
}
@end

View File

@ -1,120 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies 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 __EAGLVIEW_MAC_H__
#define __EAGLVIEW_MAC_H__
#import <Cocoa/Cocoa.h>
#import "ccConfig.h"
//PROTOCOLS:
@protocol CCMacEventDelegate <NSObject>
// Mouse
- (void)mouseDown:(NSEvent *)theEvent;
- (void)mouseUp:(NSEvent *)theEvent;
- (void)mouseMoved:(NSEvent *)theEvent;
- (void)mouseDragged:(NSEvent *)theEvent;
- (void)rightMouseDown:(NSEvent*)event;
- (void)rightMouseDragged:(NSEvent*)event;
- (void)rightMouseUp:(NSEvent*)event;
- (void)otherMouseDown:(NSEvent*)event;
- (void)otherMouseDragged:(NSEvent*)event;
- (void)otherMouseUp:(NSEvent*)event;
- (void)scrollWheel:(NSEvent *)theEvent;
- (void)mouseEntered:(NSEvent *)theEvent;
- (void)mouseExited:(NSEvent *)theEvent;
// Keyboard
- (void)keyDown:(NSEvent *)theEvent;
- (void)keyUp:(NSEvent *)theEvent;
- (void)flagsChanged:(NSEvent *)theEvent;
// Touches
- (void)touchesBeganWithEvent:(NSEvent *)event;
- (void)touchesMovedWithEvent:(NSEvent *)event;
- (void)touchesEndedWithEvent:(NSEvent *)event;
- (void)touchesCancelledWithEvent:(NSEvent *)event;
#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
- (void)queueEvent:(NSEvent*)event selector:(SEL)selector;
#endif
@end
/** MacGLView
Only available for Mac OS X
*/
@interface CCEAGLView : NSOpenGLView {
id<CCMacEventDelegate> eventDelegate_;
BOOL isFullScreen_;
NSWindow *fullScreenWindow_;
// cache
NSWindow *windowGLView_;
NSView *superViewGLView_;
NSRect originalWinRect_; // Original size and position
float frameZoomFactor_;
}
@property (nonatomic, readwrite, assign) id<CCMacEventDelegate> eventDelegate;
// whether or not the view is in fullscreen mode
@property (nonatomic, readonly) BOOL isFullScreen;
@property (nonatomic, readwrite) float frameZoomFactor;
// initializes the MacGLView with a frame rect and an OpenGL context
- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context;
- (id) initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format;
/** uses and locks the OpenGL context */
-(void) lockOpenGLContext;
/** unlocks the openGL context */
-(void) unlockOpenGLContext;
/** returns the depth format of the view in BPP */
- (NSUInteger) depthFormat;
- (void) setFrameZoomFactor:(float)frameZoomFactor;
// get the view object
+(id) sharedEGLView;
-(int) getWidth;
-(int) getHeight;
-(void) swapBuffers;
-(void) setFullScreen:(BOOL)fullscreen;
@end
#endif // __EAGLVIEW_MAC_H__

View File

@ -1,490 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies 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.
****************************************************************************/
/*
* Idea of subclassing NSOpenGLView was taken from "TextureUpload" Apple's sample
*/
#import <Availability.h>
#import "EAGLView.h"
#import "CCEGLView.h"
#import <OpenGL/gl.h>
#import "CCDirector.h"
#import "ccConfig.h"
#import "CCSet.h"
#import "CCTouch.h"
#import "CCIMEDispatcher.h"
#import "CCWindow.h"
#import "CCEventDispatcherMac.h"
#import "CCEGLView.h"
//USING_NS_CC;
static CCEAGLView *view;
@implementation CCEAGLView
@synthesize eventDelegate = eventDelegate_, isFullScreen = isFullScreen_, frameZoomFactor=frameZoomFactor_;
+(id) sharedEGLView
{
return view;
}
- (id) initWithFrame:(NSRect)frameRect
{
self = [self initWithFrame:frameRect shareContext:nil];
return self;
}
- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context
{
NSOpenGLPixelFormatAttribute attribs[] =
{
// NSOpenGLPFAAccelerated,
// NSOpenGLPFANoRecovery,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFADepthSize, 24,
0
};
NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
if (!pixelFormat)
NSLog(@"No OpenGL pixel format");
if( (self = [super initWithFrame:frameRect pixelFormat:[pixelFormat autorelease]]) ) {
if( context )
[self setOpenGLContext:context];
// event delegate
eventDelegate_ = [CCEventDispatcher sharedDispatcher];
}
cocos2d::EGLView::getInstance()->setFrameSize(frameRect.size.width, frameRect.size.height);
frameZoomFactor_ = 1.0f;
view = self;
return self;
}
- (id) initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format{
// event delegate
eventDelegate_ = [CCEventDispatcher sharedDispatcher];
cocos2d::EGLView::getInstance()->setFrameSize(frameRect.size.width, frameRect.size.height);
frameZoomFactor_ = 1.0f;
view = self;
[super initWithFrame:frameRect pixelFormat:format];
return self;
}
- (void) update
{
// XXX: Should I do something here ?
[super update];
}
- (void) prepareOpenGL
{
// XXX: Initialize OpenGL context
[super prepareOpenGL];
// Make this openGL context current to the thread
// (i.e. all openGL on this thread calls will go to this context)
[[self openGLContext] makeCurrentContext];
// Synchronize buffer swaps with vertical refresh rate
GLint swapInt = 1;
[[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
// GLint order = -1;
// [[self openGLContext] setValues:&order forParameter:NSOpenGLCPSurfaceOrder];
}
- (NSUInteger) depthFormat
{
return 24;
}
- (void) setFrameZoomFactor:(float)frameZoomFactor
{
frameZoomFactor_ = frameZoomFactor;
NSRect winRect = [[self window] frame];
NSRect viewRect = [self frame];
// compute the margin width and margin height
float diffX = winRect.size.width - viewRect.size.width;
float diffY = winRect.size.height - viewRect.size.height;
// new window width and height
float newWindowWidth = (int)(viewRect.size.width * frameZoomFactor + diffX);
float newWindowHeight = (int)(viewRect.size.height * frameZoomFactor + diffY);
// display window in the center of the screen
NSRect screenRect = [[NSScreen mainScreen] frame];
float originX = (screenRect.size.width - newWindowWidth) / 2;
float originY = (screenRect.size.height - newWindowHeight) / 2;
[[self window] setFrame:NSMakeRect(originX, originY, newWindowWidth, newWindowHeight) display:true];
}
- (void) reshape
{
// We draw on a secondary thread through the display link
// When resizing the view, -reshape is called automatically on the main thread
// Add a mutex around to avoid the threads accessing the context simultaneously when resizing
[self lockOpenGLContext];
// NSRect rect = [self bounds];
cocos2d::Director *director = cocos2d::Director::getInstance();
// CGSize size = NSSizeToCGSize(rect.size);
// cocos2d::Size ccsize = cocos2d::Size(size.width, size.height);
//director->reshapeProjection(ccsize);
// avoid flicker
director->drawScene();
// [self setNeedsDisplay:YES];
[self unlockOpenGLContext];
}
-(void) lockOpenGLContext
{
NSOpenGLContext *glContext = [self openGLContext];
NSAssert( glContext, @"FATAL: could not get openGL context");
[glContext makeCurrentContext];
CGLLockContext((CGLContextObj)[glContext CGLContextObj]);
}
-(void) unlockOpenGLContext
{
NSOpenGLContext *glContext = [self openGLContext];
NSAssert( glContext, @"FATAL: could not get openGL context");
CGLUnlockContext((CGLContextObj)[glContext CGLContextObj]);
}
- (void) dealloc
{
CCLOGINFO("deallocing CCEAGLView: %p", self);
[super dealloc];
}
-(int) getWidth
{
NSSize bound = [self bounds].size;
return bound.width;
}
-(int) getHeight
{
NSSize bound = [self bounds].size;
return bound.height;
}
-(void) swapBuffers
{
}
//
// setFullScreen code taken from GLFullScreen example by Apple
//
- (void) setFullScreen:(BOOL)fullscreen
{
// Mac OS X 10.6 and later offer a simplified mechanism to create full-screen contexts
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
if (isFullScreen_ == fullscreen)
return;
CCEAGLView *openGLview = [[self class] sharedEGLView];
if( fullscreen ) {
originalWinRect_ = [openGLview frame];
// Cache normal window and superview of openGLView
if(!windowGLView_)
windowGLView_ = [[openGLview window] retain];
[superViewGLView_ release];
superViewGLView_ = [[openGLview superview] retain];
// Get screen size
NSRect displayRect = [[NSScreen mainScreen] frame];
// Create a screen-sized window on the display you want to take over
fullScreenWindow_ = [[CCWindow alloc] initWithFrame:displayRect fullscreen:YES];
// Remove glView from window
[openGLview removeFromSuperview];
// Set new frame
[openGLview setFrame:displayRect];
// Attach glView to fullscreen window
[fullScreenWindow_ setContentView:openGLview];
// Show the fullscreen window
[fullScreenWindow_ makeKeyAndOrderFront:self];
[fullScreenWindow_ makeMainWindow];
//[fullScreenWindow_ setNextResponder:superViewGLView_];
} else {
// Remove glView from fullscreen window
[openGLview removeFromSuperview];
// Release fullscreen window
[fullScreenWindow_ release];
fullScreenWindow_ = nil;
// Attach glView to superview
[superViewGLView_ addSubview:openGLview];
// Set new frame
[openGLview setFrame:originalWinRect_];
// Show the window
[windowGLView_ makeKeyAndOrderFront:self];
[windowGLView_ makeMainWindow];
}
// issue #1189
[windowGLView_ makeFirstResponder:openGLview];
isFullScreen_ = fullscreen;
//[openGLview retain]; // Retain +1
// is this necessary?
// re-configure glView
//cocos2d::Director *director = cocos2d::Director::getInstance();
//director->setOpenGLView(openGLview); //[self setView:openGLview];
//[openGLview release]; // Retain -1
[openGLview setNeedsDisplay:YES];
#else
#error Full screen is not supported for Mac OS 10.5 or older yet
#error If you don't want FullScreen support, you can safely remove these 2 lines
#endif
}
#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
#define DISPATCH_EVENT(__event__, __selector__) [eventDelegate_ queueEvent:__event__ selector:__selector__];
#else
#define DISPATCH_EVENT(__event__, __selector__) \
id obj = eventDelegate_; \
[obj performSelector:__selector__ \
onThread:[(cocos2d::Director*)[Director sharedDirector] runningThread] \
withObject:__event__ \
waitUntilDone:NO];
#endif
#pragma mark CCEAGLView - Mouse events
- (void)mouseDown:(NSEvent *)theEvent
{
NSPoint event_location = [theEvent locationInWindow];
NSPoint local_point = [self convertPoint:event_location fromView:nil];
float x = local_point.x;
float y = [self getHeight] - local_point.y;
NSInteger ids[1] = {0};
float xs[1] = {0.0f};
float ys[1] = {0.0f};
ids[0] = [theEvent eventNumber];
xs[0] = x / frameZoomFactor_;
ys[0] = y / frameZoomFactor_;
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, (int*)ids, xs, ys);
}
- (void)mouseMoved:(NSEvent *)theEvent
{
DISPATCH_EVENT(theEvent, _cmd);
}
- (void)mouseDragged:(NSEvent *)theEvent
{
NSPoint event_location = [theEvent locationInWindow];
NSPoint local_point = [self convertPoint:event_location fromView:nil];
float x = local_point.x;
float y = [self getHeight] - local_point.y;
NSInteger ids[1] = {0};
float xs[1] = {0.0f};
float ys[1] = {0.0f};
ids[0] = [theEvent eventNumber];
xs[0] = x / frameZoomFactor_;
ys[0] = y / frameZoomFactor_;
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, (int*)ids, xs, ys);
}
- (void)mouseUp:(NSEvent *)theEvent
{
NSPoint event_location = [theEvent locationInWindow];
NSPoint local_point = [self convertPoint:event_location fromView:nil];
float x = local_point.x;
float y = [self getHeight] - local_point.y;
NSInteger ids[1] = {0};
float xs[1] = {0.0f};
float ys[1] = {0.0f};
ids[0] = [theEvent eventNumber];
xs[0] = x / frameZoomFactor_;
ys[0] = y / frameZoomFactor_;
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, (int*)ids, xs, ys);
}
- (void)rightMouseDown:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
// pass the event along to the next responder (like your NSWindow subclass)
[super rightMouseDown:theEvent];
}
- (void)rightMouseDragged:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
[super rightMouseDragged:theEvent];
}
- (void)rightMouseUp:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
[super rightMouseUp:theEvent];
}
- (void)otherMouseDown:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
[super otherMouseDown:theEvent];
}
- (void)otherMouseDragged:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
[super otherMouseDragged:theEvent];
}
- (void)otherMouseUp:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
[super otherMouseUp:theEvent];
}
- (void)mouseEntered:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
[super mouseEntered:theEvent];
}
- (void)mouseExited:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
[super mouseExited:theEvent];
}
-(void) scrollWheel:(NSEvent *)theEvent {
DISPATCH_EVENT(theEvent, _cmd);
[super scrollWheel:theEvent];
}
#pragma mark CCEAGLView - Key events
-(BOOL) becomeFirstResponder
{
return YES;
}
-(BOOL) acceptsFirstResponder
{
return YES;
}
-(BOOL) resignFirstResponder
{
return YES;
}
- (void)keyDown:(NSEvent *)theEvent
{
DISPATCH_EVENT(theEvent, _cmd);
// pass the event along to the next responder (like your NSWindow subclass)
[super keyDown:theEvent];
}
- (void)keyUp:(NSEvent *)theEvent
{
DISPATCH_EVENT(theEvent, _cmd);
// pass the event along to the next responder (like your NSWindow subclass)
[super keyUp:theEvent];
}
- (void)flagsChanged:(NSEvent *)theEvent
{
DISPATCH_EVENT(theEvent, _cmd);
}
#pragma mark CCEAGLView - Touch events
- (void)touchesBeganWithEvent:(NSEvent *)theEvent
{
DISPATCH_EVENT(theEvent, _cmd);
}
- (void)touchesMovedWithEvent:(NSEvent *)theEvent
{
DISPATCH_EVENT(theEvent, _cmd);
}
- (void)touchesEndedWithEvent:(NSEvent *)theEvent
{
DISPATCH_EVENT(theEvent, _cmd);
}
- (void)touchesCancelledWithEvent:(NSEvent *)theEvent
{
DISPATCH_EVENT(theEvent, _cmd);
}
@end

View File

@ -26,6 +26,7 @@
#include "renderer/CCBatchCommand.h"
#include "ccGLStateCache.h"
#include "CCTextureAtlas.h"
#include "CCTexture2D.h"
NS_CC_BEGIN
@ -38,10 +39,13 @@ BatchCommand::BatchCommand()
_shader = nullptr;
}
void BatchCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform)
void BatchCommand::init(float globalOrder, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform)
{
CCASSERT(shader, "shader cannot be nill");
CCASSERT(textureAtlas, "textureAtlas cannot be nill");
_globalOrder = globalOrder;
_textureID = textureID;
_textureID = textureAtlas->getTexture()->getName();
_blendType = blendType;
_shader = shader;

View File

@ -43,19 +43,15 @@ public:
BatchCommand();
~BatchCommand();
void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform);
void init(float depth, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform);
void execute();
protected:
//Material
int32_t _materialID;
//Maternal
GLuint _textureID;
GLProgram* _shader;
// GLuint _shaderID;
BlendFunc _blendType;
TextureAtlas *_textureAtlas;

View File

@ -44,24 +44,23 @@ AutoreleasePool::AutoreleasePool(const std::string &name)
AutoreleasePool::~AutoreleasePool()
{
CCLOGINFO("deallocing AutoreleasePool: %p", this);
_managedObjectArray.clear();
clear();
PoolManager::getInstance()->pop();
}
void AutoreleasePool::addObject(Object* object)
{
_managedObjectArray.pushBack(object);
CCASSERT(object->_reference > 1, "reference count should be greater than 1");
_managedObjectArray.push_back(object);
}
void AutoreleasePool::clear()
{
if (!_managedObjectArray.empty())
for (const auto &obj : _managedObjectArray)
{
_managedObjectArray.clear();
obj->release();
}
_managedObjectArray.clear();
}
void AutoreleasePool::dump()

View File

@ -26,9 +26,9 @@ THE SOFTWARE.
#define __AUTORELEASEPOOL_H__
#include <stack>
#include <vector>
#include <string>
#include "CCObject.h"
#include "CCVector.h"
NS_CC_BEGIN
@ -100,7 +100,7 @@ private:
* be destructed properly by calling Object::release() even if the object
* is in the pool.
*/
Vector<Object*> _managedObjectArray;
std::vector<Object*> _managedObjectArray;
std::string _name;
};

@ -1 +1 @@
Subproject commit de699f63aef423c3d90725171b0f020a719ef572
Subproject commit 68ff365557a8bdb119c2a4e2502214b4d1025c7e

View File

@ -28,10 +28,15 @@
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "CCEditBox.h"
#import "EAGLView.h"
#define GLFW_EXPOSE_NATIVE_NSGL
#define GLFW_EXPOSE_NATIVE_COCOA
#include "glfw3native.h"
#define getEditBoxImplMac() ((cocos2d::extension::EditBoxImplMac*)editBox_)
@implementation CCCustomNSTextField
- (CGRect)textRectForBounds:(CGRect)bounds {
@ -58,6 +63,10 @@
@synthesize editState = editState_;
@synthesize editBox = editBox_;
- (id) getNSWindow {
return glfwGetCocoaWindow(cocos2d::EGLView::getInstance()->getWindow());
}
- (void)dealloc
{
[textField_ resignFirstResponder];
@ -84,7 +93,7 @@
[textField_ setDelegate:self];
self.editBox = editBox;
[[CCEAGLView sharedEGLView] addSubview:textField_];
[[[self getNSWindow] contentView] addSubview:textField_];
return self;
}while(0);
@ -94,8 +103,7 @@
-(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance
{
id eglView = [CCEAGLView sharedEGLView];
[eglView doAnimationWhenKeyboardMoveWithDuration:duration distance:distance];
[[[self getNSWindow] contentView] doAnimationWhenKeyboardMoveWithDuration:duration distance:distance];
}
-(void) setPosition:(NSPoint) pos

View File

@ -123,6 +123,7 @@ Classes/PerformanceTest/PerformanceTouchesTest.cpp \
Classes/PerformanceTest/PerformanceLabelTest.cpp \
Classes/PerformanceTest/PerformanceRendererTest.cpp \
Classes/PerformanceTest/PerformanceContainerTest.cpp \
Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp \
Classes/PhysicsTest/PhysicsTest.cpp \
Classes/ReleasePoolTest/ReleasePoolTest.cpp \
Classes/RenderTextureTest/RenderTextureTest.cpp \

View File

@ -118,6 +118,7 @@ set(SAMPLE_SRC
Classes/PerformanceTest/PerformanceLabelTest.cpp
Classes/PerformanceTest/PerformanceRendererTest.cpp
Classes/PerformanceTest/PerformanceContainerTest.cpp
Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp
Classes/PhysicsTest/PhysicsTest.cpp
Classes/ReleasePoolTest/ReleasePoolTest.cpp
Classes/RenderTextureTest/RenderTextureTest.cpp

View File

@ -24,7 +24,7 @@
****************************************************************************/
#ifndef _ACTIONS__PROGRESS_TEST_H_
#define _ACTIONS_PROGRESS_TEST_H_
#define _ACTIONS__PROGRESS_TEST_H_
#include "../testBasic.h"
#include "../BaseTest.h"
@ -99,4 +99,4 @@ public:
virtual void runThisTest();
};
#endif
#endif // _ACTIONS__PROGRESS_TEST_H_

View File

@ -0,0 +1,795 @@
//
// PerformanceEventDispatcherTest.cpp
//
#include "PerformanceEventDispatcherTest.h"
#include <algorithm>
// Enable profiles for this file
#undef CC_PROFILER_DISPLAY_TIMERS
#define CC_PROFILER_DISPLAY_TIMERS() Profiler::getInstance()->displayTimers()
#undef CC_PROFILER_PURGE_ALL
#define CC_PROFILER_PURGE_ALL() Profiler::getInstance()->releaseAllTimers()
#undef CC_PROFILER_START
#define CC_PROFILER_START(__name__) ProfilingBeginTimingBlock(__name__)
#undef CC_PROFILER_STOP
#define CC_PROFILER_STOP(__name__) ProfilingEndTimingBlock(__name__)
#undef CC_PROFILER_RESET
#define CC_PROFILER_RESET(__name__) ProfilingResetTimingBlock(__name__)
#undef CC_PROFILER_START_CATEGORY
#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingBeginTimingBlock(__name__); } while(0)
#undef CC_PROFILER_STOP_CATEGORY
#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingEndTimingBlock(__name__); } while(0)
#undef CC_PROFILER_RESET_CATEGORY
#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingResetTimingBlock(__name__); } while(0)
#undef CC_PROFILER_START_INSTANCE
#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ ProfilingBeginTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0)
#undef CC_PROFILER_STOP_INSTANCE
#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ ProfilingEndTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0)
#undef CC_PROFILER_RESET_INSTANCE
#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ ProfilingResetTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0)
static std::function<PerformanceEventDispatcherScene*()> createFunctions[] =
{
CL(TouchEventDispatchingPerfTest),
CL(KeyboardEventDispatchingPerfTest),
CL(CustomEventDispatchingPerfTest),
};
#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))
enum {
kTagInfoLayer = 1,
kTagBase = 20000,
};
enum {
kMaxNodes = 15000,
kNodesIncrease = 500,
};
static int g_curCase = 0;
////////////////////////////////////////////////////////
//
// EventDispatcherBasicLayer
//
////////////////////////////////////////////////////////
EventDispatcherBasicLayer::EventDispatcherBasicLayer(bool bControlMenuVisible, int nMaxCases, int nCurCase)
: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase)
{
}
void EventDispatcherBasicLayer::showCurrentTest()
{
int nodes = ((PerformanceEventDispatcherScene*)getParent())->getQuantityOfNodes();
auto scene = createFunctions[_curCase]();
g_curCase = _curCase;
if (scene)
{
scene->initWithQuantityOfNodes(nodes);
Director::getInstance()->replaceScene(scene);
}
}
////////////////////////////////////////////////////////
//
// PerformanceEventDispatcherScene
//
////////////////////////////////////////////////////////
void PerformanceEventDispatcherScene::initWithQuantityOfNodes(unsigned int nNodes)
{
_type = 0;
srand(time(nullptr));
auto s = Director::getInstance()->getWinSize();
// Title
auto label = LabelTTF::create(title().c_str(), "Arial", 40);
addChild(label, 1, TAG_TITLE);
label->setPosition(Point(s.width/2, s.height-32));
label->setColor(Color3B(255,255,40));
// Subtitle
std::string strSubTitle = subtitle();
if(strSubTitle.length())
{
auto l = LabelTTF::create(strSubTitle.c_str(), "Thonburi", 16);
addChild(l, 1, TAG_SUBTITLE);
l->setPosition(Point(s.width/2, s.height-80));
}
_lastRenderedCount = 0;
_currentQuantityOfNodes = 0;
_quantityOfNodes = nNodes;
MenuItemFont::setFontSize(65);
auto decrease = MenuItemFont::create(" - ", [&](Object *sender) {
_quantityOfNodes -= kNodesIncrease;
if( _quantityOfNodes < 0 )
_quantityOfNodes = 0;
updateQuantityLabel();
updateQuantityOfNodes();
updateProfilerName();
CC_PROFILER_PURGE_ALL();
srand(0);
});
decrease->setColor(Color3B(0,200,20));
_decrease = decrease;
auto increase = MenuItemFont::create(" + ", [&](Object *sender) {
_quantityOfNodes += kNodesIncrease;
if( _quantityOfNodes > kMaxNodes )
_quantityOfNodes = kMaxNodes;
updateQuantityLabel();
updateQuantityOfNodes();
updateProfilerName();
CC_PROFILER_PURGE_ALL();
srand(0);
});
increase->setColor(Color3B(0,200,20));
_increase = increase;
auto menu = Menu::create(decrease, increase, NULL);
menu->alignItemsHorizontally();
menu->setPosition(Point(s.width/2, s.height/2+15));
addChild(menu, 1);
auto infoLabel = LabelTTF::create("0 listeners", "Marker Felt", 30);
infoLabel->setColor(Color3B(0,200,20));
infoLabel->setPosition(Point(s.width/2, s.height/2-15));
addChild(infoLabel, 1, kTagInfoLayer);
auto menuLayer = new EventDispatcherBasicLayer(true, MAX_LAYER, g_curCase);
addChild(menuLayer);
menuLayer->release();
printf("Size of Node: %lu\n", sizeof(Node));
int oldFontSize = MenuItemFont::getFontSize();
MenuItemFont::setFontSize(24);
Vector<cocos2d::MenuItem *> toggleItems;
generateTestFunctions();
CCASSERT(!_testFunctions.empty(), "Should not be empty after generate test functions");
for (const auto& f : _testFunctions)
{
toggleItems.pushBack(MenuItemFont::create(f.name));
}
auto reset = [this](){
// Removes all nodes
for (auto& node : _nodes)
{
node->removeFromParent();
}
_nodes.clear();
// Removes all fixed listeners
for (auto& listener : _fixedPriorityListeners)
{
Director::getInstance()->getEventDispatcher()->removeEventListener(listener);
}
this->_lastRenderedCount = 0;
};
auto toggle = MenuItemToggle::createWithCallback([=](Object* sender){
auto toggle = static_cast<MenuItemToggle*>(sender);
this->_type = toggle->getSelectedIndex();
auto label = static_cast<LabelTTF*>(this->getChildByTag(TAG_SUBTITLE));
label->setString(StringUtils::format("Test '%s', See console", this->_testFunctions[this->_type].name));
this->updateProfilerName();
reset();
}, toggleItems);
toggle->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT);
toggle->setPosition(VisibleRect::left());
_toggle = toggle;
auto start = MenuItemFont::create("start", [this](Object* sender){
auto director = Director::getInstance();
auto sched = director->getScheduler();
CC_PROFILER_PURGE_ALL();
sched->scheduleSelector(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this, 2, false);
this->unscheduleUpdate();
this->scheduleUpdate();
this->_startItem->setEnabled(false);
this->_stopItem->setEnabled(true);
this->_toggle->setEnabled(false);
this->_increase->setEnabled(false);
this->_decrease->setEnabled(false);
});
start->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT);
start->setPosition(VisibleRect::right() + Point(0, 40));
_startItem = start;
auto stop = MenuItemFont::create("stop", [=](Object* sender){
auto director = Director::getInstance();
auto sched = director->getScheduler();
sched->unscheduleSelector(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this);
this->unscheduleUpdate();
this->_startItem->setEnabled(true);
this->_stopItem->setEnabled(false);
this->_toggle->setEnabled(true);
this->_increase->setEnabled(true);
this->_decrease->setEnabled(true);
reset();
});
stop->setEnabled(false);
stop->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT);
stop->setPosition(VisibleRect::right() + Point(0, -40));
_stopItem = stop;
auto menu2 = Menu::create(toggle, start, stop, NULL);
menu2->setPosition(Point::ZERO);
addChild(menu2);
MenuItemFont::setFontSize(oldFontSize);
updateQuantityLabel();
updateQuantityOfNodes();
updateProfilerName();
}
std::string PerformanceEventDispatcherScene::title() const
{
return "No title";
}
std::string PerformanceEventDispatcherScene::subtitle() const
{
return "";
}
void PerformanceEventDispatcherScene::updateQuantityLabel()
{
if( _quantityOfNodes != _lastRenderedCount )
{
auto infoLabel = static_cast<LabelTTF*>( getChildByTag(kTagInfoLayer) );
char str[20] = {0};
sprintf(str, "%u listeners", _quantityOfNodes);
infoLabel->setString(str);
}
}
const char * PerformanceEventDispatcherScene::profilerName()
{
return _profilerName;
}
void PerformanceEventDispatcherScene::updateProfilerName()
{
snprintf(_profilerName, sizeof(_profilerName)-1, "%s(%d)", testName(), _quantityOfNodes);
}
void PerformanceEventDispatcherScene::dumpProfilerInfo(float dt)
{
CC_PROFILER_DISPLAY_TIMERS();
}
void PerformanceEventDispatcherScene::update(float dt)
{
_testFunctions[_type].func();
}
void PerformanceEventDispatcherScene::updateQuantityOfNodes()
{
_currentQuantityOfNodes = _quantityOfNodes;
}
const char* PerformanceEventDispatcherScene::testName()
{
return _testFunctions[_type].name;
}
////////////////////////////////////////////////////////
//
// TouchEventDispatchingPerfTest
//
////////////////////////////////////////////////////////
void TouchEventDispatchingPerfTest::generateTestFunctions()
{
TestFunction testFunctions[] = {
{ "OneByOne-scenegraph", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [](Touch* touch, Event* event){
return false;
};
listener->onTouchMoved = [](Touch* touch, Event* event){};
listener->onTouchEnded = [](Touch* touch, Event* event){};
// Create new touchable nodes
for (int i = 0; i < this->_quantityOfNodes; ++i)
{
auto node = Node::create();
node->setTag(1000 + i);
this->addChild(node);
this->_nodes.push_back(node);
dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node);
}
_lastRenderedCount = _quantityOfNodes;
}
Size size = Director::getInstance()->getWinSize();
EventTouch touchEvent;
touchEvent.setEventCode(EventTouch::EventCode::BEGAN);
std::vector<Touch*> touches;
for (int i = 0; i < 4; ++i)
{
Touch* touch = new Touch();
touch->autorelease();
touch->setTouchInfo(i, rand() % 200, rand() % 200);
touches.push_back(touch);
}
touchEvent.setTouches(touches);
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&touchEvent);
CC_PROFILER_STOP(this->profilerName());
} } ,
{ "OneByOne-fixed", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [](Touch* touch, Event* event){
return false;
};
listener->onTouchMoved = [](Touch* touch, Event* event){};
listener->onTouchEnded = [](Touch* touch, Event* event){};
for (int i = 0; i < this->_quantityOfNodes; ++i)
{
auto l = listener->clone();
this->_fixedPriorityListeners.push_back(l);
dispatcher->addEventListenerWithFixedPriority(l, i+1);
}
_lastRenderedCount = _quantityOfNodes;
}
Size size = Director::getInstance()->getWinSize();
EventTouch touchEvent;
touchEvent.setEventCode(EventTouch::EventCode::BEGAN);
std::vector<Touch*> touches;
for (int i = 0; i < 4; ++i)
{
Touch* touch = new Touch();
touch->autorelease();
touch->setTouchInfo(i, rand() % 200, rand() % 200);
touches.push_back(touch);
}
touchEvent.setTouches(touches);
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&touchEvent);
CC_PROFILER_STOP(this->profilerName());
} } ,
{ "AllAtOnce-scenegraph", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = [](const std::vector<Touch*> touches, Event* event){};
listener->onTouchesMoved = [](const std::vector<Touch*> touches, Event* event){};
listener->onTouchesEnded = [](const std::vector<Touch*> touches, Event* event){};
// Create new touchable nodes
for (int i = 0; i < this->_quantityOfNodes; ++i)
{
auto node = Node::create();
node->setTag(1000 + i);
this->addChild(node);
this->_nodes.push_back(node);
dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node);
}
_lastRenderedCount = _quantityOfNodes;
}
Size size = Director::getInstance()->getWinSize();
EventTouch touchEvent;
touchEvent.setEventCode(EventTouch::EventCode::BEGAN);
std::vector<Touch*> touches;
for (int i = 0; i < 4; ++i)
{
Touch* touch = new Touch();
touch->autorelease();
touch->setTouchInfo(i, rand() % 200, rand() % 200);
touches.push_back(touch);
}
touchEvent.setTouches(touches);
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&touchEvent);
CC_PROFILER_STOP(this->profilerName());
} } ,
{ "AllAtOnce-fixed", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = [](const std::vector<Touch*> touches, Event* event){};
listener->onTouchesMoved = [](const std::vector<Touch*> touches, Event* event){};
listener->onTouchesEnded = [](const std::vector<Touch*> touches, Event* event){};
for (int i = 0; i < this->_quantityOfNodes; ++i)
{
auto l = listener->clone();
this->_fixedPriorityListeners.push_back(l);
dispatcher->addEventListenerWithFixedPriority(l, i+1);
}
_lastRenderedCount = _quantityOfNodes;
}
Size size = Director::getInstance()->getWinSize();
EventTouch touchEvent;
touchEvent.setEventCode(EventTouch::EventCode::BEGAN);
std::vector<Touch*> touches;
for (int i = 0; i < 4; ++i)
{
Touch* touch = new Touch();
touch->autorelease();
touch->setTouchInfo(i, rand() % 200, rand() % 200);
touches.push_back(touch);
}
touchEvent.setTouches(touches);
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&touchEvent);
CC_PROFILER_STOP(this->profilerName());
} } ,
{ "TouchModeMix-scenegraph", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listenerOneByOne = EventListenerTouchOneByOne::create();
listenerOneByOne->onTouchBegan = [](Touch* touch, Event* event){
return false;
};
listenerOneByOne->onTouchMoved = [](Touch* touch, Event* event){};
listenerOneByOne->onTouchEnded = [](Touch* touch, Event* event){};
auto listenerAllAtOnce = EventListenerTouchAllAtOnce::create();
listenerAllAtOnce->onTouchesBegan = [](const std::vector<Touch*> touches, Event* event){};
listenerAllAtOnce->onTouchesMoved = [](const std::vector<Touch*> touches, Event* event){};
listenerAllAtOnce->onTouchesEnded = [](const std::vector<Touch*> touches, Event* event){};
int i = 0;
// Create new touchable nodes
for (; i < this->_quantityOfNodes/2; ++i)
{
auto node = Node::create();
node->setTag(1000 + i);
this->addChild(node);
this->_nodes.push_back(node);
dispatcher->addEventListenerWithSceneGraphPriority(listenerOneByOne->clone(), node);
}
for (; i < this->_quantityOfNodes; ++i)
{
auto node = Node::create();
node->setTag(1000 + i);
this->addChild(node);
this->_nodes.push_back(node);
dispatcher->addEventListenerWithSceneGraphPriority(listenerAllAtOnce->clone(), node);
}
_lastRenderedCount = _quantityOfNodes;
}
Size size = Director::getInstance()->getWinSize();
EventTouch touchEvent;
touchEvent.setEventCode(EventTouch::EventCode::BEGAN);
std::vector<Touch*> touches;
for (int i = 0; i < 4; ++i)
{
Touch* touch = new Touch();
touch->autorelease();
touch->setTouchInfo(i, rand() % 200, rand() % 200);
touches.push_back(touch);
}
touchEvent.setTouches(touches);
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&touchEvent);
CC_PROFILER_STOP(this->profilerName());
} } ,
{ "TouchModeMix-fixed", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listenerOneByOne = EventListenerTouchOneByOne::create();
listenerOneByOne->onTouchBegan = [](Touch* touch, Event* event){
return false;
};
listenerOneByOne->onTouchMoved = [](Touch* touch, Event* event){};
listenerOneByOne->onTouchEnded = [](Touch* touch, Event* event){};
auto listenerAllAtOnce = EventListenerTouchAllAtOnce::create();
listenerAllAtOnce->onTouchesBegan = [](const std::vector<Touch*> touches, Event* event){};
listenerAllAtOnce->onTouchesMoved = [](const std::vector<Touch*> touches, Event* event){};
listenerAllAtOnce->onTouchesEnded = [](const std::vector<Touch*> touches, Event* event){};
int i = 0;
for (; i < this->_quantityOfNodes/2; ++i)
{
auto l = listenerOneByOne->clone();
this->_fixedPriorityListeners.push_back(l);
dispatcher->addEventListenerWithFixedPriority(l, i+1);
}
for (; i < this->_quantityOfNodes; ++i)
{
auto l = listenerAllAtOnce->clone();
this->_fixedPriorityListeners.push_back(l);
dispatcher->addEventListenerWithFixedPriority(l, i+1);
}
_lastRenderedCount = _quantityOfNodes;
}
Size size = Director::getInstance()->getWinSize();
EventTouch touchEvent;
touchEvent.setEventCode(EventTouch::EventCode::BEGAN);
std::vector<Touch*> touches;
for (int i = 0; i < 4; ++i)
{
Touch* touch = new Touch();
touch->autorelease();
touch->setTouchInfo(i, rand() % 200, rand() % 200);
touches.push_back(touch);
}
touchEvent.setTouches(touches);
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&touchEvent);
CC_PROFILER_STOP(this->profilerName());
} } ,
};
for (const auto& func : testFunctions)
{
_testFunctions.push_back(func);
}
}
std::string TouchEventDispatchingPerfTest::title() const
{
return "Touch Event Dispatching Perf test";
}
std::string TouchEventDispatchingPerfTest::subtitle() const
{
return "Test 'OneByOne-scenegraph', See console";
}
////////////////////////////////////////////////////////
//
// KeyboardEventDispatchingPerfTest
//
////////////////////////////////////////////////////////
void KeyboardEventDispatchingPerfTest::generateTestFunctions()
{
TestFunction testFunctions[] = {
{ "keyboard-scenegraph", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){};
listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event){};
// Create new nodes listen to keyboard event
for (int i = 0; i < this->_quantityOfNodes; ++i)
{
auto node = Node::create();
node->setTag(1000 + i);
this->addChild(node);
this->_nodes.push_back(node);
dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node);
}
_lastRenderedCount = _quantityOfNodes;
}
EventKeyboard event(EventKeyboard::KeyCode::KEY_RETURN, true);
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&event);
CC_PROFILER_STOP(this->profilerName());
} } ,
{ "keyboard-fixed", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){};
listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event){};
for (int i = 0; i < this->_quantityOfNodes; ++i)
{
auto l = listener->clone();
this->_fixedPriorityListeners.push_back(l);
dispatcher->addEventListenerWithFixedPriority(l, i+1);
}
_lastRenderedCount = _quantityOfNodes;
}
EventKeyboard event(EventKeyboard::KeyCode::KEY_RETURN, true);
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&event);
CC_PROFILER_STOP(this->profilerName());
} } ,
};
for (const auto& func : testFunctions)
{
_testFunctions.push_back(func);
}
}
std::string KeyboardEventDispatchingPerfTest::title() const
{
return "Keyboard Event Dispatching Perf test";
}
std::string KeyboardEventDispatchingPerfTest::subtitle() const
{
return "Test 'keyboard-scenegraph', See console";
}
////////////////////////////////////////////////////////
//
// CustomEventDispatchingPerfTest
//
////////////////////////////////////////////////////////
void CustomEventDispatchingPerfTest::onEnter()
{
PerformanceEventDispatcherScene::onEnter();
for (int i = 0; i < 2000; i++)
{
auto listener = EventListenerCustom::create(StringUtils::format("custom_event_%d", i), [](EventCustom* event){});
_eventDispatcher->addEventListenerWithFixedPriority(listener, i + 1);
_customListeners.push_back(listener);
}
}
void CustomEventDispatchingPerfTest::onExit()
{
for (auto& l : _customListeners)
{
_eventDispatcher->removeEventListener(l);
}
PerformanceEventDispatcherScene::onExit();
}
void CustomEventDispatchingPerfTest::generateTestFunctions()
{
TestFunction testFunctions[] = {
{ "custom-scenegraph", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listener = EventListenerCustom::create("custom_event_test_scenegraph", [](EventCustom* event){});
// Create new nodes listen to custom event
for (int i = 0; i < this->_quantityOfNodes; ++i)
{
auto node = Node::create();
node->setTag(1000 + i);
this->addChild(node);
this->_nodes.push_back(node);
dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node);
}
_lastRenderedCount = _quantityOfNodes;
}
EventCustom event("custom_event_test_scenegraph");
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&event);
CC_PROFILER_STOP(this->profilerName());
} } ,
{ "custom-fixed", [=](){
auto dispatcher = Director::getInstance()->getEventDispatcher();
if (_quantityOfNodes != _lastRenderedCount)
{
auto listener = EventListenerCustom::create("custom_event_test_fixed", [](EventCustom* event){});
for (int i = 0; i < this->_quantityOfNodes; ++i)
{
auto l = listener->clone();
this->_fixedPriorityListeners.push_back(l);
dispatcher->addEventListenerWithFixedPriority(l, i+1);
}
_lastRenderedCount = _quantityOfNodes;
}
EventCustom event("custom_event_test_fixed");
CC_PROFILER_START(this->profilerName());
dispatcher->dispatchEvent(&event);
CC_PROFILER_STOP(this->profilerName());
} } ,
};
for (const auto& func : testFunctions)
{
_testFunctions.push_back(func);
}
}
std::string CustomEventDispatchingPerfTest::title() const
{
return "Custom Event Dispatching Perf test";
}
std::string CustomEventDispatchingPerfTest::subtitle() const
{
return "Test 'custom-scenegraph', See console";
}
///----------------------------------------
void runEventDispatcherPerformanceTest()
{
auto scene = createFunctions[g_curCase]();
scene->initWithQuantityOfNodes(kNodesIncrease);
Director::getInstance()->replaceScene(scene);
}

View File

@ -0,0 +1,106 @@
//
// PerformanceEventDispatcherTest.h
#ifndef __PERFORMANCE_EVENTDISPATCHER_TEST_H__
#define __PERFORMANCE_EVENTDISPATCHER_TEST_H__
#include "PerformanceTest.h"
#include "CCProfiling.h"
class EventDispatcherBasicLayer : public PerformBasicLayer
{
public:
EventDispatcherBasicLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0);
virtual void showCurrentTest();
};
class PerformanceEventDispatcherScene : public Scene
{
public:
static const int TAG_TITLE = 100;
static const int TAG_SUBTITLE = 101;
struct TestFunction
{
const char* name;
std::function<void()> func;
};
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void generateTestFunctions() = 0;
virtual std::string title() const;
virtual std::string subtitle() const;
virtual void updateQuantityOfNodes();
const char* profilerName();
void updateProfilerName();
// for the profiler
virtual const char* testName();
void updateQuantityLabel();
int getQuantityOfNodes() { return _quantityOfNodes; }
void dumpProfilerInfo(float dt);
// overrides
virtual void update(float dt) override;
protected:
char _profilerName[256];
int _lastRenderedCount;
int _quantityOfNodes;
int _currentQuantityOfNodes;
unsigned int _type;
std::vector<TestFunction> _testFunctions;
std::vector<Node*> _nodes;
std::vector<EventListener*> _fixedPriorityListeners;
MenuItemFont* _increase;
MenuItemFont* _decrease;
MenuItemFont* _startItem;
MenuItemFont* _stopItem;
MenuItemToggle* _toggle;
};
class TouchEventDispatchingPerfTest : public PerformanceEventDispatcherScene
{
public:
CREATE_FUNC(TouchEventDispatchingPerfTest);
virtual void generateTestFunctions() override;
virtual std::string title() const override;
virtual std::string subtitle() const override;
};
class KeyboardEventDispatchingPerfTest : public PerformanceEventDispatcherScene
{
public:
CREATE_FUNC(KeyboardEventDispatchingPerfTest);
virtual void generateTestFunctions() override;
virtual std::string title() const override;
virtual std::string subtitle() const override;
};
class CustomEventDispatchingPerfTest : public PerformanceEventDispatcherScene
{
public:
CREATE_FUNC(CustomEventDispatchingPerfTest);
virtual void onEnter() override;
virtual void onExit() override;
virtual void generateTestFunctions() override;
virtual std::string title() const override;
virtual std::string subtitle() const override;
private:
std::vector<EventListener*> _customListeners;
};
void runEventDispatcherPerformanceTest();
#endif /* defined(__PERFORMANCE_EVENTDISPATCHER_TEST_H__) */

View File

@ -397,15 +397,9 @@ void CallFuncsSpriteSheetForEach::update(float dt)
CC_PROFILER_START(this->profilerName());
#if CC_USE_ARRAY_VECTOR
std::for_each(std::begin(children), std::end(children), [](const RCPtr<Object>& obj) {
static_cast<Node*>( static_cast<Object*>(obj) )->getPosition();
});
#else
std::for_each(std::begin(children), std::end(children), [](Node* obj) {
obj->getPosition();
});
#endif
CC_PROFILER_STOP(this->profilerName());
}

View File

@ -9,6 +9,7 @@
#include "PerformanceLabelTest.h"
#include "PerformanceRendererTest.h"
#include "PerformanceContainerTest.h"
#include "PerformanceEventDispatcherTest.h"
enum
{
@ -29,7 +30,8 @@ struct {
{ "Touches Perf Test",[](Object*sender){runTouchesTest();} },
{ "Label Perf Test",[](Object*sender){runLabelTest();} },
{ "Renderer Perf Test",[](Object*sender){runRendererTest();} },
{ "Container Perf Test", [](Object* sender ) { runContainerPerformanceTest(); } }
{ "Container Perf Test", [](Object* sender ) { runContainerPerformanceTest(); } },
{ "EventDispatcher Perf Test", [](Object* sender ) { runEventDispatcherPerformanceTest(); } },
};
static const int g_testMax = sizeof(g_testsName)/sizeof(g_testsName[0]);

View File

@ -5,7 +5,21 @@ using namespace cocos2d;
class TestObject : public Object
{
public:
TestObject() : _name(""){}
TestObject(std::string name) : _name(name)
{
CCLOG("TestObject:%s is created", _name.c_str());
}
~TestObject()
{
if (_name.size() > 0)
CCLOG("TestObject:%s is destroyed", _name.c_str());
}
private:
std::string _name;
};
void ReleasePoolTestScene::runThisTest()
@ -17,19 +31,25 @@ void ReleasePoolTestScene::runThisTest()
// reference count should be added when added into auto release pool
TestObject *obj = new TestObject();
TestObject *obj = new TestObject("testobj");
obj->autorelease();
assert(obj->retainCount() == 1);
// should retain first before invoking autorelease
obj->retain();
obj->autorelease();
assert(obj->retainCount() == 2);
// can invoke autorelease more than once
obj->autorelease();
assert(obj->retainCount() == 3);
// create an autorelease pool in stack
{
AutoreleasePool pool1;
// can invoke autorelease more than once
obj->retain();
obj->autorelease();
assert(obj->retainCount() == 3);
obj->retain();
obj->autorelease();
assert(obj->retainCount() == 4);
@ -38,19 +58,23 @@ void ReleasePoolTestScene::runThisTest()
assert(obj->retainCount() == 5);
obj->release();
assert(obj->retainCount() == 4);
AutoreleasePool pool2;
for (int i = 0; i < 1000; ++i)
{
TestObject *tmpObj = new TestObject();
tmpObj->autorelease();
}
pool2.dump();
}
// pool is destroyed, so the release count is minused by one
assert(obj->retainCount() == 3);
assert(obj->retainCount() == 2);
// example of using temple autorelease pool
{
AutoreleasePool pool2;
char name[20];
for (int i = 0; i < 100; ++i)
{
snprintf(name, 20, "object%d", i);
TestObject *tmpObj = new TestObject(name);
tmpObj->autorelease();
}
}
// object in pool2 should be released
Director::getInstance()->replaceScene(this);
}

View File

@ -187,6 +187,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$
<ClCompile Include="..\Classes\NewRendererTest\NewRendererTest.cpp" />
<ClCompile Include="..\Classes\PerformanceTest\PerformanceAllocTest.cpp" />
<ClCompile Include="..\Classes\PerformanceTest\PerformanceContainerTest.cpp" />
<ClCompile Include="..\Classes\PerformanceTest\PerformanceEventDispatcherTest.cpp" />
<ClCompile Include="..\Classes\PerformanceTest\PerformanceLabelTest.cpp" />
<ClCompile Include="..\Classes\PerformanceTest\PerformanceRendererTest.cpp" />
<ClCompile Include="..\Classes\PhysicsTest\PhysicsTest.cpp" />
@ -336,6 +337,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$
<ClInclude Include="..\Classes\NewRendererTest\NewRendererTest.h" />
<ClInclude Include="..\Classes\PerformanceTest\PerformanceAllocTest.h" />
<ClInclude Include="..\Classes\PerformanceTest\PerformanceContainerTest.h" />
<ClInclude Include="..\Classes\PerformanceTest\PerformanceEventDispatcherTest.h" />
<ClInclude Include="..\Classes\PerformanceTest\PerformanceLabelTest.h" />
<ClInclude Include="..\Classes\PerformanceTest\PerformanceRendererTest.h" />
<ClInclude Include="..\Classes\PhysicsTest\PhysicsTest.h" />

View File

@ -727,6 +727,9 @@
<ClCompile Include="..\Classes\ReleasePoolTest\ReleasePoolTest.cpp">
<Filter>Classes\ReleasePoolTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\PerformanceTest\PerformanceEventDispatcherTest.cpp">
<Filter>Classes\PerformanceTest</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="main.h">
@ -1342,5 +1345,8 @@
<ClInclude Include="..\Classes\ReleasePoolTest\ReleasePoolTest.h">
<Filter>Classes\ReleasePoolTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\PerformanceTest\PerformanceEventDispatcherTest.h">
<Filter>Classes\PerformanceTest</Filter>
</ClInclude>
</ItemGroup>
</Project>

@ -1 +1 @@
Subproject commit 6fc3372cdfdbf39dd20bdcf1f60eb779773d32d7
Subproject commit ad6f6c781687b0dd471c4df53c0ba5925e43894d

View File

@ -59,7 +59,7 @@ def main():
except:
traceback.print_exc()
job_trigger_url = os.environ['JOB_TRIGGER_URL']+access_token
job_trigger_url = os.environ['JOB_TRIGGER_URL']
#send trigger and payload
post_data = {'payload':""}
post_data['payload']= payload_str

View File

@ -0,0 +1,88 @@
@echo off
:: This script is used to generate jsbinding glue codes.
:: You should modify PYTHON_ROOT and NDK_ROOT to work under your environment.
:: Android ndk version must be at least ndk-r9b.
set PYTHON_ROOT=C:/Python27
set NDK_ROOT=G:/android/android-ndk-r9b
set NDK_LLVM_ROOT=%NDK_ROOT%/toolchains/llvm-3.3/prebuilt/windows-x86_64
set COCOS2DX_ROOT=%cd%/../..
set "COCOS2DX_ROOT=%COCOS2DX_ROOT:\=/%"
set CXX_GENERATOR_ROOT=%COCOS2DX_ROOT%/tools/bindings-generator
set TO_JS_ROOT=%COCOS2DX_ROOT%/tools/tojs
set "CXX_GENERATOR_ROOT=%CXX_GENERATOR_ROOT:\=/%"
set OUTPUT_DIR=%COCOS2DX_ROOT%/scripting/auto-generated/js-bindings
set "OUTPUT_DIR=%OUTPUT_DIR:/=\%"
set PATH=%PATH%;%CXX_GENERATOR_ROOT%/libclang;%CXX_GENERATOR_ROOT%/tools/win32;%PYTHON_ROOT%
:: write userconf.ini
set _CONF_INI_FILE=%cd%\userconf.ini
if exist %_CONF_INI_FILE% del /Q %_CONF_INI_FILE%
echo
echo generating userconf.ini...
echo ---
echo [DEFAULT] > %_CONF_INI_FILE%
echo androidndkdir=%NDK_ROOT% >> %_CONF_INI_FILE%
echo clangllvmdir=%NDK_LLVM_ROOT% >> %_CONF_INI_FILE%
echo cocosdir=%COCOS2DX_ROOT% >> %_CONF_INI_FILE%
echo cxxgeneratordir=%CXX_GENERATOR_ROOT% >> %_CONF_INI_FILE%
:: fixme: to fix parse error, we must difine __WCHAR_MAX__ and undefine __MINGW32__ .
echo extra_flags=-D__WCHAR_MAX__=0x7fffffff -U__MINGW32__ >> %_CONF_INI_FILE%
echo ---
:: Generate bindings for cocos2dx
echo Generating bindings for cocos2dx...
python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx.ini -s cocos2d-x -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_extension..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_extension_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_builder..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o %OUTPUT_DIR% -n jsb_cocos2dx_builder_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_gui..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_gui_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_studio..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_studio_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_spine..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_spine_auto
if %errorlevel% neq 0 goto ERROR
:: Change the generated file format from DOS to UNIX.
pushd "%OUTPUT_DIR%"
dos2unix *
popd
echo ---------------------------------
echo Generating bindings succeeds.
echo ---------------------------------
goto QUIT
:ERROR
echo ---------------------------------
echo Generating bindings fails.
echo ---------------------------------
:QUIT
pause

View File

@ -1,4 +1,9 @@
#!/bin/bash
#
# Usage:
# export NDK_ROOT=/path/to/ndk-r9b
# ./genbindings.sh
#
# exit this script if any commmand fails
set -e
@ -6,10 +11,12 @@ set -e
# read user.cfg if it exists and is readable
_CFG_FILE=$(dirname "$0")"/user.cfg"
if [ -f "$_CFG_FILE" ]
if [ -f "$_CFG_FILE" ];
then
[ -r "$_CFG_FILE" ] || die "Fatal Error: $_CFG_FILE exists but is unreadable"
. "$_CFG_FILE"
if [ ! -r "$_CFG_FILE" ]; then
echo "Fatal Error: $_CFG_FILE exists but is unreadable"
exit 1
fi
fi
# paths
@ -19,11 +26,6 @@ if [ -z "${NDK_ROOT+aaa}" ]; then
NDK_ROOT="$HOME/bin/android-ndk"
fi
if [ -z "${CLANG_ROOT+aaa}" ]; then
# ... if CLANG_ROOT is not set, use "$HOME/bin/clang+llvm-3.3"
CLANG_ROOT="$HOME/bin/clang+llvm-3.3"
fi
if [ -z "${PYTHON_BIN+aaa}" ]; then
# ... if PYTHON_BIN is not set, use "/usr/bin/python2.7"
PYTHON_BIN="/usr/bin/python2.7"
@ -35,7 +37,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# paths with defaults hardcoded to relative paths
if [ -z "${COCOS2DX_ROOT+aaa}" ]; then
COCOS2DX_ROOT="$DIR/../../"
COCOS2DX_ROOT="$DIR/../.."
fi
if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then
@ -43,16 +45,59 @@ if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then
fi
if [ -z "${TOJS_ROOT+aaa}" ]; then
TO_JS_ROOT="$COCOS2DX_ROOT/tools/tojs"
TOJS_ROOT="$COCOS2DX_ROOT/tools/tojs"
fi
# set output dir
OUTPUT_DIR=${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings
echo "Paths"
echo " NDK_ROOT: $NDK_ROOT"
echo " CLANG_ROOT: $CLANG_ROOT"
echo " PYTHON_BIN: $PYTHON_BIN"
echo " COCOS2DX_ROOT: $COCOS2DX_ROOT"
echo " CXX_GENERATOR_ROOT: $CXX_GENERATOR_ROOT"
echo " TO_JS_ROOT: $TO_JS_ROOT"
echo " TOJS_ROOT: $TOJS_ROOT"
# check NDK version, must be r9b
if ! grep -q r9b $NDK_ROOT/RELEASE.TXT
then
echo " Fatal Error: NDK r9b must be required!"
exit 1
fi
# check clang include path
OS_NAME=$('uname')
NDK_LLVM_ROOT=$NDK_ROOT/toolchains/llvm-3.3/prebuilt
case "$OS_NAME" in
Darwin | darwin)
echo "in darwin"
if [ -d "$NDK_LLVM_ROOT/darwin-x86_64" ]; then
NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86_64
elif [ -d "$NDK_LLVM_ROOT/darwin-x86" ]; then
NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86
else
echo $NDK_LLVM_ROOT
echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3"
exit 1
fi
;;
Linux | linux)
echo "in linux"
if [ -d "$NDK_LLVM_ROOT/linux-x86_64" ]; then
NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86_64
elif [ -d "$NDK_LLVM_ROOT/linux-x86" ]; then
NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86
else
echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3"
exit 1
fi
;;
*)
echo " Fatal Error: Please run this script in linux or mac osx."
exit 1
;;
esac
# write userconf.ini
@ -65,7 +110,7 @@ fi
_CONTENTS=""
_CONTENTS+="[DEFAULT]"'\n'
_CONTENTS+="androidndkdir=$NDK_ROOT"'\n'
_CONTENTS+="clangllvmdir=$CLANG_ROOT"'\n'
_CONTENTS+="clangllvmdir=$NDK_LLVM_ROOT"'\n'
_CONTENTS+="cocosdir=$COCOS2DX_ROOT"'\n'
_CONTENTS+="cxxgeneratordir=$CXX_GENERATOR_ROOT"'\n'
_CONTENTS+="extra_flags="'\n'
@ -80,19 +125,20 @@ echo ---
# Generate bindings for cocos2dx
echo "Generating bindings for cocos2dx..."
set -x
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx.ini -s cocos2d-x -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_auto
echo "Generating bindings for cocos2dx_extension..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_extension_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_extension_auto
echo "Generating bindings for cocos2dx_builder..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_builder_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_builder_auto
echo "Generating bindings for cocos2dx_gui..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_gui_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_gui_auto
echo "Generating bindings for cocos2dx_studio..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_studio_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_studio_auto
echo "Generating bindings for cocos2dx_spine..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_spine_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_spine_auto

View File

@ -0,0 +1,89 @@
@echo off
:: This script is used to generate luabinding glue codes.
:: You should modify PYTHON_ROOT and NDK_ROOT to work under your environment.
:: Android ndk version must be at least ndk-r9b.
set PYTHON_ROOT=C:/Python27
set NDK_ROOT=G:/android/android-ndk-r9b
set NDK_LLVM_ROOT=%NDK_ROOT%/toolchains/llvm-3.3/prebuilt/windows-x86_64
set COCOS2DX_ROOT=%cd%/../..
set "COCOS2DX_ROOT=%COCOS2DX_ROOT:\=/%"
set CXX_GENERATOR_ROOT=%COCOS2DX_ROOT%/tools/bindings-generator
set TO_LUA_ROOT=%COCOS2DX_ROOT%/tools/tolua
set "CXX_GENERATOR_ROOT=%CXX_GENERATOR_ROOT:\=/%"
set OUTPUT_DIR=%COCOS2DX_ROOT%/scripting/auto-generated/lua-bindings
set "OUTPUT_DIR=%OUTPUT_DIR:/=\%"
set PATH=%PATH%;%CXX_GENERATOR_ROOT%/libclang;%CXX_GENERATOR_ROOT%/tools/win32;%PYTHON_ROOT%
:: write userconf.ini
set _CONF_INI_FILE=%cd%\userconf.ini
if exist %_CONF_INI_FILE% del /Q %_CONF_INI_FILE%
echo
echo generating userconf.ini...
echo ---
echo [DEFAULT] > %_CONF_INI_FILE%
echo androidndkdir=%NDK_ROOT% >> %_CONF_INI_FILE%
echo clangllvmdir=%NDK_LLVM_ROOT% >> %_CONF_INI_FILE%
echo cocosdir=%COCOS2DX_ROOT% >> %_CONF_INI_FILE%
echo cxxgeneratordir=%CXX_GENERATOR_ROOT% >> %_CONF_INI_FILE%
:: fixme: to fix parse error, we must difine __WCHAR_MAX__ and undefine __MINGW32__ .
echo extra_flags=-D__WCHAR_MAX__=0x7fffffff -U__MINGW32__ >> %_CONF_INI_FILE%
echo ---
:: Generate bindings for cocos2dx
echo Generating bindings for cocos2dx...
python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx.ini -s cocos2d-x -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_extension..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_extension_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_gui..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_gui_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_studio..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_studio_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_spine..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_spine_auto
if %errorlevel% neq 0 goto ERROR
echo "Generating bindings for cocos2dx_physics..."
python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_physics_auto
if %errorlevel% neq 0 goto ERROR
:: Change the generated file format from DOS to UNIX.
pushd "%OUTPUT_DIR%"
dos2unix *
popd
echo ---------------------------------
echo Generating bindings succeeds.
echo ---------------------------------
goto QUIT
:ERROR
echo ---------------------------------
echo Generating bindings fails.
echo ---------------------------------
:QUIT
pause

View File

@ -1,4 +1,9 @@
#!/bin/bash
#
# Usage:
# export NDK_ROOT=/path/to/ndk-r9b
# ./genbindings.sh
#
# exit this script if any commmand fails
set -e
@ -6,10 +11,12 @@ set -e
# read user.cfg if it exists and is readable
_CFG_FILE=$(dirname "$0")"/user.cfg"
if [ -f "$_CFG_FILE" ]
if [ -f "$_CFG_FILE" ];
then
[ -r "$_CFG_FILE" ] || die "Fatal Error: $_CFG_FILE exists but is unreadable"
. "$_CFG_FILE"
if [ ! -r "$_CFG_FILE" ]; then
echo "Fatal Error: $_CFG_FILE exists but is unreadable"
exit 1
fi
fi
# paths
@ -19,11 +26,6 @@ if [ -z "${NDK_ROOT+aaa}" ]; then
NDK_ROOT="$HOME/bin/android-ndk"
fi
if [ -z "${CLANG_ROOT+aaa}" ]; then
# ... if CLANG_ROOT is not set, use "$HOME/bin/clang+llvm-3.3"
CLANG_ROOT="$HOME/bin/clang+llvm-3.3"
fi
if [ -z "${PYTHON_BIN+aaa}" ]; then
# ... if PYTHON_BIN is not set, use "/usr/bin/python2.7"
PYTHON_BIN="/usr/bin/python2.7"
@ -35,24 +37,67 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# paths with defaults hardcoded to relative paths
if [ -z "${COCOS2DX_ROOT+aaa}" ]; then
COCOS2DX_ROOT="$DIR/../../"
COCOS2DX_ROOT="$DIR/../.."
fi
if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then
CXX_GENERATOR_ROOT="$COCOS2DX_ROOT/tools/bindings-generator"
fi
if [ -z "${TOJS_ROOT+aaa}" ]; then
TO_JS_ROOT="$COCOS2DX_ROOT/tools/tolua"
if [ -z "${TOLUA_ROOT+aaa}" ]; then
TOLUA_ROOT="$COCOS2DX_ROOT/tools/tolua"
fi
# set output dir
OUTPUT_DIR=${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings
echo "Paths"
echo " NDK_ROOT: $NDK_ROOT"
echo " CLANG_ROOT: $CLANG_ROOT"
echo " PYTHON_BIN: $PYTHON_BIN"
echo " COCOS2DX_ROOT: $COCOS2DX_ROOT"
echo " CXX_GENERATOR_ROOT: $CXX_GENERATOR_ROOT"
echo " TO_JS_ROOT: $TO_JS_ROOT"
echo " TOLUA_ROOT: $TOLUA_ROOT"
# check NDK version, must be r9b
if ! grep -q r9b $NDK_ROOT/RELEASE.TXT
then
echo " Fatal Error: NDK r9b must be required!"
exit 1
fi
# check clang include path
OS_NAME=$('uname')
NDK_LLVM_ROOT=$NDK_ROOT/toolchains/llvm-3.3/prebuilt
case "$OS_NAME" in
Darwin | darwin)
echo "in darwin"
if [ -d "$NDK_LLVM_ROOT/darwin-x86_64" ]; then
NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86_64
elif [ -d "$NDK_LLVM_ROOT/darwin-x86" ]; then
NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86
else
echo $NDK_LLVM_ROOT
echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3"
exit 1
fi
;;
Linux | linux)
echo "in linux"
if [ -d "$NDK_LLVM_ROOT/linux-x86_64" ]; then
NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86_64
elif [ -d "$NDK_LLVM_ROOT/linux-x86" ]; then
NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86
else
echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3"
exit 1
fi
;;
*)
echo " Fatal Error: Please run this script in linux or mac osx."
exit 1
;;
esac
# write userconf.ini
@ -65,7 +110,7 @@ fi
_CONTENTS=""
_CONTENTS+="[DEFAULT]"'\n'
_CONTENTS+="androidndkdir=$NDK_ROOT"'\n'
_CONTENTS+="clangllvmdir=$CLANG_ROOT"'\n'
_CONTENTS+="clangllvmdir=$NDK_LLVM_ROOT"'\n'
_CONTENTS+="cocosdir=$COCOS2DX_ROOT"'\n'
_CONTENTS+="cxxgeneratordir=$CXX_GENERATOR_ROOT"'\n'
_CONTENTS+="extra_flags="'\n'
@ -80,19 +125,20 @@ echo ---
# Generate bindings for cocos2dx
echo "Generating bindings for cocos2dx..."
set -x
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_auto
echo "Generating bindings for cocos2dx_extension..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_extension_auto
echo "Generating bindings for cocos2dx_gui..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_gui_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_gui_auto
echo "Generating bindings for cocos2dx_studio..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_studio_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_studio_auto
echo "Generating bindings for cocos2dx_spine..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_spine_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_spine_auto
echo "Generating bindings for cocos2dx_physics..."
LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_physics_auto
LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_physics_auto

View File

@ -6,9 +6,6 @@ set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
COCOS2DX_ROOT="$DIR"/../..
HOST_NAME=""
LLVM_VERSION=""
LLVM_PACKAGE=""
LLVM_PACKAGE_SUFFIX=""
mkdir -p $HOME/bin
cd $HOME/bin
@ -29,47 +26,6 @@ install_android_ndk()
mv android-ndk-r9b android-ndk
}
install_llvm()
{
LLVM_VERSION="3.3"
if [ "$PLATFORM"x = "ios"x ]; then
LLVM_PACKAGE="clang+llvm-3.3-x86_64-apple-darwin12"
LLVM_PACKAGE_SUFFIX=".tar.gz"
else
LLVM_PACKAGE="clang+llvm-3.3-Ubuntu-13.04-x86_64-linux-gnu"
LLVM_PACKAGE_SUFFIX=".tar.bz2"
fi
# Download llvm
echo "Download ${LLVM_PACKAGE} ..."
curl -O http://llvm.org/releases/${LLVM_VERSION}/${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX}
echo "Decompress ${LLVM_PACKAGE} ..."
if [ "$PLATFORM"x = "ios"x ]; then
tar xzf ${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX}
else
tar xjf ${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX}
fi
# Rename llvm
mv ${LLVM_PACKAGE} clang+llvm-${LLVM_VERSION}
}
install_llvm_3_2()
{
if [ "$PLATFORM"x = "ios"x ]; then
HOST_NAME="apple-darwin11"
else
HOST_NAME="linux-ubuntu-12.04"
fi
# Download llvm3.2
echo "Download clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz"
curl -O http://llvm.org/releases/3.2/clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz
echo "Decompress clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz ..."
tar xzf clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz
# Rename llvm
mv clang+llvm-3.2-x86_64-${HOST_NAME} clang+llvm-3.2
}
install_nacl_sdk()
{
# NaCl compilers are built for 32-bit linux so we need to install
@ -92,7 +48,6 @@ if [ "$GEN_JSB"x = "YES"x ]; then
exit 0
fi
install_android_ndk
install_llvm
elif [ "$PLATFORM"x = "linux"x ]; then
sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
# OpenMW team provides SDL2 package.
@ -104,19 +59,15 @@ elif [ "$PLATFORM"x = "linux"x ]; then
g++ --version
bash $COCOS2DX_ROOT/build/install-deps-linux.sh
install_android_ndk
install_llvm
elif [ "$PLATFORM"x = "nacl"x ]; then
install_nacl_sdk
elif [ "$PLATFORM"x = "android"x ]; then
install_android_ndk
install_llvm
elif [ "$PLATFORM"x = "emscripten"x ]; then
sudo rm -rf /dev/shm && sudo ln -s /run/shm /dev/shm
install_android_ndk
install_llvm_3_2
elif [ "$PLATFORM"x = "ios"x ]; then
install_android_ndk
install_llvm
pushd $COCOS2DX_ROOT
git submodule add https://github.com/facebook/xctool.git ./xctool
@ -127,3 +78,4 @@ else
echo "Unknown \$PLATFORM: '$PLATFORM'"
exit 1
fi