Merge branch 'develop' of git://github.com/cocos2d/cocos2d-x into new-spine

This commit is contained in:
James Chen 2013-12-20 20:11:41 +08:00
commit 0db2067f97
105 changed files with 1092 additions and 896 deletions

View File

@ -672,6 +672,9 @@ Developers:
yinkaile (2youyouo2) yinkaile (2youyouo2)
Maintainer of Armature Bone Animation. Maintainer of Armature Bone Animation.
dmurtagh
Fixed a bug that UserDefault::getDoubleForKey() doesn't pass default value to Java.
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang
Author of windows port, CCTextField, Author of windows port, CCTextField,

View File

@ -9,11 +9,13 @@ cocos2d-x-3.0beta0 ?? 2013
[FIX] Removed most hungarian notations. [FIX] Removed most hungarian notations.
[FIX] Merged NodeRGBA to Node. [FIX] Merged NodeRGBA to Node.
[NEW] New renderer support. [NEW] New renderer support.
[FIX] Potential hash collision fix.
[Android] [Android]
[NEW] build/android-build.sh: add supporting to generate .apk file [NEW] build/android-build.sh: add supporting to generate .apk file
[FIX] XMLHttpRequest receives wrong binary array. [FIX] XMLHttpRequest receives wrong binary array.
[NEW] Bindings-generator supports to bind 'unsigned long'. [NEW] Bindings-generator supports to bind 'unsigned long'.
[FIX] 'Test Frame Event' of TestJavascript/CocoStudioArmatureTest Crashes. [FIX] 'Test Frame Event' of TestJavascript/CocoStudioArmatureTest Crashes.
[FIX] UserDefault::getDoubleForKey() doesn't pass default value to Java.
[Windows] [Windows]
[NEW] CMake support for windows. [NEW] CMake support for windows.

View File

@ -1 +1 @@
97dc469fdca8c07ff75f357fbb9b56399336f307 86be6483df53eae247ab9679cc73e093e9b08f44

View File

@ -60,6 +60,7 @@ CCGLProgram.cpp \
ccGLStateCache.cpp \ ccGLStateCache.cpp \
CCGrabber.cpp \ CCGrabber.cpp \
CCGrid.cpp \ CCGrid.cpp \
CCNodeGrid.cpp \
CCIMEDispatcher.cpp \ CCIMEDispatcher.cpp \
CCLabel.cpp \ CCLabel.cpp \
CCLabelAtlas.cpp \ CCLabelAtlas.cpp \

View File

@ -25,6 +25,7 @@ THE SOFTWARE.
#include "CCActionGrid.h" #include "CCActionGrid.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCGrid.h" #include "CCGrid.h"
#include "CCNodeGrid.h"
NS_CC_BEGIN NS_CC_BEGIN
// implementation of GridAction // implementation of GridAction
@ -44,11 +45,11 @@ bool GridAction::initWithDuration(float duration, const Size& gridSize)
void GridAction::startWithTarget(Node *target) void GridAction::startWithTarget(Node *target)
{ {
ActionInterval::startWithTarget(target); ActionInterval::startWithTarget(target);
cacheTargetAsGridNode();
GridBase *newgrid = this->getGrid(); GridBase *newgrid = this->getGrid();
Node *t = _target; GridBase *targetGrid = _gridNodeTarget->getGrid();
GridBase *targetGrid = t->getGrid();
if (targetGrid && targetGrid->getReuseGrid() > 0) if (targetGrid && targetGrid->getReuseGrid() > 0)
{ {
@ -69,11 +70,17 @@ void GridAction::startWithTarget(Node *target)
targetGrid->setActive(false); targetGrid->setActive(false);
} }
t->setGrid(newgrid); _gridNodeTarget->setGrid(newgrid);
t->getGrid()->setActive(true); _gridNodeTarget->getGrid()->setActive(true);
} }
} }
void GridAction::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
GridAction* GridAction::reverse() const GridAction* GridAction::reverse() const
{ {
// FIXME: This conversion isn't safe. // FIXME: This conversion isn't safe.
@ -97,19 +104,19 @@ GridBase* Grid3DAction::getGrid()
Vertex3F Grid3DAction::getVertex(const Point& position) const Vertex3F Grid3DAction::getVertex(const Point& position) const
{ {
Grid3D *g = (Grid3D*)_target->getGrid(); Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
return g->getVertex(position); return g->getVertex(position);
} }
Vertex3F Grid3DAction::getOriginalVertex(const Point& position) const Vertex3F Grid3DAction::getOriginalVertex(const Point& position) const
{ {
Grid3D *g = (Grid3D*)_target->getGrid(); Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
return g->getOriginalVertex(position); return g->getOriginalVertex(position);
} }
void Grid3DAction::setVertex(const Point& position, const Vertex3F& vertex) void Grid3DAction::setVertex(const Point& position, const Vertex3F& vertex)
{ {
Grid3D *g = (Grid3D*)_target->getGrid(); Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
g->setVertex(position, vertex); g->setVertex(position, vertex);
} }
@ -122,19 +129,19 @@ GridBase* TiledGrid3DAction::getGrid(void)
Quad3 TiledGrid3DAction::getTile(const Point& pos) const Quad3 TiledGrid3DAction::getTile(const Point& pos) const
{ {
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->getTile(pos); return g->getTile(pos);
} }
Quad3 TiledGrid3DAction::getOriginalTile(const Point& pos) const Quad3 TiledGrid3DAction::getOriginalTile(const Point& pos) const
{ {
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->getOriginalTile(pos); return g->getOriginalTile(pos);
} }
void TiledGrid3DAction::setTile(const Point& pos, const Quad3& coords) void TiledGrid3DAction::setTile(const Point& pos, const Quad3& coords)
{ {
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->setTile(pos, coords); return g->setTile(pos, coords);
} }
@ -345,14 +352,20 @@ DeccelAmplitude* DeccelAmplitude::reverse() const
void StopGrid::startWithTarget(Node *target) void StopGrid::startWithTarget(Node *target)
{ {
ActionInstant::startWithTarget(target); ActionInstant::startWithTarget(target);
cacheTargetAsGridNode();
GridBase *grid = _target->getGrid(); GridBase *grid = _gridNodeTarget->getGrid();
if (grid && grid->isActive()) if (grid && grid->isActive())
{ {
grid->setActive(false); grid->setActive(false);
} }
} }
void StopGrid::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
StopGrid* StopGrid::create() StopGrid* StopGrid::create()
{ {
StopGrid* pAction = new StopGrid(); StopGrid* pAction = new StopGrid();
@ -402,13 +415,20 @@ bool ReuseGrid::initWithTimes(int times)
void ReuseGrid::startWithTarget(Node *target) void ReuseGrid::startWithTarget(Node *target)
{ {
ActionInstant::startWithTarget(target); ActionInstant::startWithTarget(target);
cacheTargetAsGridNode();
if (_target->getGrid() && _target->getGrid()->isActive()) if (_gridNodeTarget->getGrid() && _gridNodeTarget->getGrid()->isActive())
{ {
_target->getGrid()->setReuseGrid(_target->getGrid()->getReuseGrid() + _times); _gridNodeTarget->getGrid()->setReuseGrid(_gridNodeTarget->getGrid()->getReuseGrid() + _times);
} }
} }
void ReuseGrid::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
ReuseGrid* ReuseGrid::clone() const ReuseGrid* ReuseGrid::clone() const
{ {
return ReuseGrid::create(_times); return ReuseGrid::create(_times);

View File

@ -31,6 +31,7 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
class GridBase; class GridBase;
class NodeGrid;
/** /**
* @addtogroup actions * @addtogroup actions
@ -58,6 +59,10 @@ protected:
Size _gridSize; Size _gridSize;
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(GridAction); CC_DISALLOW_COPY_AND_ASSIGN(GridAction);
}; };
@ -265,6 +270,10 @@ protected:
StopGrid() {} StopGrid() {}
virtual ~StopGrid() {} virtual ~StopGrid() {}
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(StopGrid); CC_DISALLOW_COPY_AND_ASSIGN(StopGrid);
}; };
@ -287,6 +296,10 @@ protected:
/** initializes an action with the number of times that the current grid will be reused */ /** initializes an action with the number of times that the current grid will be reused */
bool initWithTimes(int times); bool initWithTimes(int times);
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
int _times; int _times;
private: private:

View File

@ -158,9 +158,9 @@ Vector<Node*> ActionManager::pauseAllRunningActions()
void ActionManager::resumeTargets(const Vector<Node*>& targetsToResume) void ActionManager::resumeTargets(const Vector<Node*>& targetsToResume)
{ {
std::for_each(targetsToResume.begin(), targetsToResume.end(), [this](Node* node){ for(const auto &node : targetsToResume) {
this->resumeTarget(node); this->resumeTarget(node);
}); }
} }
// run // run

View File

@ -26,6 +26,7 @@ THE SOFTWARE.
#include "CCDirector.h" #include "CCDirector.h"
#include "ccMacros.h" #include "ccMacros.h"
#include "CCGrid.h" #include "CCGrid.h"
#include "CCNodeGrid.h"
#include <stdlib.h> #include <stdlib.h>
NS_CC_BEGIN NS_CC_BEGIN
@ -279,7 +280,7 @@ void ShuffleTiles::placeTile(const Point& pos, Tile *t)
{ {
Quad3 coords = getOriginalTile(pos); Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep(); Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.x += (int)(t->position.x * step.x); coords.bl.x += (int)(t->position.x * step.x);
coords.bl.y += (int)(t->position.y * step.y); coords.bl.y += (int)(t->position.y * step.y);
@ -408,7 +409,7 @@ void FadeOutTRTiles::turnOffTile(const Point& pos)
void FadeOutTRTiles::transformTile(const Point& pos, float distance) void FadeOutTRTiles::transformTile(const Point& pos, float distance)
{ {
Quad3 coords = getOriginalTile(pos); Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep(); Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.x += (step.x / 2) * (1.0f - distance); coords.bl.x += (step.x / 2) * (1.0f - distance);
coords.bl.y += (step.y / 2) * (1.0f - distance); coords.bl.y += (step.y / 2) * (1.0f - distance);
@ -535,7 +536,7 @@ float FadeOutUpTiles::testFunc(const Size& pos, float time)
void FadeOutUpTiles::transformTile(const Point& pos, float distance) void FadeOutUpTiles::transformTile(const Point& pos, float distance)
{ {
Quad3 coords = getOriginalTile(pos); Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep(); Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.y += (step.y / 2) * (1.0f - distance); coords.bl.y += (step.y / 2) * (1.0f - distance);
coords.br.y += (step.y / 2) * (1.0f - distance); coords.br.y += (step.y / 2) * (1.0f - distance);

View File

@ -203,9 +203,9 @@ void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary)
version = properties.at("format").asInt(); version = properties.at("format").asInt();
const ValueVector& spritesheets = properties.at("spritesheets").asValueVector(); const ValueVector& spritesheets = properties.at("spritesheets").asValueVector();
std::for_each(spritesheets.cbegin(), spritesheets.cend(), [](const Value& value){ for(const auto &value : spritesheets) {
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString()); SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString());
}); }
} }
switch (version) { switch (version) {

View File

@ -41,9 +41,9 @@ static void setProgram(Node *n, GLProgram *p)
n->setShaderProgram(p); n->setShaderProgram(p);
auto& children = n->getChildren(); auto& children = n->getChildren();
std::for_each(children.begin(), children.end(), [p](Node* child){ for(const auto &child : children) {
setProgram(child, p); setProgram(child, p);
}); }
} }
ClippingNode::ClippingNode() ClippingNode::ClippingNode()

View File

@ -26,6 +26,7 @@ THE SOFTWARE.
#define __CC_FRAMEWORK_COMCONTAINER_H__ #define __CC_FRAMEWORK_COMCONTAINER_H__
#include "CCMap.h" #include "CCMap.h"
#include <string>
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -26,6 +26,10 @@
#include "CCEventTouch.h" #include "CCEventTouch.h"
#include "CCEventCustom.h" #include "CCEventCustom.h"
#include "CCEventListenerTouch.h" #include "CCEventListenerTouch.h"
#include "CCEventListenerAcceleration.h"
#include "CCEventListenerMouse.h"
#include "CCEventListenerKeyboard.h"
#include "CCNode.h" #include "CCNode.h"
#include "CCDirector.h" #include "CCDirector.h"
@ -59,31 +63,30 @@ private:
NS_CC_BEGIN NS_CC_BEGIN
static EventListener::ListenerID getListenerID(Event* event) static EventListener::ListenerID __getListenerID(Event* event)
{ {
EventListener::ListenerID ret; EventListener::ListenerID ret;
switch (event->getType()) switch (event->getType())
{ {
case Event::Type::ACCELERATION: case Event::Type::ACCELERATION:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::ACCELERATION); ret = EventListenerAcceleration::LISTENER_ID;
break; break;
case Event::Type::CUSTOM: case Event::Type::CUSTOM:
{ {
auto customEvent = static_cast<EventCustom*>(event); auto customEvent = static_cast<EventCustom*>(event);
auto listenerID = std::hash<std::string>()(customEvent->getEventName()); ret = customEvent->getEventName();
ret = static_cast<EventListener::ListenerID>(listenerID);
} }
break; break;
case Event::Type::KEYBOARD: case Event::Type::KEYBOARD:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::KEYBOARD); ret = EventListenerKeyboard::LISTENER_ID;
break; break;
case Event::Type::MOUSE: case Event::Type::MOUSE:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::MOUSE); ret = EventListenerMouse::LISTENER_ID;
break; break;
case Event::Type::TOUCH: case Event::Type::TOUCH:
// Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce.
// return UNKNOW instead. // return UNKNOWN instead.
ret = static_cast<EventListener::ListenerID>(EventListener::Type::UNKNOWN); CCASSERT(false, "Don't call this method if the event is for touch.");
break; break;
default: default:
CCASSERT(false, "Invalid type!"); CCASSERT(false, "Invalid type!");
@ -557,7 +560,7 @@ void EventDispatcher::dispatchEvent(Event* event)
return; return;
} }
auto listenerID = getListenerID(event); auto listenerID = __getListenerID(event);
sortEventListeners(listenerID); sortEventListeners(listenerID);
@ -580,14 +583,11 @@ void EventDispatcher::dispatchEvent(Event* event)
void EventDispatcher::dispatchTouchEvent(EventTouch* event) void EventDispatcher::dispatchTouchEvent(EventTouch* event)
{ {
auto touchOneByOneID = static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ONE_BY_ONE); sortEventListeners(EventListenerTouchOneByOne::LISTENER_ID);
auto touchAllAtOnceID = static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ALL_AT_ONCE); sortEventListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
sortEventListeners(touchOneByOneID); auto oneByOnelisteners = getListeners(EventListenerTouchOneByOne::LISTENER_ID);
sortEventListeners(touchAllAtOnceID); auto allAtOncelisteners = getListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
auto oneByOnelisteners = getListeners(touchOneByOneID);
auto allAtOncelisteners = getListeners(touchAllAtOnceID);
// If there aren't any touch listeners, return directly. // If there aren't any touch listeners, return directly.
if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners) if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners)
@ -776,7 +776,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event)
void EventDispatcher::updateListeners(Event* event) void EventDispatcher::updateListeners(Event* event)
{ {
auto onUpdateListeners = [this](EventListener::ListenerID listenerID) auto onUpdateListeners = [this](const EventListener::ListenerID& listenerID)
{ {
auto listenersIter = _listeners.find(listenerID); auto listenersIter = _listeners.find(listenerID);
if (listenersIter == _listeners.end()) if (listenersIter == _listeners.end())
@ -844,12 +844,12 @@ void EventDispatcher::updateListeners(Event* event)
if (event->getType() == Event::Type::TOUCH) if (event->getType() == Event::Type::TOUCH)
{ {
onUpdateListeners(static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ONE_BY_ONE)); onUpdateListeners(EventListenerTouchOneByOne::LISTENER_ID);
onUpdateListeners(static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ALL_AT_ONCE)); onUpdateListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
} }
else else
{ {
onUpdateListeners(getListenerID(event)); onUpdateListeners(__getListenerID(event));
} }
@ -907,7 +907,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph()
} }
} }
void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID) void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listenerID)
{ {
DirtyFlag dirtyFlag = DirtyFlag::NONE; DirtyFlag dirtyFlag = DirtyFlag::NONE;
@ -933,7 +933,7 @@ void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID)
} }
} }
void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID) void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID)
{ {
auto listeners = getListeners(listenerID); auto listeners = getListeners(listenerID);
@ -962,7 +962,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::List
#endif #endif
} }
void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID) void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID)
{ {
auto listeners = getListeners(listenerID); auto listeners = getListeners(listenerID);
@ -996,7 +996,7 @@ void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerI
} }
EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListener::ListenerID listenerID) EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventListener::ListenerID& listenerID)
{ {
auto iter = _listeners.find(listenerID); auto iter = _listeners.find(listenerID);
if (iter != _listeners.end()) if (iter != _listeners.end())
@ -1007,7 +1007,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListene
return nullptr; return nullptr;
} }
void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerID listenerID) void EventDispatcher::removeEventListenersForListenerID(const EventListener::ListenerID& listenerID)
{ {
auto listenerItemIter = _listeners.find(listenerID); auto listenerItemIter = _listeners.find(listenerID);
if (listenerItemIter != _listeners.end()) if (listenerItemIter != _listeners.end())
@ -1068,26 +1068,47 @@ void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerI
void EventDispatcher::removeEventListeners(EventListener::Type listenerType) void EventDispatcher::removeEventListeners(EventListener::Type listenerType)
{ {
CCASSERT(listenerType != EventListener::Type::CUSTOM, "Not support custom event listener type, please use EventDispatcher::removeCustomEventListeners instead."); if (listenerType == EventListener::Type::TOUCH_ONE_BY_ONE)
{
removeEventListenersForListenerID(static_cast<EventListener::ListenerID>(listenerType)); removeEventListenersForListenerID(EventListenerTouchOneByOne::LISTENER_ID);
}
else if (listenerType == EventListener::Type::TOUCH_ALL_AT_ONCE)
{
removeEventListenersForListenerID(EventListenerTouchAllAtOnce::LISTENER_ID);
}
else if (listenerType == EventListener::Type::MOUSE)
{
removeEventListenersForListenerID(EventListenerMouse::LISTENER_ID);
}
else if (listenerType == EventListener::Type::ACCELERATION)
{
removeEventListenersForListenerID(EventListenerAcceleration::LISTENER_ID);
}
else if (listenerType == EventListener::Type::KEYBOARD)
{
removeEventListenersForListenerID(EventListenerKeyboard::LISTENER_ID);
}
else
{
CCASSERT(false, "Invalid listener type!");
}
} }
void EventDispatcher::removeCustomEventListeners(const std::string& customEventName) void EventDispatcher::removeCustomEventListeners(const std::string& customEventName)
{ {
removeEventListenersForListenerID(std::hash<std::string>()(customEventName)); removeEventListenersForListenerID(customEventName);
} }
void EventDispatcher::removeAllEventListeners() void EventDispatcher::removeAllEventListeners()
{ {
std::vector<EventListener::ListenerID> types(_listeners.size()); std::vector<EventListener::ListenerID> types(_listeners.size());
for (auto iter = _listeners.begin(); iter != _listeners.end(); ++iter) for (const auto& e : _listeners)
{ {
types.push_back(iter->first); types.push_back(e.first);
} }
for (auto& type : types) for (const auto& type : types)
{ {
removeEventListenersForListenerID(type); removeEventListenersForListenerID(type);
} }
@ -1118,7 +1139,7 @@ void EventDispatcher::setDirtyForNode(Node* node)
} }
} }
void EventDispatcher::setDirty(EventListener::ListenerID listenerID, DirtyFlag flag) void EventDispatcher::setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag)
{ {
auto iter = _priorityDirtyFlagMap.find(listenerID); auto iter = _priorityDirtyFlagMap.find(listenerID);
if (iter == _priorityDirtyFlagMap.end()) if (iter == _priorityDirtyFlagMap.end())

View File

@ -148,22 +148,22 @@ private:
void addEventListener(EventListener* listener); void addEventListener(EventListener* listener);
/** Gets event the listener list for the event listener type. */ /** Gets event the listener list for the event listener type. */
EventListenerVector* getListeners(EventListener::ListenerID listenerID); EventListenerVector* getListeners(const EventListener::ListenerID& listenerID);
/** Update dirty flag */ /** Update dirty flag */
void updateDirtyFlagForSceneGraph(); void updateDirtyFlagForSceneGraph();
/** Removes all listeners with the same event listener ID */ /** Removes all listeners with the same event listener ID */
void removeEventListenersForListenerID(EventListener::ListenerID listenerID); void removeEventListenersForListenerID(const EventListener::ListenerID& listenerID);
/** Sort event listener */ /** Sort event listener */
void sortEventListeners(EventListener::ListenerID listenerID); void sortEventListeners(const EventListener::ListenerID& listenerID);
/** Sorts the listeners of specified type by scene graph priority */ /** Sorts the listeners of specified type by scene graph priority */
void sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID); void sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID);
/** Sorts the listeners of specified type by fixed priority */ /** Sorts the listeners of specified type by fixed priority */
void sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID); void sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID);
/** Updates all listeners /** Updates all listeners
* 1) Removes all listener items that have been marked as 'removed' when dispatching event. * 1) Removes all listener items that have been marked as 'removed' when dispatching event.
@ -193,7 +193,7 @@ private:
}; };
/** Sets the dirty flag for a specified listener ID */ /** Sets the dirty flag for a specified listener ID */
void setDirty(EventListener::ListenerID listenerID, DirtyFlag flag); void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag);
/** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */ /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */
void visitTarget(Node* node); void visitTarget(Node* node);

View File

@ -57,7 +57,7 @@ public:
CUSTOM CUSTOM
}; };
typedef std::size_t ListenerID; typedef std::string ListenerID;
protected: protected:
/** Constructor */ /** Constructor */
@ -83,7 +83,7 @@ protected:
inline bool isRegistered() const { return _isRegistered; }; inline bool isRegistered() const { return _isRegistered; };
inline Type getType() const { return _type; }; inline Type getType() const { return _type; };
inline ListenerID getListenerID() const { return _listenerID; }; inline const ListenerID& getListenerID() const { return _listenerID; };
inline void setFixedPriority(int fixedPriority) { _fixedPriority = fixedPriority; }; inline void setFixedPriority(int fixedPriority) { _fixedPriority = fixedPriority; };
inline int getFixedPriority() const { return _fixedPriority; }; inline int getFixedPriority() const { return _fixedPriority; };

View File

@ -27,6 +27,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const std::string EventListenerAcceleration::LISTENER_ID = "__cc_acceleration";
EventListenerAcceleration::EventListenerAcceleration() EventListenerAcceleration::EventListenerAcceleration()
{ {
@ -59,7 +61,7 @@ bool EventListenerAcceleration::init(std::function<void(Acceleration*, Event* ev
this->onAccelerationEvent(&accEvent->_acc, event); this->onAccelerationEvent(&accEvent->_acc, event);
}; };
if (EventListener::init(Type::ACCELERATION, static_cast<ListenerID>(Type::ACCELERATION), listener)) if (EventListener::init(Type::ACCELERATION, LISTENER_ID, listener))
{ {
onAccelerationEvent = callback; onAccelerationEvent = callback;
return true; return true;

View File

@ -33,6 +33,8 @@ NS_CC_BEGIN
class EventListenerAcceleration : public EventListener class EventListenerAcceleration : public EventListener
{ {
public: public:
static const std::string LISTENER_ID;
static EventListenerAcceleration* create(std::function<void(Acceleration*, Event*)> callback); static EventListenerAcceleration* create(std::function<void(Acceleration*, Event*)> callback);
virtual ~EventListenerAcceleration(); virtual ~EventListenerAcceleration();

View File

@ -35,7 +35,7 @@ EventListenerCustom::EventListenerCustom()
EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function<void(EventCustom*)> callback) EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function<void(EventCustom*)> callback)
{ {
EventListenerCustom* ret = new EventListenerCustom(); EventListenerCustom* ret = new EventListenerCustom();
if (ret && ret->init(std::hash<std::string>()(eventName), callback)) if (ret && ret->init(eventName, callback))
{ {
ret->autorelease(); ret->autorelease();
} }

View File

@ -29,6 +29,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const std::string EventListenerKeyboard::LISTENER_ID = "__cc_keyboard";
bool EventListenerKeyboard::checkAvailable() bool EventListenerKeyboard::checkAvailable()
{ {
if (onKeyPressed == nullptr && onKeyReleased == nullptr) if (onKeyPressed == nullptr && onKeyReleased == nullptr)
@ -92,7 +94,7 @@ bool EventListenerKeyboard::init()
} }
}; };
if (EventListener::init(Type::KEYBOARD, static_cast<ListenerID>(Type::KEYBOARD), listener)) if (EventListener::init(Type::KEYBOARD, LISTENER_ID, listener))
{ {
return true; return true;
} }

View File

@ -36,6 +36,8 @@ class Event;
class EventListenerKeyboard : public EventListener class EventListenerKeyboard : public EventListener
{ {
public: public:
static const std::string LISTENER_ID;
static EventListenerKeyboard* create(); static EventListenerKeyboard* create();
/// Overrides /// Overrides

View File

@ -27,6 +27,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const std::string EventListenerMouse::LISTENER_ID = "__cc_mouse";
bool EventListenerMouse::checkAvailable() bool EventListenerMouse::checkAvailable()
{ {
return true; return true;
@ -99,7 +101,7 @@ bool EventListenerMouse::init()
} }
}; };
if (EventListener::init(Type::MOUSE, static_cast<ListenerID>(Type::MOUSE), listener)) if (EventListener::init(Type::MOUSE, LISTENER_ID, listener))
{ {
return true; return true;
} }

View File

@ -36,6 +36,8 @@ class Event;
class EventListenerMouse : public EventListener class EventListenerMouse : public EventListener
{ {
public: public:
static const std::string LISTENER_ID;
static EventListenerMouse* create(); static EventListenerMouse* create();
/// Overrides /// Overrides

View File

@ -30,6 +30,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const std::string EventListenerTouchOneByOne::LISTENER_ID = "__cc_touch_one_by_one";
EventListenerTouchOneByOne::EventListenerTouchOneByOne() EventListenerTouchOneByOne::EventListenerTouchOneByOne()
: onTouchBegan(nullptr) : onTouchBegan(nullptr)
, onTouchMoved(nullptr) , onTouchMoved(nullptr)
@ -46,7 +48,7 @@ EventListenerTouchOneByOne::~EventListenerTouchOneByOne()
bool EventListenerTouchOneByOne::init() bool EventListenerTouchOneByOne::init()
{ {
if (EventListener::init(Type::TOUCH_ONE_BY_ONE, static_cast<ListenerID>(Type::TOUCH_ONE_BY_ONE), nullptr)) if (EventListener::init(Type::TOUCH_ONE_BY_ONE, LISTENER_ID, nullptr))
{ {
return true; return true;
} }
@ -107,6 +109,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::clone()
} }
///////// /////////
const std::string EventListenerTouchAllAtOnce::LISTENER_ID = "__cc_touch_all_at_once";
EventListenerTouchAllAtOnce::EventListenerTouchAllAtOnce() EventListenerTouchAllAtOnce::EventListenerTouchAllAtOnce()
: onTouchesBegan(nullptr) : onTouchesBegan(nullptr)
, onTouchesMoved(nullptr) , onTouchesMoved(nullptr)
@ -122,7 +127,7 @@ EventListenerTouchAllAtOnce::~EventListenerTouchAllAtOnce()
bool EventListenerTouchAllAtOnce::init() bool EventListenerTouchAllAtOnce::init()
{ {
if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, static_cast<ListenerID>(Type::TOUCH_ALL_AT_ONCE), nullptr)) if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, LISTENER_ID, nullptr))
{ {
return true; return true;
} }

View File

@ -36,6 +36,8 @@ NS_CC_BEGIN
class EventListenerTouchOneByOne : public EventListener class EventListenerTouchOneByOne : public EventListener
{ {
public: public:
static const std::string LISTENER_ID;
static EventListenerTouchOneByOne* create(); static EventListenerTouchOneByOne* create();
virtual ~EventListenerTouchOneByOne(); virtual ~EventListenerTouchOneByOne();
@ -67,7 +69,7 @@ private:
class EventListenerTouchAllAtOnce : public EventListener class EventListenerTouchAllAtOnce : public EventListener
{ {
public: public:
static const ListenerID ID = static_cast<ListenerID>(Type::TOUCH_ALL_AT_ONCE); static const std::string LISTENER_ID;
static EventListenerTouchAllAtOnce* create(); static EventListenerTouchAllAtOnce* create();
virtual ~EventListenerTouchAllAtOnce(); virtual ~EventListenerTouchAllAtOnce();

View File

@ -802,9 +802,9 @@ LayerMultiplex::LayerMultiplex()
LayerMultiplex::~LayerMultiplex() LayerMultiplex::~LayerMultiplex()
{ {
std::for_each(_layers.begin(), _layers.end(), [](Layer* layer){ for(const auto &layer : _layers) {
layer->cleanup(); layer->cleanup();
}); }
} }
LayerMultiplex * LayerMultiplex::create(Layer * layer, ...) LayerMultiplex * LayerMultiplex::create(Layer * layer, ...)

View File

@ -291,22 +291,15 @@ void Menu::alignItemsVerticallyWithPadding(float padding)
{ {
float height = -padding; float height = -padding;
std::for_each(_children.begin(), _children.end(), [&](Node* child){ for(const auto &child : _children)
if (child) height += child->getContentSize().height * child->getScaleY() + padding;
{
height += child->getContentSize().height * child->getScaleY() + padding;
}
});
float y = height / 2.0f; float y = height / 2.0f;
std::for_each(_children.begin(), _children.end(), [&](Node* child){ for(const auto &child : _children) {
if (child) child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f));
{ y -= child->getContentSize().height * child->getScaleY() + padding;
child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f)); }
y -= child->getContentSize().height * child->getScaleY() + padding;
}
});
} }
void Menu::alignItemsHorizontally(void) void Menu::alignItemsHorizontally(void)
@ -317,22 +310,15 @@ void Menu::alignItemsHorizontally(void)
void Menu::alignItemsHorizontallyWithPadding(float padding) void Menu::alignItemsHorizontallyWithPadding(float padding)
{ {
float width = -padding; float width = -padding;
std::for_each(_children.begin(), _children.end(), [&](Node* child){ for(const auto &child : _children)
if (child) width += child->getContentSize().width * child->getScaleX() + padding;
{
width += child->getContentSize().width * child->getScaleX() + padding;
}
});
float x = -width / 2.0f; float x = -width / 2.0f;
std::for_each(_children.begin(), _children.end(), [&](Node* child){ for(const auto &child : _children) {
if (child) child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0));
{ x += child->getContentSize().width * child->getScaleX() + padding;
child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0)); }
x += child->getContentSize().width * child->getScaleX() + padding;
}
});
} }
void Menu::alignItemsInColumns(int columns, ...) void Menu::alignItemsInColumns(int columns, ...)
@ -365,29 +351,26 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
int columnsOccupied = 0; int columnsOccupied = 0;
int rowColumns = 0; int rowColumns = 0;
std::for_each(_children.begin(), _children.end(), [&](Node* child){ for(const auto &child : _children) {
if (child) CCASSERT(row < rows.size(), "");
rowColumns = rows[row].asInt();
// can not have zero columns on a row
CCASSERT(rowColumns, "");
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{ {
CCASSERT(row < rows.size(), ""); height += rowHeight + 5;
rowColumns = rows[row].asInt(); columnsOccupied = 0;
// can not have zero columns on a row rowHeight = 0;
CCASSERT(rowColumns, ""); ++row;
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
height += rowHeight + 5;
columnsOccupied = 0;
rowHeight = 0;
++row;
}
} }
}); }
// check if too many rows/columns for available menu items // check if too many rows/columns for available menu items
CCASSERT(! columnsOccupied, ""); CCASSERT(! columnsOccupied, "");
@ -401,39 +384,33 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
float x = 0.0; float x = 0.0;
float y = (float)(height / 2); float y = (float)(height / 2);
std::for_each(_children.begin(), _children.end(), [&](Node* child){ for(const auto &child : _children) {
if (child) if (rowColumns == 0)
{ {
if (child) rowColumns = rows[row].asInt();
{ w = winSize.width / (1 + rowColumns);
if (rowColumns == 0) x = w;
{
rowColumns = rows[row].asInt();
w = winSize.width / (1 + rowColumns);
x = w;
}
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
child->setPosition(Point(x - winSize.width / 2,
y - child->getContentSize().height / 2));
x += w;
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
y -= rowHeight + 5;
columnsOccupied = 0;
rowColumns = 0;
rowHeight = 0;
++row;
}
}
} }
});
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
child->setPosition(Point(x - winSize.width / 2,
y - child->getContentSize().height / 2));
x += w;
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
y -= rowHeight + 5;
columnsOccupied = 0;
rowColumns = 0;
rowHeight = 0;
++row;
}
}
} }
void Menu::alignItemsInRows(int rows, ...) void Menu::alignItemsInRows(int rows, ...)
@ -469,36 +446,33 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
int rowsOccupied = 0; int rowsOccupied = 0;
int columnRows; int columnRows;
std::for_each(_children.begin(), _children.end(), [&](Node* child){ for(const auto &child : _children) {
if (child) // check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), "");
columnRows = columns[column].asInt();
// can't have zero rows on a column
CCASSERT(columnRows, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{ {
// check if too many menu items for the amount of rows/columns columnWidths.push_back(columnWidth);
CCASSERT(column < columns.size(), ""); columnHeights.push_back(columnHeight);
width += columnWidth + 10;
columnRows = columns[column].asInt(); rowsOccupied = 0;
// can't have zero rows on a column columnWidth = 0;
CCASSERT(columnRows, ""); columnHeight = -5;
++column;
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
columnWidths.push_back(columnWidth);
columnHeights.push_back(columnHeight);
width += columnWidth + 10;
rowsOccupied = 0;
columnWidth = 0;
columnHeight = -5;
++column;
}
} }
}); }
// check if too many rows/columns for available menu items. // check if too many rows/columns for available menu items.
CCASSERT(! rowsOccupied, ""); CCASSERT(! rowsOccupied, "");
@ -511,35 +485,32 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
float x = (float)(-width / 2); float x = (float)(-width / 2);
float y = 0.0; float y = 0.0;
std::for_each(_children.begin(), _children.end(), [&](Node* child){ for(const auto &child : _children) {
if (child) if (columnRows == 0)
{ {
if (columnRows == 0) columnRows = columns[column].asInt();
{ y = (float) columnHeights[column];
columnRows = columns[column].asInt();
y = (float) columnHeights[column];
}
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2));
y -= child->getContentSize().height + 10;
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
} }
});
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2));
y -= child->getContentSize().height + 10;
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
}
} }
MenuItem* Menu::getItemForTouch(Touch *touch) MenuItem* Menu::getItemForTouch(Touch *touch)

View File

@ -918,9 +918,9 @@ void MenuItemToggle::addSubItem(MenuItem *item)
MenuItemToggle::~MenuItemToggle() MenuItemToggle::~MenuItemToggle()
{ {
std::for_each(_subItems.begin(), _subItems.end(), [](MenuItem* item){ for(const auto &item : _subItems) {
item->cleanup(); item->cleanup();
}); }
} }
void MenuItemToggle::setSelectedIndex(unsigned int index) void MenuItemToggle::setSelectedIndex(unsigned int index)
@ -970,9 +970,9 @@ void MenuItemToggle::setEnabled(bool enabled)
{ {
MenuItem::setEnabled(enabled); MenuItem::setEnabled(enabled);
std::for_each(_subItems.begin(), _subItems.end(), [&enabled](MenuItem* item){ for(const auto &item : _subItems) {
item->setEnabled(enabled); item->setEnabled(enabled);
}); }
} }
} }

View File

@ -109,7 +109,6 @@ Node::Node(void)
, _camera(nullptr) , _camera(nullptr)
// children (lazy allocs) // children (lazy allocs)
// lazy alloc // lazy alloc
, _grid(nullptr)
, _ZOrder(0) , _ZOrder(0)
, _parent(nullptr) , _parent(nullptr)
// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
@ -171,7 +170,6 @@ Node::~Node()
// attributes // attributes
CC_SAFE_RELEASE(_camera); CC_SAFE_RELEASE(_camera);
CC_SAFE_RELEASE(_grid);
CC_SAFE_RELEASE(_shaderProgram); CC_SAFE_RELEASE(_shaderProgram);
CC_SAFE_RELEASE(_userObject); CC_SAFE_RELEASE(_userObject);
@ -415,15 +413,6 @@ Camera* Node::getCamera()
return _camera; return _camera;
} }
/// grid setter
void Node::setGrid(GridBase* grid)
{
CC_SAFE_RETAIN(grid);
CC_SAFE_RELEASE(_grid);
_grid = grid;
}
/// isVisible getter /// isVisible getter
bool Node::isVisible() const bool Node::isVisible() const
{ {
@ -823,11 +812,6 @@ void Node::visit()
kmGLPushMatrix(); kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
}
this->transform(); this->transform();
int i = 0; int i = 0;
@ -858,11 +842,6 @@ void Node::visit()
// reset for next frame // reset for next frame
_orderOfArrival = 0; _orderOfArrival = 0;
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix(); kmGLPopMatrix();
} }
@ -888,24 +867,9 @@ void Node::transform()
kmGLMultMatrix( &transfrom4x4 ); kmGLMultMatrix( &transfrom4x4 );
// saves the MV matrix // saves the MV matrix
kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewTransform); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewTransform);
// XXX: Expensive calls. Camera should be integrated into the cached affine matrix
if ( _camera != nullptr && !(_grid != nullptr && _grid->isActive()) )
{
bool translate = (_anchorPointInPoints.x != 0.0f || _anchorPointInPoints.y != 0.0f);
if( translate )
kmGLTranslatef(RENDER_IN_SUBPIXEL(_anchorPointInPoints.x), RENDER_IN_SUBPIXEL(_anchorPointInPoints.y), 0 );
_camera->locate();
if( translate )
kmGLTranslatef(RENDER_IN_SUBPIXEL(-_anchorPointInPoints.x), RENDER_IN_SUBPIXEL(-_anchorPointInPoints.y), 0 );
}
} }

View File

@ -703,33 +703,6 @@ public:
/// @} end of Children and Parent /// @} end of Children and Parent
/// @{
/// @name Grid object for effects
/**
* Returns a grid object that is used when applying effects
*
* @return A Grid object that is used when applying effects
* @js NA
*/
virtual GridBase* getGrid() { return _grid; }
/**
* @js NA
*/
virtual const GridBase* getGrid() const { return _grid; }
/**
* Changes a grid object that is used when applying effects
*
* @param grid A Grid object that is used when applying effects
*/
virtual void setGrid(GridBase *grid);
/// @} end of Grid
/// @{ /// @{
/// @name Tag & User data /// @name Tag & User data
@ -1466,8 +1439,6 @@ protected:
Camera *_camera; ///< a camera Camera *_camera; ///< a camera
GridBase *_grid; ///< a grid
int _ZOrder; ///< z-order value that affects the draw order int _ZOrder; ///< z-order value that affects the draw order
Vector<Node*> _children; ///< array of children nodes Vector<Node*> _children; ///< array of children nodes

160
cocos/2d/CCNodeGrid.cpp Normal file
View File

@ -0,0 +1,160 @@
#include "CCNodeGrid.h"
#include "CCGrid.h"
#include "CCGroupCommand.h"
#include "CCRenderer.h"
#include "CCCustomCommand.h"
NS_CC_BEGIN
NodeGrid* NodeGrid::create()
{
NodeGrid * ret = new NodeGrid();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
NodeGrid::NodeGrid()
: _nodeGrid(nullptr)
, _gridTarget(nullptr)
{
}
void NodeGrid::setTarget(Node* target)
{
CC_SAFE_RELEASE(_gridTarget);
CC_SAFE_RETAIN(target);
_gridTarget = target;
}
NodeGrid::~NodeGrid()
{
CC_SAFE_RELEASE(_nodeGrid);
CC_SAFE_RELEASE(_gridTarget);
}
bool NodeGrid::init()
{
return Node::init();
}
void NodeGrid::onGridBeginDraw()
{
if (_nodeGrid && _nodeGrid->isActive())
{
_nodeGrid->beforeDraw();
}
}
void NodeGrid::onGridEndDraw()
{
if(_nodeGrid && _nodeGrid->isActive())
{
_nodeGrid->afterDraw(this);
}
}
void NodeGrid::visit()
{
// quick return if not visible. children won't be drawn.
if (!_visible)
{
return;
}
Renderer* renderer = Director::getInstance()->getRenderer();
GroupCommand* groupCommand = GroupCommand::getCommandPool().generateCommand();
groupCommand->init(0,_vertexZ);
renderer->addCommand(groupCommand);
renderer->pushGroup(groupCommand->getRenderQueueID());
kmGLPushMatrix();
Director::Projection beforeProjectionType;
if(_nodeGrid && _nodeGrid->isActive())
{
beforeProjectionType = Director::getInstance()->getProjection();
_nodeGrid->set2DProjection();
}
kmGLGetMatrix(KM_GL_MODELVIEW, &_cachedMVmat);
CustomCommand* gridBeginCmd = CustomCommand::getCommandPool().generateCommand();
gridBeginCmd->init(0,_vertexZ);
gridBeginCmd->func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this);
renderer->addCommand(gridBeginCmd);
this->transform();
if(_gridTarget)
{
_gridTarget->visit();
}
int i = 0;
if(!_children.empty())
{
sortAllChildren();
// draw children zOrder < 0
for( ; i < _children.size(); i++ )
{
auto node = _children.at(i);
if ( node && node->getZOrder() < 0 )
node->visit();
else
break;
}
// self draw,currently we have nothing to draw on NodeGrid, so there is no need to add render command
this->draw();
// Uses std::for_each to improve performance.
std::for_each(_children.cbegin()+i, _children.cend(), [](Node* node){
node->visit();
});
}
else
{
this->draw();
}
// reset for next frame
_orderOfArrival = 0;
if(_nodeGrid && _nodeGrid->isActive())
{
// restore projection
Director *director = Director::getInstance();
director->setProjection(beforeProjectionType);
}
CustomCommand* gridEndCmd = CustomCommand::getCommandPool().generateCommand();
gridEndCmd->init(0,_vertexZ);
gridEndCmd->func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this);
renderer->addCommand(gridEndCmd);
renderer->popGroup();
kmGLPopMatrix();
}
void NodeGrid::setGrid(GridBase *grid)
{
CC_SAFE_RELEASE(_nodeGrid);
CC_SAFE_RETAIN(grid);
_nodeGrid = grid;
}
NS_CC_END

47
cocos/2d/CCNodeGrid.h Normal file
View File

@ -0,0 +1,47 @@
#ifndef __MISCNODE_CCGRID_NODE_H__
#define __MISCNODE_CCGRID_NODE_H__
#include "CCNode.h"
#include "kazmath/GL/matrix.h"
NS_CC_BEGIN
class GridBase;
class NodeGrid : public Node
{
public:
static NodeGrid* create();
GridBase* getGrid() { return _nodeGrid; }
/**
* @js NA
*/
const GridBase* getGrid() const { return _nodeGrid; }
/**
* Changes a grid object that is used when applying effects
*
* @param grid A Grid object that is used when applying effects
*/
void setGrid(GridBase *grid);
virtual bool init();
virtual void visit();
void setTarget(Node *target);
protected:
NodeGrid();
virtual ~NodeGrid();
void onGridBeginDraw();
void onGridEndDraw();
protected:
kmMat4 _cachedMVmat;
Node* _gridTarget;
GridBase* _nodeGrid;
};
NS_CC_END
#endif

View File

@ -135,21 +135,10 @@ void ParticleBatchNode::visit()
kmGLPushMatrix(); kmGLPushMatrix();
if ( _grid && _grid->isActive())
{
_grid->beforeDraw();
transformAncestors();
}
transform(); transform();
draw(); draw();
if ( _grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix(); kmGLPopMatrix();
} }
@ -385,9 +374,8 @@ void ParticleBatchNode::removeChildAtIndex(int index, bool doCleanup)
void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup) void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup)
{ {
std::for_each(_children.begin(), _children.end(), [](Node* child){ for(const auto &child : _children)
static_cast<ParticleSystem*>(child)->setBatchNode(nullptr); static_cast<ParticleSystem*>(child)->setBatchNode(nullptr);
});
Node::removeAllChildrenWithCleanup(doCleanup); Node::removeAllChildrenWithCleanup(doCleanup);
@ -481,11 +469,11 @@ void ParticleBatchNode::updateAllAtlasIndexes()
{ {
int index = 0; int index = 0;
std::for_each(_children.begin(), _children.end(), [&index](Node* child){ for(const auto &child : _children) {
ParticleSystem* partiSys = static_cast<ParticleSystem*>(child); ParticleSystem* partiSys = static_cast<ParticleSystem*>(child);
partiSys->setAtlasIndex(index); partiSys->setAtlasIndex(index);
index += partiSys->getTotalParticles(); index += partiSys->getTotalParticles();
}); }
} }
// ParticleBatchNode - CocosNodeTexture protocol // ParticleBatchNode - CocosNodeTexture protocol

View File

@ -457,21 +457,10 @@ void RenderTexture::visit()
kmGLPushMatrix(); kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
transformAncestors();
}
transform(); transform();
_sprite->visit(); _sprite->visit();
draw(); draw();
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix(); kmGLPopMatrix();
_orderOfArrival = 0; _orderOfArrival = 0;
@ -529,12 +518,12 @@ void RenderTexture::draw()
//! make sure all children are drawn //! make sure all children are drawn
sortAllChildren(); sortAllChildren();
std::for_each(_children.begin(), _children.end(), [this](Node* child){ for(const auto &child : _children) {
if (child != _sprite) if (child != _sprite)
{ {
child->visit(); child->visit();
} }
}); }
end(); end();
} }

View File

@ -146,9 +146,9 @@ void Scene::addChildToPhysicsWorld(Node* child)
} }
auto& children = node->getChildren(); auto& children = node->getChildren();
std::for_each(children.begin(), children.end(), [addToPhysicsWorldFunc](Node* n){ for( const auto &n : children) {
addToPhysicsWorldFunc(n); addToPhysicsWorldFunc(n);
}); }
}; };
addToPhysicsWorldFunc(child); addToPhysicsWorldFunc(child);

View File

@ -809,9 +809,9 @@ Vector<Object*> Scheduler::pauseAllTargetsWithMinPriority(int minPriority)
void Scheduler::resumeTargets(const Vector<Object*>& targetsToResume) void Scheduler::resumeTargets(const Vector<Object*>& targetsToResume)
{ {
std::for_each(targetsToResume.begin(), targetsToResume.end(), [this](Object* obj){ for(const auto &obj : targetsToResume) {
this->resumeTarget(obj); this->resumeTarget(obj);
}); }
} }
void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function) void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function)

View File

@ -528,7 +528,7 @@ void Sprite::updateTransform(void)
CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite"); CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite");
kmMat4 nodeToParent = getNodeToParentTransform(); kmMat4 nodeToParent = getNodeToParentTransform();
kmMat4 parentTransform = static_cast<Sprite*>(_parent)->_transformToBatch; kmMat4 parentTransform = static_cast<Sprite*>(_parent)->_transformToBatch;
kmMat4Multiply(&_transformToBatch, &nodeToParent, &parentTransform); kmMat4Multiply(&_transformToBatch, &parentTransform, &nodeToParent);
} }
// //

View File

@ -146,22 +146,11 @@ void SpriteBatchNode::visit(void)
kmGLPushMatrix(); kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
transformAncestors();
}
sortAllChildren(); sortAllChildren();
transform(); transform();
draw(); draw();
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix(); kmGLPopMatrix();
setOrderOfArrival(0); setOrderOfArrival(0);
@ -225,9 +214,9 @@ void SpriteBatchNode::removeAllChildrenWithCleanup(bool doCleanup)
{ {
// Invalidate atlas index. issue #569 // Invalidate atlas index. issue #569
// useSelfRender should be performed on all descendants. issue #1216 // useSelfRender should be performed on all descendants. issue #1216
std::for_each(_descendants.begin(), _descendants.end(), [](Sprite* sprite) { for(const auto &sprite: _descendants) {
sprite->setBatchNode(nullptr); sprite->setBatchNode(nullptr);
}); }
Node::removeAllChildrenWithCleanup(doCleanup); Node::removeAllChildrenWithCleanup(doCleanup);
@ -240,48 +229,24 @@ void SpriteBatchNode::sortAllChildren()
{ {
if (_reorderChildDirty) if (_reorderChildDirty)
{ {
#if 0
int i = 0,j = 0,length = _children->count();
// insertion sort
for(i=1; i<length; i++)
{
j = i-1;
auto tempI = static_cast<Node*>( _children->getObjectAtIndex(i) );
auto tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() ||
( tempI->getZOrder() == tempJ->getZOrder() &&
tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) )
{
_children->fastSetObject( tempJ, j+1 );
j = j-1;
if(j>=0)
tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
}
_children->fastSetObject(tempI, j+1);
}
#else
std::sort(std::begin(_children), std::end(_children), nodeComparisonLess); std::sort(std::begin(_children), std::end(_children), nodeComparisonLess);
#endif
//sorted now check all children //sorted now check all children
if (!_children.empty()) if (!_children.empty())
{ {
//first sort all children recursively based on zOrder //first sort all children recursively based on zOrder
std::for_each(_children.begin(), _children.end(), [](Node* child){ for(const auto &child: _children) {
child->sortAllChildren(); child->sortAllChildren();
}); }
ssize_t index=0; ssize_t index=0;
//fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact) //fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact)
// and at the same time reorder descendants and the quads to the right index // and at the same time reorder descendants and the quads to the right index
std::for_each(_children.begin(), _children.end(), [this, &index](Node* child){ for(const auto &child: _children) {
Sprite* sp = static_cast<Sprite*>(child); Sprite* sp = static_cast<Sprite*>(child);
updateAtlasIndex(sp, &index); updateAtlasIndex(sp, &index);
}); }
} }
_reorderChildDirty=false; _reorderChildDirty=false;
@ -324,7 +289,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex)
needNewIndex = false; needNewIndex = false;
} }
std::for_each(array.begin(), array.end(), [&](Node* child){ for(const auto &child: array) {
Sprite* sp = static_cast<Sprite*>(child); Sprite* sp = static_cast<Sprite*>(child);
if (needNewIndex && sp->getZOrder() >= 0) if (needNewIndex && sp->getZOrder() >= 0)
{ {
@ -339,7 +304,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex)
} }
updateAtlasIndex(sp, curIndex); updateAtlasIndex(sp, curIndex);
}); }
if (needNewIndex) if (needNewIndex)
{//all children have a zOrder < 0) {//all children have a zOrder < 0)
@ -390,9 +355,9 @@ void SpriteBatchNode::draw(void)
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
std::for_each(_children.begin(), _children.end(), [](Node* child){ for(const auto &child: _children) {
child->updateTransform(); child->updateTransform();
}); }
GL::blendFunc( _blendFunc.src, _blendFunc.dst ); GL::blendFunc( _blendFunc.src, _blendFunc.dst );
@ -425,14 +390,13 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index)
CCASSERT(index>=0 && index < _children.size(), "Invalid index"); CCASSERT(index>=0 && index < _children.size(), "Invalid index");
auto& children = parent->getChildren(); auto& children = parent->getChildren();
for(const auto &child: children) {
std::for_each(children.begin(), children.end(), [this, &index](Node* child){
Sprite* sp = static_cast<Sprite*>(child); Sprite* sp = static_cast<Sprite*>(child);
if (sp && (sp->getZOrder() < 0)) if (sp && (sp->getZOrder() < 0))
{ {
index = rebuildIndexInOrder(sp, index); index = rebuildIndexInOrder(sp, index);
} }
}); }
// ignore self (batch node) // ignore self (batch node)
if (! parent->isEqual(this)) if (! parent->isEqual(this))
@ -441,13 +405,13 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index)
index++; index++;
} }
std::for_each(children.begin(), children.end(), [this, &index](Node* child){ for(const auto &child: children) {
Sprite* sp = static_cast<Sprite*>(child); Sprite* sp = static_cast<Sprite*>(child);
if (sp && (sp->getZOrder() >= 0)) if (sp && (sp->getZOrder() >= 0))
{ {
index = rebuildIndexInOrder(sp, index); index = rebuildIndexInOrder(sp, index);
} }
}); }
return index; return index;
} }
@ -560,9 +524,9 @@ void SpriteBatchNode::appendChild(Sprite* sprite)
// add children recursively // add children recursively
auto& children = sprite->getChildren(); auto& children = sprite->getChildren();
std::for_each(children.begin(), children.end(), [this](Node* child){ for(const auto &child: children) {
appendChild(static_cast<Sprite*>(child)); appendChild(static_cast<Sprite*>(child));
}); }
} }
void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite) void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
@ -578,22 +542,23 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
{ {
auto next = std::next(it); auto next = std::next(it);
std::for_each(next, _descendants.end(), [](Sprite *spr) { for(; next != _descendants.end(); ++next) {
Sprite *spr = *next;
spr->setAtlasIndex( spr->getAtlasIndex() - 1 ); spr->setAtlasIndex( spr->getAtlasIndex() - 1 );
}); }
_descendants.erase(it); _descendants.erase(it);
} }
// remove children recursively // remove children recursively
auto& children = sprite->getChildren(); auto& children = sprite->getChildren();
std::for_each(children.begin(), children.end(), [this](Node* obj){ for(const auto &obj: children) {
Sprite* child = static_cast<Sprite*>(obj); Sprite* child = static_cast<Sprite*>(obj);
if (child) if (child)
{ {
removeSpriteFromAtlas(child); removeSpriteFromAtlas(child);
} }
}); }
} }
void SpriteBatchNode::updateBlendFunc(void) void SpriteBatchNode::updateBlendFunc(void)
@ -686,10 +651,10 @@ SpriteBatchNode * SpriteBatchNode::addSpriteWithoutQuad(Sprite*child, int z, int
// XXX: optimize with a binary search // XXX: optimize with a binary search
auto it = std::begin(_descendants); auto it = std::begin(_descendants);
std::for_each(_descendants.begin(), _descendants.end(), [&](Sprite *sprite) { for(const auto &sprite: _descendants) {
if(sprite->getAtlasIndex() >= z) if(sprite->getAtlasIndex() >= z)
std::next(it); std::next(it);
}); }
_descendants.insert(it, child); _descendants.insert(it, child);

View File

@ -172,7 +172,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Textu
// get aliases // get aliases
ValueVector& aliases = frameDict["aliases"].asValueVector(); ValueVector& aliases = frameDict["aliases"].asValueVector();
std::for_each(aliases.cbegin(), aliases.cend(), [this, &spriteFrameName](const Value& value){ for(const auto &value : aliases) {
std::string oneAlias = value.asString(); std::string oneAlias = value.asString();
if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end()) if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
{ {
@ -180,7 +180,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Textu
} }
_spriteFramesAliases[oneAlias] = Value(spriteFrameName); _spriteFramesAliases[oneAlias] = Value(spriteFrameName);
}); }
// create frame // create frame
spriteFrame = new SpriteFrame(); spriteFrame = new SpriteFrame();

View File

@ -389,17 +389,14 @@ Sprite * TMXLayer::insertTileForGID(unsigned int gid, const Point& pos)
// update possible children // update possible children
std::for_each(_children.begin(), _children.end(), [&indexForZ](Node* child){ for(const auto &child : _children) {
Sprite* sp = static_cast<Sprite*>(child); Sprite* sp = static_cast<Sprite*>(child);
if (child) ssize_t ai = sp->getAtlasIndex();
if ( ai >= indexForZ )
{ {
ssize_t ai = sp->getAtlasIndex(); sp->setAtlasIndex(ai+1);
if ( ai >= indexForZ )
{
sp->setAtlasIndex(ai+1);
}
} }
}); }
_tiles[z] = gid; _tiles[z] = gid;
return tile; return tile;
@ -594,17 +591,14 @@ void TMXLayer::removeTileAt(const Point& pos)
_textureAtlas->removeQuadAtIndex(atlasIndex); _textureAtlas->removeQuadAtIndex(atlasIndex);
// update possible children // update possible children
std::for_each(_children.begin(), _children.end(), [&atlasIndex](Node* obj){ for(const auto &obj : _children) {
Sprite* child = static_cast<Sprite*>(obj); Sprite* child = static_cast<Sprite*>(obj);
if (child) ssize_t ai = child->getAtlasIndex();
if ( ai >= atlasIndex )
{ {
ssize_t ai = child->getAtlasIndex(); child->setAtlasIndex(ai-1);
if ( ai >= atlasIndex )
{
child->setAtlasIndex(ai-1);
}
} }
}); }
} }
} }
} }

View File

@ -169,8 +169,8 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
int idx=0; int idx=0;
auto& layers = mapInfo->getLayers(); auto& layers = mapInfo->getLayers();
std::for_each(layers.begin(), layers.end(), [&idx, this, &mapInfo](TMXLayerInfo* layerInfo){ for(const auto &layerInfo : layers) {
if (layerInfo && layerInfo->_visible) if (layerInfo->_visible)
{ {
TMXLayer *child = parseLayer(layerInfo, mapInfo); TMXLayer *child = parseLayer(layerInfo, mapInfo);
addChild((Node*)child, idx, idx); addChild((Node*)child, idx, idx);
@ -184,7 +184,7 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
idx++; idx++;
} }
}); }
} }
// public // public

View File

@ -35,6 +35,8 @@ THE SOFTWARE.
#include "CCActionGrid.h" #include "CCActionGrid.h"
#include "CCLayer.h" #include "CCLayer.h"
#include "CCRenderTexture.h" #include "CCRenderTexture.h"
#include "CCNodeGrid.h"
#include "CCNewRenderTexture.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -1256,7 +1258,7 @@ TransitionCrossFade* TransitionCrossFade::create(float t, Scene* scene)
return nullptr; return nullptr;
} }
void TransitionCrossFade:: draw() void TransitionCrossFade::draw()
{ {
// override draw since both scenes (textures) are rendered in 1 scene // override draw since both scenes (textures) are rendered in 1 scene
} }
@ -1272,7 +1274,7 @@ void TransitionCrossFade::onEnter()
LayerColor* layer = LayerColor::create(color); LayerColor* layer = LayerColor::create(color);
// create the first render texture for inScene // create the first render texture for inScene
RenderTexture* inTexture = RenderTexture::create((int)size.width, (int)size.height); RenderTexture* inTexture = NewRenderTexture::create((int)size.width, (int)size.height);
if (nullptr == inTexture) if (nullptr == inTexture)
{ {
@ -1289,7 +1291,7 @@ void TransitionCrossFade::onEnter()
inTexture->end(); inTexture->end();
// create the second render texture for outScene // create the second render texture for outScene
RenderTexture* outTexture = RenderTexture::create((int)size.width, (int)size.height); RenderTexture* outTexture = NewRenderTexture::create((int)size.width, (int)size.height);
outTexture->getSprite()->setAnchorPoint( Point(0.5f,0.5f) ); outTexture->getSprite()->setAnchorPoint( Point(0.5f,0.5f) );
outTexture->setPosition( Point(size.width/2, size.height/2) ); outTexture->setPosition( Point(size.width/2, size.height/2) );
outTexture->setAnchorPoint( Point(0.5f,0.5f) ); outTexture->setAnchorPoint( Point(0.5f,0.5f) );
@ -1346,10 +1348,13 @@ void TransitionCrossFade::onExit()
// //
TransitionTurnOffTiles::TransitionTurnOffTiles() TransitionTurnOffTiles::TransitionTurnOffTiles()
{ {
_outSceneProxy = NodeGrid::create();
_outSceneProxy->retain();
} }
TransitionTurnOffTiles::~TransitionTurnOffTiles() TransitionTurnOffTiles::~TransitionTurnOffTiles()
{ {
CC_SAFE_RELEASE(_outSceneProxy);
} }
TransitionTurnOffTiles* TransitionTurnOffTiles::create(float t, Scene* scene) TransitionTurnOffTiles* TransitionTurnOffTiles::create(float t, Scene* scene)
@ -1373,6 +1378,9 @@ void TransitionTurnOffTiles::sceneOrder()
void TransitionTurnOffTiles::onEnter() void TransitionTurnOffTiles::onEnter()
{ {
TransitionScene::onEnter(); TransitionScene::onEnter();
_outSceneProxy->setTarget(_outScene);
_outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize(); Size s = Director::getInstance()->getWinSize();
float aspect = s.width / s.height; float aspect = s.width / s.height;
int x = (int)(12 * aspect); int x = (int)(12 * aspect);
@ -1380,7 +1388,7 @@ void TransitionTurnOffTiles::onEnter()
TurnOffTiles* toff = TurnOffTiles::create(_duration, Size(x,y)); TurnOffTiles* toff = TurnOffTiles::create(_duration, Size(x,y));
ActionInterval* action = easeActionWithAction(toff); ActionInterval* action = easeActionWithAction(toff);
_outScene->runAction _outSceneProxy->runAction
( (
Sequence::create Sequence::create
( (
@ -1392,6 +1400,29 @@ void TransitionTurnOffTiles::onEnter()
); );
} }
void TransitionTurnOffTiles::onExit()
{
_outSceneProxy->setTarget(nullptr);
_outSceneProxy->onExit();
TransitionScene::onExit();
}
void TransitionTurnOffTiles::draw()
{
Scene::draw();
if( _isInSceneOnTop )
{
_outSceneProxy->visit();
_inScene->visit();
}
else
{
_inScene->visit();
_outSceneProxy->visit();
}
}
ActionInterval* TransitionTurnOffTiles:: easeActionWithAction(ActionInterval* action) ActionInterval* TransitionTurnOffTiles:: easeActionWithAction(ActionInterval* action)
{ {
@ -1403,9 +1434,12 @@ ActionInterval* TransitionTurnOffTiles:: easeActionWithAction(ActionInterval* ac
// //
TransitionSplitCols::TransitionSplitCols() TransitionSplitCols::TransitionSplitCols()
{ {
_gridProxy = NodeGrid::create();
_gridProxy->retain();
} }
TransitionSplitCols::~TransitionSplitCols() TransitionSplitCols::~TransitionSplitCols()
{ {
CC_SAFE_RELEASE(_gridProxy);
} }
TransitionSplitCols* TransitionSplitCols::create(float t, Scene* scene) TransitionSplitCols* TransitionSplitCols::create(float t, Scene* scene)
@ -1423,18 +1457,20 @@ TransitionSplitCols* TransitionSplitCols::create(float t, Scene* scene)
void TransitionSplitCols::onEnter() void TransitionSplitCols::onEnter()
{ {
TransitionScene::onEnter(); TransitionScene::onEnter();
_inScene->setVisible(false);
_gridProxy->setTarget(_outScene);
_gridProxy->onEnter();
ActionInterval* split = action(); ActionInterval* split = action();
ActionInterval* seq = (ActionInterval*)Sequence::create ActionInterval* seq = (ActionInterval*)Sequence::create
( (
split, split,
CallFunc::create(CC_CALLBACK_0(TransitionScene::hideOutShowIn,this)), CallFunc::create(CC_CALLBACK_0(TransitionSplitCols::switchTargetToInscene,this)),
split->reverse(), split->reverse(),
nullptr nullptr
); );
this->runAction _gridProxy->runAction
( (
Sequence::create Sequence::create
( (
@ -1446,6 +1482,24 @@ void TransitionSplitCols::onEnter()
); );
} }
void TransitionSplitCols::switchTargetToInscene()
{
_gridProxy->setTarget(_inScene);
}
void TransitionSplitCols::draw()
{
Scene::draw();
_gridProxy->visit();
}
void TransitionSplitCols::onExit()
{
_gridProxy->setTarget(nullptr);
_gridProxy->onExit();
TransitionScene::onExit();
}
ActionInterval* TransitionSplitCols:: action() ActionInterval* TransitionSplitCols:: action()
{ {
return SplitCols::create(_duration/2.0f, 3); return SplitCols::create(_duration/2.0f, 3);
@ -1491,9 +1545,12 @@ TransitionSplitRows* TransitionSplitRows::create(float t, Scene* scene)
// //
TransitionFadeTR::TransitionFadeTR() TransitionFadeTR::TransitionFadeTR()
{ {
_outSceneProxy = NodeGrid::create();
_outSceneProxy->retain();
} }
TransitionFadeTR::~TransitionFadeTR() TransitionFadeTR::~TransitionFadeTR()
{ {
CC_SAFE_RELEASE(_outSceneProxy);
} }
TransitionFadeTR* TransitionFadeTR::create(float t, Scene* scene) TransitionFadeTR* TransitionFadeTR::create(float t, Scene* scene)
@ -1517,6 +1574,9 @@ void TransitionFadeTR::onEnter()
{ {
TransitionScene::onEnter(); TransitionScene::onEnter();
_outSceneProxy->setTarget(_outScene);
_outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize(); Size s = Director::getInstance()->getWinSize();
float aspect = s.width / s.height; float aspect = s.width / s.height;
int x = (int)(12 * aspect); int x = (int)(12 * aspect);
@ -1524,7 +1584,7 @@ void TransitionFadeTR::onEnter()
ActionInterval* action = actionWithSize(Size(x,y)); ActionInterval* action = actionWithSize(Size(x,y));
_outScene->runAction _outSceneProxy->runAction
( (
Sequence::create Sequence::create
( (
@ -1536,6 +1596,28 @@ void TransitionFadeTR::onEnter()
); );
} }
void TransitionFadeTR::onExit()
{
_outSceneProxy->setTarget(nullptr);
_outSceneProxy->onExit();
TransitionScene::onExit();
}
void TransitionFadeTR::draw()
{
Scene::draw();
if( _isInSceneOnTop )
{
_outSceneProxy->visit();
_inScene->visit();
}
else
{
_inScene->visit();
_outSceneProxy->visit();
}
}
ActionInterval* TransitionFadeTR::actionWithSize(const Size& size) ActionInterval* TransitionFadeTR::actionWithSize(const Size& size)
{ {

View File

@ -43,6 +43,7 @@ NS_CC_BEGIN
class ActionInterval; class ActionInterval;
class Node; class Node;
class NodeGrid;
/** @brief TransitionEaseScene can ease the actions of the scene protocol. /** @brief TransitionEaseScene can ease the actions of the scene protocol.
@since v0.8.2 @since v0.8.2
@ -643,13 +644,16 @@ public :
* @lua NA * @lua NA
*/ */
virtual void onEnter() override; virtual void onEnter() override;
virtual void onExit() override;
virtual ActionInterval * easeActionWithAction(ActionInterval * action) override; virtual ActionInterval * easeActionWithAction(ActionInterval * action) override;
virtual void draw() override;
protected: protected:
TransitionTurnOffTiles(); TransitionTurnOffTiles();
virtual ~TransitionTurnOffTiles(); virtual ~TransitionTurnOffTiles();
virtual void sceneOrder() override; virtual void sceneOrder() override;
NodeGrid* _outSceneProxy;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionTurnOffTiles); CC_DISALLOW_COPY_AND_ASSIGN(TransitionTurnOffTiles);
@ -674,11 +678,13 @@ public:
*/ */
virtual void onEnter() override; virtual void onEnter() override;
virtual ActionInterval * easeActionWithAction(ActionInterval * action) override; virtual ActionInterval * easeActionWithAction(ActionInterval * action) override;
virtual void onExit() override;
virtual void draw() override;
protected: protected:
TransitionSplitCols(); TransitionSplitCols();
virtual ~TransitionSplitCols(); virtual ~TransitionSplitCols();
void switchTargetToInscene();
NodeGrid* _gridProxy;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSplitCols); CC_DISALLOW_COPY_AND_ASSIGN(TransitionSplitCols);
}; };
@ -723,13 +729,16 @@ public:
*/ */
virtual void onEnter() override; virtual void onEnter() override;
virtual ActionInterval* easeActionWithAction(ActionInterval * action) override; virtual ActionInterval* easeActionWithAction(ActionInterval * action) override;
virtual void onExit() override;
virtual void draw() override;
protected: protected:
TransitionFadeTR(); TransitionFadeTR();
virtual ~TransitionFadeTR(); virtual ~TransitionFadeTR();
virtual void sceneOrder(); virtual void sceneOrder();
NodeGrid* _outSceneProxy;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeTR); CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeTR);
}; };

View File

@ -29,6 +29,7 @@ THE SOFTWARE.
#include "CCActionInstant.h" #include "CCActionInstant.h"
#include "CCActionGrid.h" #include "CCActionGrid.h"
#include "CCActionPageTurn3D.h" #include "CCActionPageTurn3D.h"
#include "CCNodeGrid.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -37,10 +38,17 @@ float TransitionPageTurn::POLYGON_OFFSET_UNITS = -20.f;
TransitionPageTurn::TransitionPageTurn() TransitionPageTurn::TransitionPageTurn()
{ {
_inSceneProxy = NodeGrid::create();
_outSceneProxy = NodeGrid::create();
_inSceneProxy->retain();
_outSceneProxy->retain();
} }
TransitionPageTurn::~TransitionPageTurn() TransitionPageTurn::~TransitionPageTurn()
{ {
CC_SAFE_RELEASE(_inSceneProxy);
CC_SAFE_RELEASE(_outSceneProxy);
} }
/** creates a base transition with duration and incoming scene */ /** creates a base transition with duration and incoming scene */
@ -75,17 +83,17 @@ void TransitionPageTurn::draw()
Scene::draw(); Scene::draw();
if( _isInSceneOnTop ) { if( _isInSceneOnTop ) {
_outScene->visit(); _outSceneProxy->visit();
glEnable(GL_POLYGON_OFFSET_FILL); glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS); glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS);
_inScene->visit(); _inSceneProxy->visit();
glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0, 0); glPolygonOffset(0, 0);
} else { } else {
_inScene->visit(); _inSceneProxy->visit();
glEnable(GL_POLYGON_OFFSET_FILL); glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS); glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS);
_outScene->visit(); _outSceneProxy->visit();
glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0, 0); glPolygonOffset(0, 0);
} }
@ -94,6 +102,13 @@ void TransitionPageTurn::draw()
void TransitionPageTurn::onEnter() void TransitionPageTurn::onEnter()
{ {
TransitionScene::onEnter(); TransitionScene::onEnter();
_inSceneProxy->setTarget(_inScene);
_outSceneProxy->setTarget(_outScene);
_inSceneProxy->onEnter();
_outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize(); Size s = Director::getInstance()->getWinSize();
int x,y; int x,y;
if (s.width > s.height) if (s.width > s.height)
@ -111,7 +126,7 @@ void TransitionPageTurn::onEnter()
if (! _back ) if (! _back )
{ {
_outScene->runAction _outSceneProxy->runAction
( (
Sequence::create Sequence::create
( (
@ -125,8 +140,8 @@ void TransitionPageTurn::onEnter()
else else
{ {
// to prevent initial flicker // to prevent initial flicker
_inScene->setVisible(false); _inSceneProxy->setVisible(false);
_inScene->runAction _inSceneProxy->runAction
( (
Sequence::create Sequence::create
( (
@ -139,7 +154,15 @@ void TransitionPageTurn::onEnter()
); );
} }
} }
void TransitionPageTurn::onExit()
{
_outSceneProxy->setTarget(nullptr);
_outSceneProxy->setTarget(nullptr);
_outSceneProxy->onExit();
_inSceneProxy->onExit();
TransitionScene::onExit();
}
ActionInterval* TransitionPageTurn:: actionWithSize(const Size& vector) ActionInterval* TransitionPageTurn:: actionWithSize(const Size& vector)
{ {

View File

@ -30,6 +30,8 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
class NodeGrid;
/** /**
* @addtogroup transition * @addtogroup transition
* @{ * @{
@ -83,11 +85,14 @@ public:
// Overrides // Overrides
// //
virtual void onEnter() override; virtual void onEnter() override;
virtual void onExit() override;
protected: protected:
virtual void sceneOrder() override; virtual void sceneOrder() override;
protected: protected:
NodeGrid* _inSceneProxy;
NodeGrid* _outSceneProxy;
bool _back; bool _back;
static float POLYGON_OFFSET_FACTOR; static float POLYGON_OFFSET_FACTOR;
static float POLYGON_OFFSET_UNITS; static float POLYGON_OFFSET_UNITS;

View File

@ -32,6 +32,7 @@ THE SOFTWARE.
#include "CCLayer.h" #include "CCLayer.h"
#include "CCActionInstant.h" #include "CCActionInstant.h"
#include "CCActionProgressTimer.h" #include "CCActionProgressTimer.h"
#include "CCNewRenderTexture.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -71,7 +72,7 @@ void TransitionProgress::onEnter()
Size size = Director::getInstance()->getWinSize(); Size size = Director::getInstance()->getWinSize();
// create the second render texture for outScene // create the second render texture for outScene
RenderTexture *texture = RenderTexture::create((int)size.width, (int)size.height); RenderTexture *texture = NewRenderTexture::create((int)size.width, (int)size.height);
texture->getSprite()->setAnchorPoint(Point(0.5f,0.5f)); texture->getSprite()->setAnchorPoint(Point(0.5f,0.5f));
texture->setPosition(Point(size.width/2, size.height/2)); texture->setPosition(Point(size.width/2, size.height/2));
texture->setAnchorPoint(Point(0.5f,0.5f)); texture->setAnchorPoint(Point(0.5f,0.5f));

View File

@ -140,23 +140,16 @@ static void setValueForKey(const char* pKey, const char* pValue)
* implements of UserDefault * implements of UserDefault
*/ */
UserDefault* UserDefault::_userDefault = 0; UserDefault* UserDefault::_userDefault = nullptr;
string UserDefault::_filePath = string(""); string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false; bool UserDefault::_isFilePathInitialized = false;
/**
* If the user invoke delete UserDefault::getInstance(), should set _userDefault
* to null to avoid error when he invoke UserDefault::getInstance() later.
*/
UserDefault::~UserDefault() UserDefault::~UserDefault()
{ {
CC_SAFE_DELETE(_userDefault);
_userDefault = nullptr;
} }
UserDefault::UserDefault() UserDefault::UserDefault()
{ {
_userDefault = nullptr;
} }
bool UserDefault::getBoolForKey(const char* pKey) bool UserDefault::getBoolForKey(const char* pKey)
@ -433,7 +426,7 @@ UserDefault* UserDefault::getInstance()
void UserDefault::destroyInstance() void UserDefault::destroyInstance()
{ {
_userDefault = nullptr; CC_SAFE_DELETE(_userDefault);
} }
// XXX: deprecated // XXX: deprecated

View File

@ -46,12 +46,6 @@ NS_CC_BEGIN
class CC_DLL UserDefault class CC_DLL UserDefault
{ {
public: public:
/**
* @js NA
* @lua NA
*/
~UserDefault();
// get value methods // get value methods
/** /**
@ -186,6 +180,8 @@ public:
private: private:
UserDefault(); UserDefault();
~UserDefault();
static bool createXMLFile(); static bool createXMLFile();
static void initXMLFilePath(); static void initXMLFilePath();

View File

@ -48,7 +48,7 @@ NS_CC_BEGIN
* implements of UserDefault * implements of UserDefault
*/ */
UserDefault* UserDefault::_userDefault = 0; UserDefault* UserDefault::_userDefault = nullptr;
string UserDefault::_filePath = string(""); string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false; bool UserDefault::_isFilePathInitialized = false;
@ -134,19 +134,12 @@ static void deleteNodeByKey(const char *pKey)
} }
#endif #endif
/**
* If the user invoke delete UserDefault::getInstance(), should set _userDefault
* to null to avoid error when he invoke UserDefault::getInstance() later.
*/
UserDefault::~UserDefault() UserDefault::~UserDefault()
{ {
CC_SAFE_DELETE(_userDefault);
_userDefault = nullptr;
} }
UserDefault::UserDefault() UserDefault::UserDefault()
{ {
_userDefault = nullptr;
} }
bool UserDefault::getBoolForKey(const char* pKey) bool UserDefault::getBoolForKey(const char* pKey)
@ -503,8 +496,7 @@ UserDefault* UserDefault::getInstance()
void UserDefault::destroyInstance() void UserDefault::destroyInstance()
{ {
delete _userDefault; CC_SAFE_DELETE(_userDefault);
_userDefault = nullptr;
} }
// XXX: deprecated // XXX: deprecated

View File

@ -49,7 +49,7 @@ NS_CC_BEGIN
* implements of UserDefault * implements of UserDefault
*/ */
UserDefault* UserDefault::_userDefault = 0; UserDefault* UserDefault::_userDefault = nullptr;
string UserDefault::_filePath = string(""); string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false; bool UserDefault::_isFilePathInitialized = false;
@ -135,19 +135,12 @@ static void deleteNodeByKey(const char *pKey)
} }
#endif #endif
/**
* If the user invoke delete UserDefault::getInstance(), should set _userDefault
* to null to avoid error when he invoke UserDefault::getInstance() later.
*/
UserDefault::~UserDefault() UserDefault::~UserDefault()
{ {
CC_SAFE_DELETE(_userDefault);
_userDefault = nullptr;
} }
UserDefault::UserDefault() UserDefault::UserDefault()
{ {
_userDefault = nullptr;
} }
// XXX: deprecated // XXX: deprecated
@ -158,7 +151,7 @@ void UserDefault::purgeSharedUserDefault()
void UserDefault::destroyInstance() void UserDefault::destroyInstance()
{ {
_userDefault = nullptr; CC_SAFE_DELETE(_userDefault);
} }
bool UserDefault::getBoolForKey(const char* pKey) bool UserDefault::getBoolForKey(const char* pKey)

View File

@ -63,6 +63,7 @@ set(COCOS2D_SRC
CCDrawNode.cpp CCDrawNode.cpp
CCGrabber.cpp CCGrabber.cpp
CCGrid.cpp CCGrid.cpp
CCNodeGrid.cpp
CCFont.cpp CCFont.cpp
CCFontAtlas.cpp CCFontAtlas.cpp
CCFontAtlasCache.cpp CCFontAtlasCache.cpp

View File

@ -257,6 +257,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="ccGLStateCache.cpp" /> <ClCompile Include="ccGLStateCache.cpp" />
<ClCompile Include="CCGrabber.cpp" /> <ClCompile Include="CCGrabber.cpp" />
<ClCompile Include="CCGrid.cpp" /> <ClCompile Include="CCGrid.cpp" />
<ClCompile Include="CCNodeGrid.cpp" />
<ClCompile Include="CCIMEDispatcher.cpp" /> <ClCompile Include="CCIMEDispatcher.cpp" />
<ClCompile Include="CCLabel.cpp" /> <ClCompile Include="CCLabel.cpp" />
<ClCompile Include="CCLabelAtlas.cpp" /> <ClCompile Include="CCLabelAtlas.cpp" />
@ -442,6 +443,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="ccGLStateCache.h" /> <ClInclude Include="ccGLStateCache.h" />
<ClInclude Include="CCGrabber.h" /> <ClInclude Include="CCGrabber.h" />
<ClInclude Include="CCGrid.h" /> <ClInclude Include="CCGrid.h" />
<ClInclude Include="CCNodeGrid.h" />
<ClInclude Include="CCIMEDelegate.h" /> <ClInclude Include="CCIMEDelegate.h" />
<ClInclude Include="CCIMEDispatcher.h" /> <ClInclude Include="CCIMEDispatcher.h" />
<ClInclude Include="CCLabel.h" /> <ClInclude Include="CCLabel.h" />

View File

@ -569,6 +569,9 @@
<ClCompile Include="..\base\CCValue.cpp"> <ClCompile Include="..\base\CCValue.cpp">
<Filter>base</Filter> <Filter>base</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="CCNodeGrid.cpp">
<Filter>misc_nodes</Filter>
</ClCompile>
<ClCompile Include="..\..\external\edtaa3func\edtaa3func.cpp"> <ClCompile Include="..\..\external\edtaa3func\edtaa3func.cpp">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClCompile> </ClCompile>
@ -1188,6 +1191,9 @@
<ClInclude Include="..\base\CCVector.h"> <ClInclude Include="..\base\CCVector.h">
<Filter>base</Filter> <Filter>base</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="CCNodeGrid.h">
<Filter>misc_nodes</Filter>
</ClInclude>
<ClInclude Include="..\..\external\edtaa3func\edtaa3func.h"> <ClInclude Include="..\..\external\edtaa3func\edtaa3func.h">
<Filter>label_nodes</Filter> <Filter>label_nodes</Filter>
</ClInclude> </ClInclude>

View File

@ -321,8 +321,8 @@ ValueVector FileUtils::getValueVectorFromFile(const std::string& filename)
/* /*
* forward statement * forward statement
*/ */
static tinyxml2::XMLElement* generateElementForArray(ValueVector& array, tinyxml2::XMLDocument *doc); static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, tinyxml2::XMLDocument *doc);
static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XMLDocument *doc); static tinyxml2::XMLElement* generateElementForDict(const ValueMap& dict, tinyxml2::XMLDocument *doc);
/* /*
* Use tinyxml2 to write plist files * Use tinyxml2 to write plist files
@ -371,7 +371,7 @@ bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath)
/* /*
* Generate tinyxml2::XMLElement for Object through a tinyxml2::XMLDocument * Generate tinyxml2::XMLElement for Object through a tinyxml2::XMLDocument
*/ */
static tinyxml2::XMLElement* generateElementForObject(Value& value, tinyxml2::XMLDocument *doc) static tinyxml2::XMLElement* generateElementForObject(const Value& value, tinyxml2::XMLDocument *doc)
{ {
// object is String // object is String
if (value.getType() == Value::Type::STRING) if (value.getType() == Value::Type::STRING)
@ -417,7 +417,7 @@ static tinyxml2::XMLElement* generateElementForObject(Value& value, tinyxml2::XM
/* /*
* Generate tinyxml2::XMLElement for Dictionary through a tinyxml2::XMLDocument * Generate tinyxml2::XMLElement for Dictionary through a tinyxml2::XMLDocument
*/ */
static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XMLDocument *doc) static tinyxml2::XMLElement* generateElementForDict(const ValueMap& dict, tinyxml2::XMLDocument *doc)
{ {
tinyxml2::XMLElement* rootNode = doc->NewElement("dict"); tinyxml2::XMLElement* rootNode = doc->NewElement("dict");
@ -438,16 +438,15 @@ static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XM
/* /*
* Generate tinyxml2::XMLElement for Array through a tinyxml2::XMLDocument * Generate tinyxml2::XMLElement for Array through a tinyxml2::XMLDocument
*/ */
static tinyxml2::XMLElement* generateElementForArray(ValueVector& array, tinyxml2::XMLDocument *pDoc) static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, tinyxml2::XMLDocument *pDoc)
{ {
tinyxml2::XMLElement* rootNode = pDoc->NewElement("array"); tinyxml2::XMLElement* rootNode = pDoc->NewElement("array");
std::for_each(array.begin(), array.end(), [=](Value& value){ for(const auto &value : array) {
tinyxml2::XMLElement *element = generateElementForObject(value, pDoc); tinyxml2::XMLElement *element = generateElementForObject(value, pDoc);
if (element) if (element)
rootNode->LinkEndChild(element); rootNode->LinkEndChild(element);
}
});
return rootNode; return rootNode;
} }

View File

@ -190,7 +190,7 @@ double getDoubleForKeyJNI(const char* pKey, double defaultValue)
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getDoubleForKey", "(Ljava/lang/String;D)D")) { if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getDoubleForKey", "(Ljava/lang/String;D)D")) {
jstring stringArg = t.env->NewStringUTF(pKey); jstring stringArg = t.env->NewStringUTF(pKey);
jdouble ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, stringArg); jdouble ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, stringArg, defaultValue);
t.env->DeleteLocalRef(t.classID); t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg); t.env->DeleteLocalRef(stringArg);

View File

@ -38,7 +38,7 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
static void addValueToDict(id nsKey, id nsValue, ValueMap& dict); static void addValueToDict(id nsKey, id nsValue, ValueMap& dict);
static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDictionary *dict); static void addObjectToNSDict(const std::string& key, const Value& value, NSMutableDictionary *dict);
static void addItemToArray(id item, ValueVector& array) static void addItemToArray(id item, ValueVector& array)
{ {
@ -83,7 +83,7 @@ static void addItemToArray(id item, ValueVector& array)
} }
} }
static void addObjectToNSArray(Value& value, NSMutableArray *array) static void addObjectToNSArray(const Value& value, NSMutableArray *array)
{ {
// add string into array // add string into array
if (value.getType() == Value::Type::STRING) if (value.getType() == Value::Type::STRING)
@ -100,9 +100,10 @@ static void addObjectToNSArray(Value& value, NSMutableArray *array)
ValueVector valueArray = value.asValueVector(); ValueVector valueArray = value.asValueVector();
std::for_each(valueArray.begin(), valueArray.end(), [=](Value& e){ for (const auto &e : valueArray)
{
addObjectToNSArray(e, element); addObjectToNSArray(e, element);
}); }
[array addObject:element]; [array addObject:element];
return; return;
@ -171,7 +172,7 @@ static void addValueToDict(id nsKey, id nsValue, ValueMap& dict)
} }
} }
static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDictionary *dict) static void addObjectToNSDict(const std::string& key, const Value& value, NSMutableDictionary *dict)
{ {
NSString *NSkey = [NSString stringWithCString:key.c_str() encoding:NSUTF8StringEncoding]; NSString *NSkey = [NSString stringWithCString:key.c_str() encoding:NSUTF8StringEncoding];
@ -204,9 +205,10 @@ static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDic
ValueVector array = value.asValueVector(); ValueVector array = value.asValueVector();
std::for_each(array.begin(), array.end(), [=](Value& v){ for(const auto& v : array)
{
addObjectToNSArray(v, arrElement); addObjectToNSArray(v, arrElement);
}); }
[dict setObject:arrElement forKey:NSkey]; [dict setObject:arrElement forKey:NSkey];
return; return;

View File

@ -68,6 +68,7 @@ int GroupCommandManager::getGroupID()
{ {
if(!it->second) if(!it->second)
{ {
_groupMapping[it->first] = true;
return it->first; return it->first;
} }
} }

View File

@ -296,7 +296,10 @@ void Renderer::render()
//TODO give command back to command pool //TODO give command back to command pool
for (size_t j = 0 ; j < _renderGroups.size(); j++) for (size_t j = 0 ; j < _renderGroups.size(); j++)
{ {
for_each(_renderGroups[j].begin(), _renderGroups[j].end(), [](RenderCommand* cmd){ cmd->releaseToCommandPool(); }); for (const auto &cmd : _renderGroups[j])
{
cmd->releaseToCommandPool();
}
_renderGroups[j].clear(); _renderGroups[j].clear();
} }

View File

@ -26,7 +26,6 @@ THE SOFTWARE.
#include "CCArray.h" #include "CCArray.h"
#include "CCString.h" #include "CCString.h"
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include <algorithm> // std::for_each
NS_CC_BEGIN NS_CC_BEGIN
@ -482,9 +481,9 @@ __Array* __Array::createWithContentsOfFileThreadSafe(const char* fileName)
__Array* ret = __Array::createWithCapacity(static_cast<int>(arr.size())); __Array* ret = __Array::createWithCapacity(static_cast<int>(arr.size()));
std::for_each(arr.cbegin(), arr.cend(), [&ret](const Value& value){ for(const auto &value : arr) {
ret->addObject(__String::create(value.asString())); ret->addObject(__String::create(value.asString()));
}); }
return ret; return ret;
} }

View File

@ -64,14 +64,14 @@ void AutoreleasePool::clear()
int nIndex = _managedObjectArray.size() - 1; int nIndex = _managedObjectArray.size() - 1;
#endif #endif
std::for_each(_managedObjectArray.rbegin(), _managedObjectArray.rend(), [&](Object* obj){ for(const auto &obj : _managedObjectArray) {
--(obj->_autoReleaseCount); --(obj->_autoReleaseCount);
//(*it)->release(); //(*it)->release();
//delete (*it); //delete (*it);
#ifdef _DEBUG #ifdef _DEBUG
nIndex--; nIndex--;
#endif #endif
}); }
_managedObjectArray.clear(); _managedObjectArray.clear();
} }
@ -118,9 +118,9 @@ void PoolManager::finalize()
{ {
if (!_releasePoolStack.empty()) if (!_releasePoolStack.empty())
{ {
std::for_each(_releasePoolStack.begin(), _releasePoolStack.end(), [](AutoreleasePool* pool){ for(const auto &pool : _releasePoolStack) {
pool->clear(); pool->clear();
}); }
} }
} }

View File

@ -26,7 +26,6 @@
#include "CCString.h" #include "CCString.h"
#include "CCInteger.h" #include "CCInteger.h"
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include <algorithm> // std::for_each
using namespace std; using namespace std;
@ -416,7 +415,7 @@ static __Array* visitArray(const ValueVector& array)
__Array* ret = new __Array(); __Array* ret = new __Array();
ret->init(); ret->init();
std::for_each(array.begin(), array.end(), [&ret](const Value& value){ for(const auto &value : array) {
if (value.getType() == Value::Type::MAP) if (value.getType() == Value::Type::MAP)
{ {
const ValueMap& subDict = value.asValueMap(); const ValueMap& subDict = value.asValueMap();
@ -437,7 +436,7 @@ static __Array* visitArray(const ValueVector& array)
ret->addObject(str); ret->addObject(str);
str->release(); str->release();
} }
}); }
return ret; return ret;
} }

View File

@ -29,7 +29,6 @@
#include <vector> #include <vector>
#include <unordered_map> #include <unordered_map>
#include <algorithm> // std::for_each
NS_CC_BEGIN NS_CC_BEGIN
@ -241,9 +240,9 @@ public:
*/ */
void erase(const std::vector<K>& keys) void erase(const std::vector<K>& keys)
{ {
std::for_each(keys.cbegin(), keys.cend(), [this](const K& key){ for(const auto &key : keys) {
this->erase(key); this->erase(key);
}); }
} }
/** All the elements in the Map<K,V> container are dropped: /** All the elements in the Map<K,V> container are dropped:

View File

@ -29,7 +29,7 @@ THE SOFTWARE.
#include <vector> #include <vector>
#include <functional> #include <functional>
#include <algorithm> // std::for_each #include <algorithm> // for std::find
NS_CC_BEGIN NS_CC_BEGIN
@ -267,10 +267,10 @@ public:
/** Push all elements of an existing vector to the end of current vector. */ /** Push all elements of an existing vector to the end of current vector. */
void pushBack(const Vector<T>& other) void pushBack(const Vector<T>& other)
{ {
std::for_each(other.begin(), other.end(), [this](T obj){ for(const auto &obj : other) {
_data.push_back(obj); _data.push_back(obj);
obj->retain(); obj->retain();
}); }
} }
/** @brief Insert a certain object at a certain index /** @brief Insert a certain object at a certain index
@ -415,9 +415,9 @@ protected:
/** Retains all the objects in the vector */ /** Retains all the objects in the vector */
void addRefForAllObjects() void addRefForAllObjects()
{ {
std::for_each(_data.begin(), _data.end(), [](T obj){ for(const auto &obj : _data) {
obj->retain(); obj->retain();
}); }
} }
std::vector<T> _data; std::vector<T> _data;

View File

@ -294,9 +294,9 @@ void CCBReader::cleanUpNodeGraph(Node *node)
node->setUserObject(nullptr); node->setUserObject(nullptr);
auto& children = node->getChildren(); auto& children = node->getChildren();
std::for_each(children.begin(), children.end(), [this](Node* obj){ for(const auto &obj : children) {
cleanUpNodeGraph(obj); cleanUpNodeGraph(obj);
}); }
} }
Node* CCBReader::readFileWithCleanUp(bool bCleanUp, CCBAnimationManagerMapPtr am) Node* CCBReader::readFileWithCleanUp(bool bCleanUp, CCBAnimationManagerMapPtr am)

View File

@ -399,7 +399,7 @@ int ActionNode::getLastFrameIndex()
continue; continue;
} }
bFindFrame = true; bFindFrame = true;
int lastInex = cArray->count() - 1; ssize_t lastInex = cArray->count() - 1;
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(lastInex)); ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(lastInex));
int iFrameIndex = frame->getFrameIndex(); int iFrameIndex = frame->getFrameIndex();
@ -428,7 +428,7 @@ bool ActionNode::updateActionToTimeLine(float fTime)
{ {
continue; continue;
} }
int frameCount = cArray->count(); ssize_t frameCount = cArray->count();
for (int i = 0; i < frameCount; i++) for (int i = 0; i < frameCount; i++)
{ {
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(i)); ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(i));

View File

@ -373,9 +373,9 @@ void Armature::update(float dt)
{ {
_animation->update(dt); _animation->update(dt);
std::for_each(_topBoneList.begin(), _topBoneList.end(), [&dt](Bone* bone){ for(const auto &bone : _topBoneList) {
bone->update(dt); bone->update(dt);
}); }
_armatureTransformDirty = false; _armatureTransformDirty = false;
} }
@ -444,11 +444,6 @@ void Armature::visit()
} }
kmGLPushMatrix(); kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
}
transform(); transform();
sortAllChildren(); sortAllChildren();
draw(); draw();
@ -456,11 +451,6 @@ void Armature::visit()
// reset for next frame // reset for next frame
_orderOfArrival = 0; _orderOfArrival = 0;
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix(); kmGLPopMatrix();
} }
@ -472,7 +462,7 @@ Rect Armature::getBoundingBox() const
Rect boundingBox = Rect(0, 0, 0, 0); Rect boundingBox = Rect(0, 0, 0, 0);
for_each(_children.begin(), _children.end(), [&minx, &miny, &maxx, &maxy, &first, &boundingBox](Node *object) for (const auto& object : _children)
{ {
if (Bone *bone = dynamic_cast<Bone *>(object)) if (Bone *bone = dynamic_cast<Bone *>(object))
{ {
@ -498,7 +488,7 @@ Rect Armature::getBoundingBox() const
boundingBox.setRect(minx, miny, maxx - minx, maxy - miny); boundingBox.setRect(minx, miny, maxx - minx, maxy - miny);
} }
}); }
return RectApplyTransform(boundingBox, getNodeToParentTransform()); return RectApplyTransform(boundingBox, getNodeToParentTransform());
} }
@ -642,15 +632,15 @@ void Armature::setBody(cpBody *body)
_body = body; _body = body;
_body->data = this; _body->data = this;
for (auto& object : _children) for (const auto& object : _children)
{ {
if (Bone *bone = dynamic_cast<Bone *>(object)) if (Bone *bone = dynamic_cast<Bone *>(object))
{ {
auto displayList = bone->getDisplayManager()->getDecorativeDisplayList(); auto displayList = bone->getDisplayManager()->getDecorativeDisplayList();
for_each(displayList.begin(), displayList.end(), [&body](DecorativeDisplay* displayObject) for (const auto& displayObject : displayList)
{ {
ColliderDetector *detector = displayObject->getColliderDetector(); auto detector = displayObject->getColliderDetector();
if (detector != nullptr) if (detector != nullptr)
{ {
detector->setBody(body); detector->setBody(body);

View File

@ -97,28 +97,28 @@ bool ArmatureAnimation::init(Armature *armature)
void ArmatureAnimation::pause() void ArmatureAnimation::pause()
{ {
for_each(_tweenList.begin(), _tweenList.end(), [](Tween *tween) for (const auto& tween : _tweenList)
{ {
tween->pause(); tween->pause();
}); }
ProcessBase::pause(); ProcessBase::pause();
} }
void ArmatureAnimation::resume() void ArmatureAnimation::resume()
{ {
for_each(_tweenList.begin(), _tweenList.end(), [](Tween *tween) for (const auto& tween : _tweenList)
{ {
tween->resume(); tween->resume();
}); }
ProcessBase::resume(); ProcessBase::resume();
} }
void ArmatureAnimation::stop() void ArmatureAnimation::stop()
{ {
for_each(_tweenList.begin(), _tweenList.end(), [](Tween *tween) for (const auto& tween : _tweenList)
{ {
tween->stop(); tween->stop();
}); }
_tweenList.clear(); _tweenList.clear();
ProcessBase::stop(); ProcessBase::stop();
} }
@ -308,10 +308,10 @@ void ArmatureAnimation::gotoAndPlay(int frameIndex)
_currentFrame = _nextFrameIndex * _currentPercent; _currentFrame = _nextFrameIndex * _currentPercent;
for_each(_tweenList.begin(), _tweenList.end(), [&frameIndex](Tween* tween) for (const auto &tween : _tweenList)
{ {
tween->gotoAndPlay(frameIndex); tween->gotoAndPlay(frameIndex);
}); }
_armature->update(0); _armature->update(0);
@ -333,10 +333,10 @@ void ArmatureAnimation::update(float dt)
{ {
ProcessBase::update(dt); ProcessBase::update(dt);
for_each(_tweenList.begin(), _tweenList.end(), [&dt](Tween* tween) for (const auto &tween : _tweenList)
{ {
tween->update(dt); tween->update(dt);
}); }
while (_frameEventQueue.size() > 0) while (_frameEventQueue.size() > 0)
{ {

View File

@ -101,11 +101,6 @@ void BatchNode::visit()
} }
kmGLPushMatrix(); kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
}
transform(); transform();
sortAllChildren(); sortAllChildren();
draw(); draw();
@ -113,11 +108,6 @@ void BatchNode::visit()
// reset for next frame // reset for next frame
_orderOfArrival = 0; _orderOfArrival = 0;
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix(); kmGLPopMatrix();
} }

View File

@ -229,11 +229,10 @@ void Bone::update(float delta)
DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty()); DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty());
std::for_each(_children.begin(), _children.end(), [&delta](Node* obj) for(const auto &obj: _children) {
{
Bone *childBone = static_cast<Bone*>(obj); Bone *childBone = static_cast<Bone*>(obj);
childBone->update(delta); childBone->update(delta);
}); }
_boneTransformDirty = false; _boneTransformDirty = false;
} }

View File

@ -202,28 +202,28 @@ void ColliderDetector::addContourData(ContourData *contourData)
void ColliderDetector::addContourDataList(cocos2d::Vector<ContourData*> &contourDataList) void ColliderDetector::addContourDataList(cocos2d::Vector<ContourData*> &contourDataList)
{ {
for_each(contourDataList.begin(), contourDataList.end(), [this](ContourData *contourData) for (const auto &contourData : contourDataList)
{ {
this->addContourData(contourData); this->addContourData(contourData);
}); }
} }
void ColliderDetector::removeContourData(ContourData *contourData) void ColliderDetector::removeContourData(ContourData *contourData)
{ {
std::vector<ColliderBody*> eraseList; std::vector<ColliderBody*> eraseList;
for_each(_colliderBodyList.begin(), _colliderBodyList.end(), [&contourData, this, &eraseList](ColliderBody *body) for (const auto &body : _colliderBodyList)
{ {
if (body && body->getContourData() == contourData) if (body && body->getContourData() == contourData)
{ {
eraseList.push_back(body); eraseList.push_back(body);
} }
}); }
for_each(eraseList.begin(), eraseList.end(), [this](ColliderBody *body) for (const auto &body : eraseList)
{ {
this->_colliderBodyList.eraseObject(body); this->_colliderBodyList.eraseObject(body);
}); }
} }
void ColliderDetector::removeAll() void ColliderDetector::removeAll()

View File

@ -37,7 +37,7 @@ UIWidget* UIHelper::seekWidgetByTag(UIWidget* root, int tag)
return root; return root;
} }
cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; cocos2d::ccArray* arrayRootChildren = root->getChildren()->data;
int length = arrayRootChildren->num; ssize_t length = arrayRootChildren->num;
for (int i=0;i<length;i++) for (int i=0;i<length;i++)
{ {
UIWidget* child = (UIWidget*)(arrayRootChildren->arr[i]); UIWidget* child = (UIWidget*)(arrayRootChildren->arr[i]);
@ -61,7 +61,7 @@ UIWidget* UIHelper::seekWidgetByName(UIWidget* root, const char *name)
return root; return root;
} }
cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; cocos2d::ccArray* arrayRootChildren = root->getChildren()->data;
int length = arrayRootChildren->num; ssize_t length = arrayRootChildren->num;
for (int i=0;i<length;i++) for (int i=0;i<length;i++)
{ {
UIWidget* child = (UIWidget*)(arrayRootChildren->arr[i]); UIWidget* child = (UIWidget*)(arrayRootChildren->arr[i]);
@ -81,7 +81,7 @@ UIWidget* UIHelper::seekWidgetByRelativeName(UIWidget *root, const char *name)
return nullptr; return nullptr;
} }
cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; cocos2d::ccArray* arrayRootChildren = root->getChildren()->data;
int length = arrayRootChildren->num; ssize_t length = arrayRootChildren->num;
for (int i=0;i<length;i++) for (int i=0;i<length;i++)
{ {
UIWidget* child = (UIWidget*)(arrayRootChildren->arr[i]); UIWidget* child = (UIWidget*)(arrayRootChildren->arr[i]);
@ -106,7 +106,7 @@ UIWidget* UIHelper::seekActionWidgetByActionTag(UIWidget* root, int tag)
return root; return root;
} }
cocos2d::ccArray* arrayRootChildren = root->getChildren()->data; cocos2d::ccArray* arrayRootChildren = root->getChildren()->data;
int length = arrayRootChildren->num; ssize_t length = arrayRootChildren->num;
for (int i=0;i<length;i++) for (int i=0;i<length;i++)
{ {
UIWidget* child = (UIWidget*)(arrayRootChildren->arr[i]); UIWidget* child = (UIWidget*)(arrayRootChildren->arr[i]);

View File

@ -71,8 +71,8 @@ void UIInputManager::registWidget(UIWidget* widget)
bool UIInputManager::checkTouchEvent(UIWidget *root, const Point &touchPoint) bool UIInputManager::checkTouchEvent(UIWidget *root, const Point &touchPoint)
{ {
ccArray* arrayRootChildren = root->getChildren()->data; ccArray* arrayRootChildren = root->getChildren()->data;
int length = arrayRootChildren->num; ssize_t length = arrayRootChildren->num;
for (int i=length-1; i >= 0; i--) for (ssize_t i=length-1; i >= 0; i--)
{ {
UIWidget* widget = (UIWidget*)(arrayRootChildren->arr[i]); UIWidget* widget = (UIWidget*)(arrayRootChildren->arr[i]);
if (checkTouchEvent(widget, touchPoint)) if (checkTouchEvent(widget, touchPoint))
@ -130,7 +130,7 @@ void UIInputManager::update(float dt)
} }
} }
ccArray* arrayWidget = _checkedDoubleClickWidget->data; ccArray* arrayWidget = _checkedDoubleClickWidget->data;
int widgetCount = arrayWidget->num; ssize_t widgetCount = arrayWidget->num;
for (int i=0;i<widgetCount;i++) for (int i=0;i<widgetCount;i++)
{ {
UIWidget* widget = (UIWidget*)(arrayWidget->arr[i]); UIWidget* widget = (UIWidget*)(arrayWidget->arr[i]);
@ -173,7 +173,7 @@ void UIInputManager::onTouchEnd(Touch* touch)
_touchEndedPoint.x = touch->getLocation().x; _touchEndedPoint.x = touch->getLocation().x;
_touchEndedPoint.y = touch->getLocation().y; _touchEndedPoint.y = touch->getLocation().y;
ccArray* selectedWidgetArray = _selectedWidgets->data; ccArray* selectedWidgetArray = _selectedWidgets->data;
int length = selectedWidgetArray->num; ssize_t length = selectedWidgetArray->num;
for (int i=0; i<length; ++i) for (int i=0; i<length; ++i)
{ {
UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]); UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]);
@ -188,7 +188,7 @@ void UIInputManager::onTouchCancelled(Touch* touch)
_touchEndedPoint.x = touch->getLocation().x; _touchEndedPoint.x = touch->getLocation().x;
_touchEndedPoint.y = touch->getLocation().y; _touchEndedPoint.y = touch->getLocation().y;
ccArray* selectedWidgetArray = _selectedWidgets->data; ccArray* selectedWidgetArray = _selectedWidgets->data;
int length = selectedWidgetArray->num; ssize_t length = selectedWidgetArray->num;
for (int i=0; i<length; ++i) for (int i=0; i<length; ++i)
{ {
UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]); UIWidget* hitWidget = (UIWidget*)(selectedWidgetArray->arr[0]);

View File

@ -128,7 +128,7 @@ void UILayout::onSizeChanged()
if (strcmp(getDescription(), "Layout") == 0) if (strcmp(getDescription(), "Layout") == 0)
{ {
cocos2d::ccArray* arrayChildren = _children->data; cocos2d::ccArray* arrayChildren = _children->data;
int length = arrayChildren->num; ssize_t length = arrayChildren->num;
for (int i=0; i<length; ++i) for (int i=0; i<length; ++i)
{ {
UIWidget* child = (UIWidget*)arrayChildren->arr[i]; UIWidget* child = (UIWidget*)arrayChildren->arr[i];
@ -452,7 +452,7 @@ void UILayout::setLayoutType(LayoutType type)
_layoutType = type; _layoutType = type;
cocos2d::ccArray* layoutChildrenArray = getChildren()->data; cocos2d::ccArray* layoutChildrenArray = getChildren()->data;
int length = layoutChildrenArray->num; ssize_t length = layoutChildrenArray->num;
for (int i=0; i<length; i++) for (int i=0; i<length; i++)
{ {
UIWidget* child = dynamic_cast<UIWidget*>(layoutChildrenArray->arr[i]); UIWidget* child = dynamic_cast<UIWidget*>(layoutChildrenArray->arr[i]);
@ -474,7 +474,7 @@ void UILayout::doLayout()
case LAYOUT_LINEAR_VERTICAL: case LAYOUT_LINEAR_VERTICAL:
{ {
cocos2d::ccArray* layoutChildrenArray = getChildren()->data; cocos2d::ccArray* layoutChildrenArray = getChildren()->data;
int length = layoutChildrenArray->num; ssize_t length = layoutChildrenArray->num;
cocos2d::Size layoutSize = getSize(); cocos2d::Size layoutSize = getSize();
float topBoundary = layoutSize.height; float topBoundary = layoutSize.height;
for (int i=0; i<length; ++i) for (int i=0; i<length; ++i)
@ -515,7 +515,7 @@ void UILayout::doLayout()
case LAYOUT_LINEAR_HORIZONTAL: case LAYOUT_LINEAR_HORIZONTAL:
{ {
cocos2d::ccArray* layoutChildrenArray = getChildren()->data; cocos2d::ccArray* layoutChildrenArray = getChildren()->data;
int length = layoutChildrenArray->num; ssize_t length = layoutChildrenArray->num;
cocos2d::Size layoutSize = getSize(); cocos2d::Size layoutSize = getSize();
float leftBoundary = 0.0f; float leftBoundary = 0.0f;
for (int i=0; i<length; ++i) for (int i=0; i<length; ++i)
@ -556,8 +556,8 @@ void UILayout::doLayout()
case LAYOUT_RELATIVE: case LAYOUT_RELATIVE:
{ {
cocos2d::ccArray* layoutChildrenArray = getChildren()->data; cocos2d::ccArray* layoutChildrenArray = getChildren()->data;
int length = layoutChildrenArray->num; ssize_t length, unlayoutChildCount;
int unlayoutChildCount = length; length = unlayoutChildCount = layoutChildrenArray->num;
cocos2d::Size layoutSize = getSize(); cocos2d::Size layoutSize = getSize();
for (int i=0; i<length; i++) for (int i=0; i<length; i++)

View File

@ -92,7 +92,7 @@ void UIListView::updateInnerContainerSize()
switch (_direction) { switch (_direction) {
case SCROLLVIEW_DIR_VERTICAL: case SCROLLVIEW_DIR_VERTICAL:
{ {
int childrenCount = _items->count(); ssize_t childrenCount = _items->count();
float totalHeight = _model->getSize().height * childrenCount + (childrenCount - 1) * _itemsMargin; float totalHeight = _model->getSize().height * childrenCount + (childrenCount - 1) * _itemsMargin;
float finalWidth = _size.width; float finalWidth = _size.width;
float finalHeight = totalHeight; float finalHeight = totalHeight;
@ -101,7 +101,7 @@ void UIListView::updateInnerContainerSize()
} }
case SCROLLVIEW_DIR_HORIZONTAL: case SCROLLVIEW_DIR_HORIZONTAL:
{ {
int childrenCount = _items->count(); ssize_t childrenCount = _items->count();
float totalWidth = _model->getSize().width * childrenCount + (childrenCount - 1) * _itemsMargin; float totalWidth = _model->getSize().width * childrenCount + (childrenCount - 1) * _itemsMargin;
float finalWidth = totalWidth; float finalWidth = totalWidth;
float finalHeight = _size.height; float finalHeight = _size.height;
@ -373,7 +373,7 @@ void UIListView::refreshView()
return; return;
} }
cocos2d::ccArray* arrayItems = _items->data; cocos2d::ccArray* arrayItems = _items->data;
int length = arrayItems->num; ssize_t length = arrayItems->num;
for (int i=0; i<length; i++) for (int i=0; i<length; i++)
{ {
UIWidget* item = (UIWidget*)(arrayItems->arr[i]); UIWidget* item = (UIWidget*)(arrayItems->arr[i]);

View File

@ -91,7 +91,7 @@ void UIPageView::addWidgetToPage(UIWidget *widget, int pageIdx, bool forceCreate
{ {
return; return;
} }
int pageCount = _pages->count(); ssize_t pageCount = _pages->count();
if (pageIdx < 0 || pageIdx >= pageCount) if (pageIdx < 0 || pageIdx >= pageCount)
{ {
if (forceCreate) if (forceCreate)
@ -168,7 +168,7 @@ void UIPageView::insertPage(UILayout* page, int idx)
return; return;
} }
int pageCount = _pages->count(); ssize_t pageCount = _pages->count();
if (idx >= pageCount) if (idx >= pageCount)
{ {
addPage(page); addPage(page);
@ -186,7 +186,7 @@ void UIPageView::insertPage(UILayout* page, int idx)
page->setSize(pvSize); page->setSize(pvSize);
} }
cocos2d::ccArray* arrayPages = _pages->data; cocos2d::ccArray* arrayPages = _pages->data;
int length = arrayPages->num; ssize_t length = arrayPages->num;
for (int i=(idx+1); i<length; i++) { for (int i=(idx+1); i<length; i++) {
UIWidget* behindPage = dynamic_cast<UIWidget*>(arrayPages->arr[i]); UIWidget* behindPage = dynamic_cast<UIWidget*>(arrayPages->arr[i]);
cocos2d::Point formerPos = behindPage->getPosition(); cocos2d::Point formerPos = behindPage->getPosition();
@ -286,7 +286,7 @@ void UIPageView::updateChildrenPosition()
return; return;
} }
int pageCount = _pages->data->num; ssize_t pageCount = _pages->data->num;
if (pageCount <= 0) if (pageCount <= 0)
{ {
_curPageIdx = 0; _curPageIdx = 0;
@ -411,7 +411,7 @@ void UIPageView::onTouchEnded(const cocos2d::Point &touchPoint)
void UIPageView::movePages(float offset) void UIPageView::movePages(float offset)
{ {
cocos2d::ccArray* arrayPages = _pages->data; cocos2d::ccArray* arrayPages = _pages->data;
int length = arrayPages->num; ssize_t length = arrayPages->num;
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
{ {
UIWidget* child = (UIWidget*)(arrayPages->arr[i]); UIWidget* child = (UIWidget*)(arrayPages->arr[i]);
@ -502,7 +502,7 @@ void UIPageView::handleReleaseLogic(const cocos2d::Point &touchPoint)
if (curPage) if (curPage)
{ {
cocos2d::Point curPagePos = curPage->getPosition(); cocos2d::Point curPagePos = curPage->getPosition();
int pageCount = _pages->count(); ssize_t pageCount = _pages->count();
float curPageLocation = curPagePos.x; float curPageLocation = curPagePos.x;
float pageWidth = getSize().width; float pageWidth = getSize().width;
float boundary = pageWidth/2.0f; float boundary = pageWidth/2.0f;
@ -613,7 +613,7 @@ UIWidget* UIPageView::createCloneInstance()
void UIPageView::copyClonedWidgetChildren(UIWidget* model) void UIPageView::copyClonedWidgetChildren(UIWidget* model)
{ {
cocos2d::ccArray* arrayPages = dynamic_cast<UIPageView*>(model)->getPages()->data; cocos2d::ccArray* arrayPages = dynamic_cast<UIPageView*>(model)->getPages()->data;
int length = arrayPages->num; ssize_t length = arrayPages->num;
for (int i=0; i<length; i++) for (int i=0; i<length; i++)
{ {
UILayout* page = (UILayout*)(arrayPages->arr[i]); UILayout* page = (UILayout*)(arrayPages->arr[i]);

View File

@ -149,7 +149,7 @@ bool UIWidget::addChild(UIWidget *child)
return false; return false;
} }
child->setParent(this); child->setParent(this);
int childrenCount = _children->data->num; ssize_t childrenCount = _children->data->num;
if (childrenCount <= 0) if (childrenCount <= 0)
{ {
_children->addObject(child); _children->addObject(child);
@ -158,7 +158,7 @@ bool UIWidget::addChild(UIWidget *child)
{ {
bool seekSucceed = false; bool seekSucceed = false;
cocos2d::ccArray* arrayChildren = _children->data; cocos2d::ccArray* arrayChildren = _children->data;
for (int i=childrenCount-1; i>=0; --i) for (ssize_t i=childrenCount-1; i>=0; --i)
{ {
UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]);
if (child->getZOrder() >= widget->getZOrder()) if (child->getZOrder() >= widget->getZOrder())
@ -226,7 +226,7 @@ void UIWidget::removeAllChildren()
{ {
return; return;
} }
int times = _children->data->num; ssize_t times = _children->data->num;
for (int i=0; i<times; ++i) for (int i=0; i<times; ++i)
{ {
UIWidget* lastChild = (UIWidget*)(_children->getLastObject()); UIWidget* lastChild = (UIWidget*)(_children->getLastObject());
@ -238,7 +238,7 @@ void UIWidget::reorderChild(UIWidget* child)
{ {
CC_SAFE_RETAIN(child); CC_SAFE_RETAIN(child);
_children->removeObject(child); _children->removeObject(child);
int childrenCount = _children->data->num; ssize_t childrenCount = _children->data->num;
if (childrenCount <= 0) if (childrenCount <= 0)
{ {
_children->addObject(child); _children->addObject(child);
@ -247,7 +247,7 @@ void UIWidget::reorderChild(UIWidget* child)
{ {
bool seekSucceed = false; bool seekSucceed = false;
cocos2d::ccArray* arrayChildren = _children->data; cocos2d::ccArray* arrayChildren = _children->data;
for (int i=childrenCount-1; i>=0; --i) for (ssize_t i=childrenCount-1; i>=0; --i)
{ {
UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]); UIWidget* widget = (UIWidget*)(arrayChildren->arr[i]);
if (child->getZOrder() >= widget->getZOrder()) if (child->getZOrder() >= widget->getZOrder())
@ -287,7 +287,7 @@ void UIWidget::setEnabled(bool enabled)
dynamic_cast<UIRectClippingNode*>(_renderer)->setEnabled(enabled); dynamic_cast<UIRectClippingNode*>(_renderer)->setEnabled(enabled);
} }
cocos2d::ccArray* arrayChildren = _children->data; cocos2d::ccArray* arrayChildren = _children->data;
int childrenCount = arrayChildren->num; ssize_t childrenCount = arrayChildren->num;
for (int i = 0; i < childrenCount; i++) for (int i = 0; i < childrenCount; i++)
{ {
UIWidget* child = dynamic_cast<UIWidget*>(arrayChildren->arr[i]); UIWidget* child = dynamic_cast<UIWidget*>(arrayChildren->arr[i]);
@ -1166,7 +1166,7 @@ UIWidget* UIWidget::createCloneInstance()
void UIWidget::copyClonedWidgetChildren(UIWidget* model) void UIWidget::copyClonedWidgetChildren(UIWidget* model)
{ {
cocos2d::ccArray* arrayWidgetChildren = model->getChildren()->data; cocos2d::ccArray* arrayWidgetChildren = model->getChildren()->data;
int length = arrayWidgetChildren->num; ssize_t length = arrayWidgetChildren->num;
for (int i=0; i<length; i++) for (int i=0; i<length; i++)
{ {
UIWidget* child = (UIWidget*)(arrayWidgetChildren->arr[i]); UIWidget* child = (UIWidget*)(arrayWidgetChildren->arr[i]);

View File

@ -195,7 +195,7 @@ bool EventListenerPhysicsContact::init()
onEvent(event); onEvent(event);
}; };
return EventListenerCustom::init(std::hash<std::string>()(PHYSICSCONTACT_EVENT_NAME), func); return EventListenerCustom::init(PHYSICSCONTACT_EVENT_NAME, func);
} }
void EventListenerPhysicsContact::onEvent(EventCustom* event) void EventListenerPhysicsContact::onEvent(EventCustom* event)

@ -1 +1 @@
Subproject commit 254158d535e46848bbe08edf76bdb1fa0c3bf873 Subproject commit aaa97fbd16ff316f929b42ccdc9983f4a86472d8

View File

@ -67,7 +67,7 @@ static void serverEntryPoint(void);
js_proxy_t *_native_js_global_ht = NULL; js_proxy_t *_native_js_global_ht = NULL;
js_proxy_t *_js_native_global_ht = NULL; js_proxy_t *_js_native_global_ht = NULL;
std::unordered_map<long, js_type_class_t*> _js_global_type_map; std::unordered_map<std::string, js_type_class_t*> _js_global_type_map;
static char *_js_log_buf = NULL; static char *_js_log_buf = NULL;

View File

@ -42,8 +42,8 @@ static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) {
T* cobj = new T(); T* cobj = new T();
cobj->autorelease(); cobj->autorelease();
js_type_class_t *p; js_type_class_t *p;
long typeId = t.s_id(); std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeId); auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
p = typeMapIter->second; p = typeMapIter->second;
@ -184,8 +184,8 @@ JSBool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_
if (ret) { if (ret) {
TypeTest<PhysicsDebugNode> t; TypeTest<PhysicsDebugNode> t;
js_type_class_t *typeClass = nullptr; js_type_class_t *typeClass = nullptr;
long typeId = t.s_id(); std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeId); auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second; typeClass = typeMapIter->second;
@ -274,8 +274,8 @@ void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, cons
TypeTest<cocos2d::DrawNode> t1; TypeTest<cocos2d::DrawNode> t1;
js_type_class_t *typeClass = nullptr; js_type_class_t *typeClass = nullptr;
long typeId = t1.s_id(); std::string typeName = t1.s_name();
auto typeMapIter = _js_global_type_map.find(typeId); auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second; typeClass = typeMapIter->second;
@ -285,15 +285,15 @@ void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, cons
TypeTest<PhysicsDebugNode> t; TypeTest<PhysicsDebugNode> t;
js_type_class_t *p; js_type_class_t *p;
typeId = t.s_id(); typeName = t.s_name();
if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) if (_js_global_type_map.find(typeName) == _js_global_type_map.end())
{ {
p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->jsclass = JSB_CCPhysicsDebugNode_class; p->jsclass = JSB_CCPhysicsDebugNode_class;
p->proto = JSB_CCPhysicsDebugNode_object; p->proto = JSB_CCPhysicsDebugNode_object;
p->parentProto = typeClass->proto; p->parentProto = typeClass->proto;
_js_global_type_map.insert(std::make_pair(typeId, p)); _js_global_type_map.insert(std::make_pair(typeName, p));
} }
} }
@ -317,8 +317,8 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32
if (ret) { if (ret) {
TypeTest<PhysicsSprite> t; TypeTest<PhysicsSprite> t;
js_type_class_t *typeClass = nullptr; js_type_class_t *typeClass = nullptr;
long typeId = t.s_id(); std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeId); auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second; typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null."); CCASSERT(typeClass, "The value is null.");
@ -346,8 +346,8 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32
if (ret) { if (ret) {
TypeTest<PhysicsSprite> t; TypeTest<PhysicsSprite> t;
js_type_class_t *typeClass = nullptr; js_type_class_t *typeClass = nullptr;
long typeId = t.s_id(); std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeId); auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second; typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null."); CCASSERT(typeClass, "The value is null.");
@ -387,8 +387,8 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint
if (ret) { if (ret) {
TypeTest<PhysicsSprite> t; TypeTest<PhysicsSprite> t;
js_type_class_t *typeClass = nullptr; js_type_class_t *typeClass = nullptr;
long typeId = t.s_id(); std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeId); auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second; typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null."); CCASSERT(typeClass, "The value is null.");
@ -421,8 +421,8 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx,
if (ret) { if (ret) {
TypeTest<PhysicsSprite> t; TypeTest<PhysicsSprite> t;
js_type_class_t *typeClass = nullptr; js_type_class_t *typeClass = nullptr;
long typeId = t.s_id(); std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeId); auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second; typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null."); CCASSERT(typeClass, "The value is null.");
@ -475,8 +475,8 @@ void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj)
TypeTest<cocos2d::Sprite> t1; TypeTest<cocos2d::Sprite> t1;
js_type_class_t *typeClass = nullptr; js_type_class_t *typeClass = nullptr;
long typeId = t1.s_id(); std::string typeName = t1.s_name();
auto typeMapIter = _js_global_type_map.find(typeId); auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!"); CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second; typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null."); CCASSERT(typeClass, "The value is null.");
@ -485,14 +485,14 @@ void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj)
TypeTest<PhysicsSprite> t; TypeTest<PhysicsSprite> t;
js_type_class_t *p; js_type_class_t *p;
typeId = t.s_id(); typeName = t.s_name();
if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) if (_js_global_type_map.find(typeName) == _js_global_type_map.end())
{ {
p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->jsclass = JSPROXY_CCPhysicsSprite_class; p->jsclass = JSPROXY_CCPhysicsSprite_class;
p->proto = JSPROXY_CCPhysicsSprite_object; p->proto = JSPROXY_CCPhysicsSprite_object;
p->parentProto = typeClass->proto; p->parentProto = typeClass->proto;
_js_global_type_map.insert(std::make_pair(typeId, p)); _js_global_type_map.insert(std::make_pair(typeName, p));
} }
} }

View File

@ -1 +1 @@
6ea6ffc183c8a15eae0641c73c9886b90172266f cb193c00a0514b8292266fba55b5f97cbebb73bd

View File

@ -40,12 +40,12 @@ extern callfuncTarget_proxy_t *_callfuncTarget_native_ht;
template <class T> template <class T>
inline js_type_class_t *js_get_type_from_native(T* native_obj) { inline js_type_class_t *js_get_type_from_native(T* native_obj) {
bool found = false; bool found = false;
long typeId = typeid(*native_obj).hash_code(); std::string typeName = typeid(*native_obj).name();
auto typeProxyIter = _js_global_type_map.find(typeId); auto typeProxyIter = _js_global_type_map.find(typeName);
if (typeProxyIter == _js_global_type_map.end()) if (typeProxyIter == _js_global_type_map.end())
{ {
typeId = typeid(T).hash_code(); typeName = typeid(T).name();
typeProxyIter = _js_global_type_map.find(typeId); typeProxyIter = _js_global_type_map.find(typeName);
if (typeProxyIter != _js_global_type_map.end()) if (typeProxyIter != _js_global_type_map.end())
{ {
found = true; found = true;

View File

@ -1,26 +1,26 @@
#include "js_bindings_opengl.h" #include "js_bindings_opengl.h"
void GLNode::draw() { void GLNode::draw() {
js_proxy_t* proxy = NULL; js_proxy_t* proxy = NULL;
JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); JSContext *cx = ScriptingCore::getInstance()->getGlobalContext();
proxy = js_get_or_create_proxy<cocos2d::Node>(cx, this); proxy = js_get_or_create_proxy<cocos2d::Node>(cx, this);
if( proxy ) { if( proxy ) {
JSObject *jsObj = proxy->obj; JSObject *jsObj = proxy->obj;
if (jsObj) { if (jsObj) {
JSBool found; JSBool found;
JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
JS_HasProperty(cx, jsObj, "draw", &found); JS_HasProperty(cx, jsObj, "draw", &found);
if (found == JS_TRUE) { if (found == JS_TRUE) {
JS::RootedValue rval(cx); JS::RootedValue rval(cx);
JS::RootedValue fval(cx); JS::RootedValue fval(cx);
jsval *argv = NULL; unsigned argc=0; jsval *argv = NULL; unsigned argc=0;
JS_GetProperty(cx, jsObj, "draw", &fval); JS_GetProperty(cx, jsObj, "draw", &fval);
JS_CallFunctionValue(cx, jsObj, fval, argc, argv, rval.address()); JS_CallFunctionValue(cx, jsObj, fval, argc, argv, rval.address());
} }
}
} }
}
} }
@ -30,33 +30,33 @@ JSObject *js_cocos2dx_GLNode_prototype;
JSBool js_cocos2dx_GLNode_constructor(JSContext *cx, uint32_t argc, jsval *vp) JSBool js_cocos2dx_GLNode_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{ {
if (argc == 0) { if (argc == 0) {
GLNode* cobj = new GLNode(); GLNode* cobj = new GLNode();
cocos2d::Object *_ccobj = dynamic_cast<cocos2d::Object *>(cobj); cocos2d::Object *_ccobj = dynamic_cast<cocos2d::Object *>(cobj);
if (_ccobj) { if (_ccobj) {
_ccobj->autorelease(); _ccobj->autorelease();
}
TypeTest<GLNode> t;
js_type_class_t *typeClass = nullptr;
std::string typeName = t.s_name();
auto typeMapIter = _js_global_type_map.find(typeName);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null.");
JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
// link the native object with the javascript object
js_proxy_t *p = jsb_new_proxy(cobj, obj);
JS_AddNamedObjectRoot(cx, &p->obj, "cocos2d::GLNode");
return JS_TRUE;
} }
JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0);
TypeTest<GLNode> t; return JS_FALSE;
js_type_class_t *typeClass = nullptr;
long typeId = t.s_id();
auto typeMapIter = _js_global_type_map.find(typeId);
CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
typeClass = typeMapIter->second;
CCASSERT(typeClass, "The value is null.");
JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
// link the native object with the javascript object
js_proxy_t *p = jsb_new_proxy(cobj, obj);
JS_AddNamedObjectRoot(cx, &p->obj, "cocos2d::GLNode");
return JS_TRUE;
}
JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0);
return JS_FALSE;
} }
void js_cocos2dx_GLNode_finalize(JSFreeOp *fop, JSObject *obj) { void js_cocos2dx_GLNode_finalize(JSFreeOp *fop, JSObject *obj) {
@ -64,7 +64,7 @@ void js_cocos2dx_GLNode_finalize(JSFreeOp *fop, JSObject *obj) {
static JSBool js_cocos2dx_GLNode_ctor(JSContext *cx, uint32_t argc, jsval *vp) static JSBool js_cocos2dx_GLNode_ctor(JSContext *cx, uint32_t argc, jsval *vp)
{ {
JSObject *obj = JS_THIS_OBJECT(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp);
GLNode *nobj = new GLNode(); GLNode *nobj = new GLNode();
js_proxy_t* p = jsb_new_proxy(nobj, obj); js_proxy_t* p = jsb_new_proxy(nobj, obj);
nobj->autorelease(); nobj->autorelease();
@ -75,72 +75,72 @@ static JSBool js_cocos2dx_GLNode_ctor(JSContext *cx, uint32_t argc, jsval *vp)
JSBool js_cocos2dx_GLNode_create(JSContext *cx, uint32_t argc, jsval *vp) JSBool js_cocos2dx_GLNode_create(JSContext *cx, uint32_t argc, jsval *vp)
{ {
GLNode* ret = new GLNode(); GLNode* ret = new GLNode();
jsval jsret; jsval jsret;
do { do {
if (ret) { if (ret) {
js_proxy_t *proxy = js_get_or_create_proxy<GLNode>(cx, ret); js_proxy_t *proxy = js_get_or_create_proxy<GLNode>(cx, ret);
jsret = OBJECT_TO_JSVAL(proxy->obj); jsret = OBJECT_TO_JSVAL(proxy->obj);
} else { } else {
jsret = JSVAL_NULL; jsret = JSVAL_NULL;
} }
} while (0); } while (0);
JS_SET_RVAL(cx, vp, jsret); JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE; return JS_TRUE;
} }
extern JSObject* jsb_Node_prototype; extern JSObject* jsb_Node_prototype;
void js_register_cocos2dx_GLNode(JSContext *cx, JSObject *global) { void js_register_cocos2dx_GLNode(JSContext *cx, JSObject *global) {
js_cocos2dx_GLNode_class = (JSClass *)calloc(1, sizeof(JSClass)); js_cocos2dx_GLNode_class = (JSClass *)calloc(1, sizeof(JSClass));
js_cocos2dx_GLNode_class->name = "GLNode"; js_cocos2dx_GLNode_class->name = "GLNode";
js_cocos2dx_GLNode_class->addProperty = JS_PropertyStub; js_cocos2dx_GLNode_class->addProperty = JS_PropertyStub;
js_cocos2dx_GLNode_class->delProperty = JS_DeletePropertyStub; js_cocos2dx_GLNode_class->delProperty = JS_DeletePropertyStub;
js_cocos2dx_GLNode_class->getProperty = JS_PropertyStub; js_cocos2dx_GLNode_class->getProperty = JS_PropertyStub;
js_cocos2dx_GLNode_class->setProperty = JS_StrictPropertyStub; js_cocos2dx_GLNode_class->setProperty = JS_StrictPropertyStub;
js_cocos2dx_GLNode_class->enumerate = JS_EnumerateStub; js_cocos2dx_GLNode_class->enumerate = JS_EnumerateStub;
js_cocos2dx_GLNode_class->resolve = JS_ResolveStub; js_cocos2dx_GLNode_class->resolve = JS_ResolveStub;
js_cocos2dx_GLNode_class->convert = JS_ConvertStub; js_cocos2dx_GLNode_class->convert = JS_ConvertStub;
js_cocos2dx_GLNode_class->finalize = js_cocos2dx_GLNode_finalize; js_cocos2dx_GLNode_class->finalize = js_cocos2dx_GLNode_finalize;
js_cocos2dx_GLNode_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2); js_cocos2dx_GLNode_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = { static JSPropertySpec properties[] = {
{0, 0, 0, 0, 0} {0, 0, 0, 0, 0}
}; };
static JSFunctionSpec funcs[] = { static JSFunctionSpec funcs[] = {
JS_FN("ctor", js_cocos2dx_GLNode_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("ctor", js_cocos2dx_GLNode_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END JS_FS_END
}; };
static JSFunctionSpec st_funcs[] = { static JSFunctionSpec st_funcs[] = {
JS_FN("create", js_cocos2dx_GLNode_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("create", js_cocos2dx_GLNode_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END JS_FS_END
}; };
js_cocos2dx_GLNode_prototype = JS_InitClass( js_cocos2dx_GLNode_prototype = JS_InitClass(
cx, global, cx, global,
jsb_Node_prototype, jsb_Node_prototype,
js_cocos2dx_GLNode_class, js_cocos2dx_GLNode_class,
js_cocos2dx_GLNode_constructor, 0, // constructor js_cocos2dx_GLNode_constructor, 0, // constructor
properties, properties,
funcs, funcs,
NULL, // no static properties NULL, // no static properties
st_funcs); st_funcs);
// make the class enumerable in the registered namespace // make the class enumerable in the registered namespace
JSBool found; JSBool found;
JS_SetPropertyAttributes(cx, global, "GLNode", JSPROP_ENUMERATE | JSPROP_READONLY, &found); JS_SetPropertyAttributes(cx, global, "GLNode", JSPROP_ENUMERATE | JSPROP_READONLY, &found);
// add the proto and JSClass to the type->js info hash table // add the proto and JSClass to the type->js info hash table
TypeTest<GLNode> t; TypeTest<GLNode> t;
js_type_class_t *p; js_type_class_t *p;
long typeId = t.s_id(); std::string typeName = t.s_name();
if (_js_global_type_map.find(typeId) == _js_global_type_map.end()) if (_js_global_type_map.find(typeName) == _js_global_type_map.end())
{ {
p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); p = (js_type_class_t *)malloc(sizeof(js_type_class_t));
p->jsclass = js_cocos2dx_GLNode_class; p->jsclass = js_cocos2dx_GLNode_class;
p->proto = js_cocos2dx_GLNode_prototype; p->proto = js_cocos2dx_GLNode_prototype;
p->parentProto = jsb_Node_prototype; p->parentProto = jsb_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeId, p)); _js_global_type_map.insert(std::make_pair(typeName, p));
} }
} }

View File

@ -20,26 +20,12 @@ typedef struct js_type_class {
JSObject *parentProto; JSObject *parentProto;
} js_type_class_t; } js_type_class_t;
extern std::unordered_map<long, js_type_class_t*> _js_global_type_map; extern std::unordered_map<std::string, js_type_class_t*> _js_global_type_map;
template< typename DERIVED > template< typename DERIVED >
class TypeTest class TypeTest
{ {
public: public:
static long s_id()
{
// return id unique for DERIVED
// NOT SURE IT WILL BE REALLY UNIQUE FOR EACH CLASS!!
/* Commented by James Chen
Using 'getHashCodeByString(typeid(*native_obj).name())' instead of 'reinterpret_cast<long>(typeid(*native_obj).name());'.
Since on win32 platform, 'reinterpret_cast<long>(typeid(*native_obj).name());' invoking in cocos2d.dll and outside cocos2d.dll(in TestJavascript.exe) will return different address.
But the return string from typeid(*native_obj).name() is the same string, so we must convert the string to hash id to make sure we can get unique id.
*/
// static const long id = reinterpret_cast<long>(typeid( DERIVED ).name());
static const long id = typeid( DERIVED ).hash_code();
return id;
}
static const char* s_name() static const char* s_name()
{ {
// return id unique for DERIVED // return id unique for DERIVED

View File

@ -32,7 +32,7 @@ extern "C" {
} }
#endif #endif
std::map<long, std::string> g_luaType; std::unordered_map<std::string, std::string> g_luaType;
#if COCOS2D_DEBUG >=1 #if COCOS2D_DEBUG >=1
void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err) void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err)
@ -1640,8 +1640,8 @@ void array_to_luaval(lua_State* L,Array* inValue)
if (nullptr == obj) if (nullptr == obj)
continue; continue;
long typeId = typeid(*obj).hash_code(); std::string typeName = typeid(*obj).name();
auto iter = g_luaType.find(typeId); auto iter = g_luaType.find(typeName);
if (g_luaType.end() != iter) if (g_luaType.end() != iter)
{ {
className = iter->second; className = iter->second;
@ -1729,9 +1729,9 @@ void dictionary_to_luaval(lua_State* L, Dictionary* dict)
if (NULL == element) if (NULL == element)
continue; continue;
long typeId = typeid(element->getObject()).hash_code(); std::string typeName = typeid(element->getObject()).name();
auto iter = g_luaType.find(typeId); auto iter = g_luaType.find(typeName);
if (g_luaType.end() != iter) if (g_luaType.end() != iter)
{ {
className = iter->second; className = iter->second;

View File

@ -11,7 +11,7 @@ extern "C" {
using namespace cocos2d; using namespace cocos2d;
extern std::map<long, std::string> g_luaType; extern std::unordered_map<std::string, std::string> g_luaType;
#if COCOS2D_DEBUG >=1 #if COCOS2D_DEBUG >=1
void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err); void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err);
@ -160,8 +160,8 @@ void ccvector_to_luaval(lua_State* L,const cocos2d::Vector<T>& inValue)
if (nullptr != dynamic_cast<cocos2d::Object *>(obj)) if (nullptr != dynamic_cast<cocos2d::Object *>(obj))
{ {
long typeId = typeid(*obj).hash_code(); std::string typeName = typeid(*obj).name();
auto iter = g_luaType.find(typeId); auto iter = g_luaType.find(typeName);
if (g_luaType.end() != iter) if (g_luaType.end() != iter)
{ {
lua_pushnumber(L, (lua_Number)indexTable); lua_pushnumber(L, (lua_Number)indexTable);

View File

@ -694,8 +694,8 @@ int register_cocos2dx_extension_CCBProxy(lua_State* tolua_S)
tolua_endmodule(tolua_S); tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S); tolua_endmodule(tolua_S);
long typeId = typeid(CCBProxy).hash_code(); std::string typeName = typeid(CCBProxy).name();
g_luaType[typeId] = "CCBProxy"; g_luaType[typeName] = "CCBProxy";
return 1; return 1;
} }

View File

@ -111,9 +111,9 @@ void Control::sendActionsForControlEvents(EventType controlEvents)
// Call invocations // Call invocations
const auto& invocationList = this->dispatchListforControlEvent((Control::EventType)(1<<i)); const auto& invocationList = this->dispatchListforControlEvent((Control::EventType)(1<<i));
std::for_each(invocationList.begin(), invocationList.end(),[this](Invocation* invocation){ for(const auto &invocation : invocationList) {
invocation->invoke(this); invocation->invoke(this);
}); }
//Call ScriptFunc //Call ScriptFunc
if (kScriptTypeLua == _scriptType) if (kScriptTypeLua == _scriptType)
@ -195,7 +195,7 @@ void Control::removeTargetWithActionForControlEvent(Object* target, Handler acti
std::vector<Invocation*> tobeRemovedInvocations; std::vector<Invocation*> tobeRemovedInvocations;
//normally we would use a predicate, but this won't work here. Have to do it manually //normally we would use a predicate, but this won't work here. Have to do it manually
std::for_each(eventInvocationList.begin(), eventInvocationList.end(), [&](Invocation* invocation){ for(const auto &invocation : eventInvocationList) {
bool shouldBeRemoved=true; bool shouldBeRemoved=true;
if (target) if (target)
{ {
@ -210,11 +210,11 @@ void Control::removeTargetWithActionForControlEvent(Object* target, Handler acti
{ {
tobeRemovedInvocations.push_back(invocation); tobeRemovedInvocations.push_back(invocation);
} }
}); }
std::for_each(tobeRemovedInvocations.begin(), tobeRemovedInvocations.end(), [&](Invocation* invocation){ for(const auto &invocation : tobeRemovedInvocations) {
eventInvocationList.eraseObject(invocation, bDeleteObjects); eventInvocationList.eraseObject(invocation, bDeleteObjects);
}); }
} }
} }

View File

@ -154,17 +154,17 @@ void ScrollView::pause(Object* sender)
_container->pause(); _container->pause();
auto& children = _container->getChildren(); auto& children = _container->getChildren();
std::for_each(children.begin(), children.end(), [](Node* child){ for(const auto &child : children) {
child->pause(); child->pause();
}); }
} }
void ScrollView::resume(Object* sender) void ScrollView::resume(Object* sender)
{ {
auto& children = _container->getChildren(); auto& children = _container->getChildren();
std::for_each(children.begin(), children.end(), [](Node* child){ for(const auto &child : children) {
child->resume(); child->resume();
}); }
_container->resume(); _container->resume();
} }
@ -550,12 +550,6 @@ void ScrollView::visit()
kmGLPushMatrix(); kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
this->transformAncestors();
}
this->transform(); this->transform();
this->beforeDraw(); this->beforeDraw();
@ -594,10 +588,6 @@ void ScrollView::visit()
} }
this->afterDraw(); this->afterDraw();
if ( _grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix(); kmGLPopMatrix();
} }

View File

@ -98,7 +98,7 @@ void TableView::reloadData()
{ {
_oldDirection = Direction::NONE; _oldDirection = Direction::NONE;
std::for_each(_cellsUsed.begin(), _cellsUsed.end(), [this](TableViewCell* cell){ for(const auto &cell : _cellsUsed) {
if(_tableViewDelegate != NULL) { if(_tableViewDelegate != NULL) {
_tableViewDelegate->tableCellWillRecycle(this, cell); _tableViewDelegate->tableCellWillRecycle(this, cell);
} }
@ -110,7 +110,7 @@ void TableView::reloadData()
{ {
this->getContainer()->removeChild(cell, true); this->getContainer()->removeChild(cell, true);
} }
}); }
_indices->clear(); _indices->clear();
_cellsUsed.clear(); _cellsUsed.clear();

View File

@ -48,10 +48,10 @@ void Bug422Layer::reset()
void Bug422Layer::check(Node* t) void Bug422Layer::check(Node* t)
{ {
auto& children = t->getChildren(); auto& children = t->getChildren();
std::for_each(children.begin(), children.end(), [this](Node* child){ for(const auto &child : children) {
log("%p, rc: %d", child, child->retainCount()); log("%p, rc: %d", child, child->retainCount());
check(child); check(child);
}); }
} }
void Bug422Layer::menuCallback(Object* sender) void Bug422Layer::menuCallback(Object* sender)

View File

@ -1,4 +1,5 @@
#include "EffectsAdvancedTest.h" #include "EffectsAdvancedTest.h"
#include "CCNodeGrid.h"
enum enum
{ {
@ -20,7 +21,7 @@ void Effect1::onEnter()
{ {
EffectAdvanceTextLayer::onEnter(); EffectAdvanceTextLayer::onEnter();
auto target = getChildByTag(kTagBackground); //auto target = getChildByTag(kTagBackground);
// To reuse a grid the grid size and the grid type must be the same. // To reuse a grid the grid size and the grid type must be the same.
// in this case: // in this case:
@ -37,8 +38,8 @@ void Effect1::onEnter()
auto orbit = OrbitCamera::create(5, 1, 2, 0, 180, 0, -90); auto orbit = OrbitCamera::create(5, 1, 2, 0, 180, 0, -90);
auto orbit_back = orbit->reverse(); auto orbit_back = orbit->reverse();
target->runAction( RepeatForever::create( Sequence::create( orbit, orbit_back, NULL) ) ); //_bgNode->runAction( RepeatForever::create( Sequence::create( orbit, orbit_back, NULL) ) );
target->runAction( Sequence::create(lens, delay, reuse, waves, NULL) ); _bgNode->runAction( Sequence::create(lens, delay, reuse, waves, NULL) );
} }
std::string Effect1::title() const std::string Effect1::title() const
@ -55,7 +56,7 @@ void Effect2::onEnter()
{ {
EffectAdvanceTextLayer::onEnter(); EffectAdvanceTextLayer::onEnter();
auto target = getChildByTag(kTagBackground); //auto target = getChildByTag(kTagBackground);
// To reuse a grid the grid size and the grid type must be the same. // To reuse a grid the grid size and the grid type must be the same.
// in this case: // in this case:
@ -79,7 +80,7 @@ void Effect2::onEnter()
// id orbit_back = [orbit reverse]; // id orbit_back = [orbit reverse];
// //
// [target runAction: [RepeatForever::create: [Sequence actions: orbit, orbit_back, nil]]]; // [target runAction: [RepeatForever::create: [Sequence actions: orbit, orbit_back, nil]]];
target->runAction(Sequence::create( shaky, delay, reuse, shuffle, delay->clone(), turnoff, turnon, NULL) ); _bgNode->runAction(Sequence::create( shaky, delay, reuse, shuffle, delay->clone(), turnoff, turnon, NULL) );
} }
std::string Effect2::title() const std::string Effect2::title() const
@ -96,20 +97,18 @@ std::string Effect2::title() const
void Effect3::onEnter() void Effect3::onEnter()
{ {
EffectAdvanceTextLayer::onEnter(); EffectAdvanceTextLayer::onEnter();
//auto bg = getChildByTag(kTagBackground);
auto bg = getChildByTag(kTagBackground); //auto target1 = bg->getChildByTag(kTagSprite1);
auto target1 = bg->getChildByTag(kTagSprite1); //auto target2 = bg->getChildByTag(kTagSprite2);
auto target2 = bg->getChildByTag(kTagSprite2);
auto waves = Waves::create(5, Size(15,10), 5, 20, true, false); auto waves = Waves::create(5, Size(15,10), 5, 20, true, false);
auto shaky = Shaky3D::create(5, Size(15,10), 4, false); auto shaky = Shaky3D::create(5, Size(15,10), 4, false);
target1->runAction( RepeatForever::create( waves ) ); _target1->runAction( RepeatForever::create( waves ) );
target2->runAction( RepeatForever::create( shaky ) ); _target2->runAction( RepeatForever::create( shaky ) );
// moving background. Testing issue #244 // moving background. Testing issue #244
auto move = MoveBy::create(3, Point(200,0) ); auto move = MoveBy::create(3, Point(200,0) );
bg->runAction(RepeatForever::create( Sequence::create(move, move->reverse(), NULL) )); _bgNode->runAction(RepeatForever::create( Sequence::create(move, move->reverse(), NULL) ));
} }
std::string Effect3::title() const std::string Effect3::title() const
@ -156,6 +155,7 @@ private:
void Effect4::onEnter() void Effect4::onEnter()
{ {
EffectAdvanceTextLayer::onEnter(); EffectAdvanceTextLayer::onEnter();
//Node* gridNode = NodeGrid::create();
auto lens = Lens3D::create(10, Size(32,24), Point(100,180), 150); auto lens = Lens3D::create(10, Size(32,24), Point(100,180), 150);
auto move = JumpBy::create(5, Point(380,0), 100, 4); auto move = JumpBy::create(5, Point(380,0), 100, 4);
@ -171,9 +171,11 @@ void Effect4::onEnter()
auto pTarget = Lens3DTarget::create(lens); auto pTarget = Lens3DTarget::create(lens);
// Please make sure the target been added to its parent. // Please make sure the target been added to its parent.
this->addChild(pTarget); this->addChild(pTarget);
//gridNode->addChild(pTarget);
director->getActionManager()->addAction(seq, pTarget, false); director->getActionManager()->addAction(seq, pTarget, false);
this->runAction( lens );
_bgNode->runAction( lens );
} }
std::string Effect4::title() const std::string Effect4::title() const
@ -202,8 +204,8 @@ void Effect5::onEnter()
// [[effect copy] autorelease], // [[effect copy] autorelease],
NULL); NULL);
auto bg = getChildByTag(kTagBackground); //auto bg = getChildByTag(kTagBackground);
bg->runAction(stopEffect); _bgNode->runAction(stopEffect);
} }
std::string Effect5::title() const std::string Effect5::title() const
@ -230,8 +232,8 @@ void Issue631::onEnter()
auto effect = Sequence::create( DelayTime::create(2.0f), Shaky3D::create(5.0f, Size(5, 5), 16, false), NULL); auto effect = Sequence::create( DelayTime::create(2.0f), Shaky3D::create(5.0f, Size(5, 5), 16, false), NULL);
// cleanup // cleanup
auto bg = getChildByTag(kTagBackground); //auto bg = getChildByTag(kTagBackground);
removeChild(bg, true); removeChild(_bgNode, true);
// background // background
auto layer = LayerColor::create( Color4B(255,0,0,255) ); auto layer = LayerColor::create( Color4B(255,0,0,255) );
@ -241,15 +243,17 @@ void Issue631::onEnter()
layer->addChild(sprite, 10); layer->addChild(sprite, 10);
// foreground // foreground
auto layer2BaseGrid = NodeGrid::create();
auto layer2 = LayerColor::create(Color4B( 0, 255,0,255 ) ); auto layer2 = LayerColor::create(Color4B( 0, 255,0,255 ) );
auto fog = Sprite::create("Images/Fog.png"); auto fog = Sprite::create("Images/Fog.png");
BlendFunc bf = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}; BlendFunc bf = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA};
fog->setBlendFunc(bf); fog->setBlendFunc(bf);
layer2->addChild(fog, 1); layer2->addChild(fog, 1);
addChild(layer2, 1); addChild(layer2BaseGrid, 1);
layer2BaseGrid->addChild(layer2);
layer2->runAction( RepeatForever::create(effect) ); layer2BaseGrid->runAction( RepeatForever::create(effect) );
} }
std::string Issue631::title() const std::string Issue631::title() const
@ -335,23 +339,37 @@ void EffectAdvanceTextLayer::onEnter(void)
{ {
BaseTest::onEnter(); BaseTest::onEnter();
_bgNode = NodeGrid::create();
_bgNode->setAnchorPoint(Point(0.5,0.5));
addChild(_bgNode);
//_bgNode->setPosition( VisibleRect::center() );
auto bg = Sprite::create("Images/background3.png"); auto bg = Sprite::create("Images/background3.png");
addChild(bg, 0, kTagBackground);
bg->setPosition( VisibleRect::center() ); bg->setPosition( VisibleRect::center() );
//addChild(bg, 0, kTagBackground);
//bg->setPosition( VisibleRect::center() );
_bgNode->addChild(bg);
_target1 = NodeGrid::create();
_target1->setAnchorPoint(Point(0.5,0.5));
auto grossini = Sprite::create("Images/grossinis_sister2.png"); auto grossini = Sprite::create("Images/grossinis_sister2.png");
bg->addChild(grossini, 1, kTagSprite1); _target1->addChild(grossini);
grossini->setPosition( Point(VisibleRect::left().x+VisibleRect::getVisibleRect().size.width/3.0f, VisibleRect::bottom().y+ 200) ); _bgNode->addChild(_target1);
_target1->setPosition( Point(VisibleRect::left().x+VisibleRect::getVisibleRect().size.width/3.0f, VisibleRect::bottom().y+ 200) );
auto sc = ScaleBy::create(2, 5); auto sc = ScaleBy::create(2, 5);
auto sc_back = sc->reverse(); auto sc_back = sc->reverse();
grossini->runAction( RepeatForever::create(Sequence::create(sc, sc_back, NULL) ) ); _target1->runAction( RepeatForever::create(Sequence::create(sc, sc_back, NULL) ) );
_target2 = NodeGrid::create();
_target2->setAnchorPoint(Point(0.5,0.5));
auto tamara = Sprite::create("Images/grossinis_sister1.png"); auto tamara = Sprite::create("Images/grossinis_sister1.png");
bg->addChild(tamara, 1, kTagSprite2); _target2->addChild(tamara);
tamara->setPosition( Point(VisibleRect::left().x+2*VisibleRect::getVisibleRect().size.width/3.0f,VisibleRect::bottom().y+200) ); _bgNode->addChild(_target2);
_target2->setPosition( Point(VisibleRect::left().x+2*VisibleRect::getVisibleRect().size.width/3.0f,VisibleRect::bottom().y+200) );
auto sc2 = ScaleBy::create(2, 5); auto sc2 = ScaleBy::create(2, 5);
auto sc2_back = sc2->reverse(); auto sc2_back = sc2->reverse();
tamara->runAction( RepeatForever::create(Sequence::create(sc2, sc2_back, NULL) ) ); _target2->runAction( RepeatForever::create(Sequence::create(sc2, sc2_back, NULL) ) );
} }
EffectAdvanceTextLayer::~EffectAdvanceTextLayer(void) EffectAdvanceTextLayer::~EffectAdvanceTextLayer(void)

View File

@ -12,6 +12,10 @@ protected:
std::string _title; std::string _title;
Node* _bgNode;
Node* _target1;
Node* _target2;
public: public:
virtual void onEnter(); virtual void onEnter();
~EffectAdvanceTextLayer(void); ~EffectAdvanceTextLayer(void);

View File

@ -1,6 +1,6 @@
#include "EffectsTest.h" #include "EffectsTest.h"
#include "../testResource.h" #include "../testResource.h"
#include "CCNodeGrid.h"
enum { enum {
kTagTextLayer = 1, kTagTextLayer = 1,
@ -342,25 +342,25 @@ TextLayer::TextLayer(void)
LayerColor *background = LayerColor::create( Color4B(32,128,32,255) ); LayerColor *background = LayerColor::create( Color4B(32,128,32,255) );
this->addChild(background,-20); this->addChild(background,-20);
auto node = Node::create(); _gridNodeTarget = NodeGrid::create();
auto effect = getAction(); auto effect = getAction();
node->runAction(effect); _gridNodeTarget->runAction(effect);
addChild(node, 0, kTagBackground); addChild(_gridNodeTarget, 0, kTagBackground);
auto bg = Sprite::create(s_back3); auto bg = Sprite::create(s_back3);
node->addChild(bg, 0); _gridNodeTarget->addChild(bg, 0);
// bg->setAnchorPoint( Point::ZERO ); // bg->setAnchorPoint( Point::ZERO );
bg->setPosition(VisibleRect::center()); bg->setPosition(VisibleRect::center());
auto grossini = Sprite::create(s_pathSister2); auto grossini = Sprite::create(s_pathSister2);
node->addChild(grossini, 1); _gridNodeTarget->addChild(grossini, 1);
grossini->setPosition( Point(VisibleRect::left().x+VisibleRect::getVisibleRect().size.width/3,VisibleRect::center().y) ); grossini->setPosition( Point(VisibleRect::left().x+VisibleRect::getVisibleRect().size.width/3,VisibleRect::center().y) );
auto sc = ScaleBy::create(2, 5); auto sc = ScaleBy::create(2, 5);
auto sc_back = sc->reverse(); auto sc_back = sc->reverse();
grossini->runAction( RepeatForever::create(Sequence::create(sc, sc_back, NULL) ) ); grossini->runAction( RepeatForever::create(Sequence::create(sc, sc_back, NULL) ) );
auto tamara = Sprite::create(s_pathSister1); auto tamara = Sprite::create(s_pathSister1);
node->addChild(tamara, 1); _gridNodeTarget->addChild(tamara, 1);
tamara->setPosition( Point(VisibleRect::left().x+2*VisibleRect::getVisibleRect().size.width/3,VisibleRect::center().y) ); tamara->setPosition( Point(VisibleRect::left().x+2*VisibleRect::getVisibleRect().size.width/3,VisibleRect::center().y) );
auto sc2 = ScaleBy::create(2, 5); auto sc2 = ScaleBy::create(2, 5);
auto sc2_back = sc2->reverse(); auto sc2_back = sc2->reverse();
@ -377,9 +377,9 @@ TextLayer::TextLayer(void)
void TextLayer::checkAnim(float dt) void TextLayer::checkAnim(float dt)
{ {
auto s2 = getChildByTag(kTagBackground); //auto s2 = getChildByTag(kTagBackground);
if ( s2->getNumberOfRunningActions() == 0 && s2->getGrid() != NULL) if ( _gridNodeTarget->getNumberOfRunningActions() == 0 && _gridNodeTarget->getGrid() != NULL)
s2->setGrid(NULL);; _gridNodeTarget->setGrid(NULL);;
} }

View File

@ -14,7 +14,7 @@ class TextLayer : public BaseTest
{ {
protected: protected:
//UxString _title; //UxString _title;
NodeGrid* _gridNodeTarget;
public: public:
TextLayer(void); TextLayer(void);
~TextLayer(void); ~TextLayer(void);

View File

@ -1,6 +1,7 @@
#include "ArmatureScene.h" #include "ArmatureScene.h"
#include "../../testResource.h" #include "../../testResource.h"
#include "cocostudio/CocoStudio.h" #include "cocostudio/CocoStudio.h"
#include "CCNodeGrid.h"
using namespace cocos2d; using namespace cocos2d;
@ -574,6 +575,7 @@ void TestAnimationEvent::callback2()
void TestFrameEvent::onEnter() void TestFrameEvent::onEnter()
{ {
ArmatureTestLayer::onEnter(); ArmatureTestLayer::onEnter();
_gridNode = NodeGrid::create();
Armature *armature = Armature::create("HeroAnimation"); Armature *armature = Armature::create("HeroAnimation");
armature->getAnimation()->play("attack"); armature->getAnimation()->play("attack");
armature->getAnimation()->setSpeedScale(0.5); armature->getAnimation()->setSpeedScale(0.5);
@ -584,7 +586,9 @@ void TestFrameEvent::onEnter()
* To disconnect this event, just setFrameEventCallFunc(nullptr); * To disconnect this event, just setFrameEventCallFunc(nullptr);
*/ */
armature->getAnimation()->setFrameEventCallFunc(CC_CALLBACK_0(TestFrameEvent::onFrameEvent, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); armature->getAnimation()->setFrameEventCallFunc(CC_CALLBACK_0(TestFrameEvent::onFrameEvent, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
addChild(armature);
_gridNode->addChild(armature);
addChild(_gridNode);
schedule( schedule_selector(TestFrameEvent::checkAction) ); schedule( schedule_selector(TestFrameEvent::checkAction) );
} }
@ -596,20 +600,19 @@ void TestFrameEvent::onFrameEvent(Bone *bone, const char *evt, int originFrameIn
{ {
CCLOG("(%s) emit a frame event (%s) at frame index (%d).", bone->getName().c_str(), evt, currentFrameIndex); CCLOG("(%s) emit a frame event (%s) at frame index (%d).", bone->getName().c_str(), evt, currentFrameIndex);
if (!_gridNode->getActionByTag(FRAME_EVENT_ACTION_TAG) || _gridNode->getActionByTag(FRAME_EVENT_ACTION_TAG)->isDone())
{
_gridNode->stopAllActions();
// if (!this->getActionByTag(FRAME_EVENT_ACTION_TAG) || this->getActionByTag(FRAME_EVENT_ACTION_TAG)->isDone()) ActionInterval *action = ShatteredTiles3D::create(0.2f, Size(16,12), 5, false);
// { action->setTag(FRAME_EVENT_ACTION_TAG);
// this->stopAllActions(); _gridNode->runAction(action);
// }
// ActionInterval *action = ShatteredTiles3D::create(0.2f, Size(16,12), 5, false);
// action->setTag(FRAME_EVENT_ACTION_TAG);
// this->runAction(action);
// }
} }
void TestFrameEvent::checkAction(float dt) void TestFrameEvent::checkAction(float dt)
{ {
if ( this->getNumberOfRunningActions() == 0 && this->getGrid() != nullptr) if ( _gridNode->getNumberOfRunningActions() == 0 && _gridNode->getGrid() != nullptr)
this->setGrid(nullptr); _gridNode->setGrid(nullptr);
} }
@ -1428,9 +1431,6 @@ void TestEasing::updateSubTitle()
label->setString(str.c_str()); label->setString(str.c_str());
} }
void TestChangeAnimationInternal::onEnter() void TestChangeAnimationInternal::onEnter()
{ {
ArmatureTestLayer::onEnter(); ArmatureTestLayer::onEnter();
@ -1451,11 +1451,11 @@ void TestChangeAnimationInternal::onExit()
{ {
Director::getInstance()->setAnimationInterval(1/60.0f); Director::getInstance()->setAnimationInterval(1/60.0f);
} }
std::string TestChangeAnimationInternal::title() std::string TestChangeAnimationInternal::title() const
{ {
return "Test change animation internal"; return "Test change animation internal";
} }
std::string TestChangeAnimationInternal::subtitle() std::string TestChangeAnimationInternal::subtitle() const
{ {
return "Touch to change animation internal"; return "Touch to change animation internal";
} }

View File

@ -168,6 +168,8 @@ public:
virtual std::string title() const override; virtual std::string title() const override;
void onFrameEvent(cocostudio::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex); void onFrameEvent(cocostudio::Bone *bone, const char *evt, int originFrameIndex, int currentFrameIndex);
void checkAction(float dt); void checkAction(float dt);
protected:
NodeGrid* _gridNode;
}; };
@ -362,7 +364,7 @@ public:
class TestEasing : public ArmatureTestLayer class TestEasing : public ArmatureTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter() override;
virtual std::string title() const override; virtual std::string title() const override;
virtual std::string subtitle() const override; virtual std::string subtitle() const override;
@ -376,10 +378,10 @@ public:
class TestChangeAnimationInternal : public ArmatureTestLayer class TestChangeAnimationInternal : public ArmatureTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter()override;
virtual void onExit(); virtual void onExit() override;
virtual std::string title(); virtual std::string title() const override;
virtual std::string subtitle(); virtual std::string subtitle() const override;
void onTouchesEnded(const std::vector<Touch*>& touches, Event* event); void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
}; };

View File

@ -118,9 +118,9 @@ static void setEnableRecursiveCascading(Node* node, bool enable)
node->setCascadeOpacityEnabled(enable); node->setCascadeOpacityEnabled(enable);
auto& children = node->getChildren(); auto& children = node->getChildren();
std::for_each(children.begin(), children.end(), [enable](Node* child){ for(const auto &child : children) {
setEnableRecursiveCascading(child, enable); setEnableRecursiveCascading(child, enable);
}); }
} }
// LayerTestCascadingOpacityA // LayerTestCascadingOpacityA
@ -899,12 +899,12 @@ void LayerBug3162A::step(float dt)
_layer[0]->setCascadeOpacityEnabled(!_layer[0]->isCascadeOpacityEnabled()); _layer[0]->setCascadeOpacityEnabled(!_layer[0]->isCascadeOpacityEnabled());
} }
std::string LayerBug3162A::title() std::string LayerBug3162A::title() const
{ {
return "Bug 3162 red layer cascade opacity eable/disable"; return "Bug 3162 red layer cascade opacity eable/disable";
} }
std::string LayerBug3162A::subtitle() std::string LayerBug3162A::subtitle() const
{ {
return "g and b layer opacity is effected/diseffected with r layer"; return "g and b layer opacity is effected/diseffected with r layer";
} }
@ -945,12 +945,12 @@ void LayerBug3162B::step(float dt)
_layer[0]->setCascadeColorEnabled(!_layer[0]->isCascadeColorEnabled()); _layer[0]->setCascadeColorEnabled(!_layer[0]->isCascadeColorEnabled());
} }
std::string LayerBug3162B::title() std::string LayerBug3162B::title() const
{ {
return "Bug 3162 bottom layer cascade color eable/disable"; return "Bug 3162 bottom layer cascade color eable/disable";
} }
std::string LayerBug3162B::subtitle() std::string LayerBug3162B::subtitle() const
{ {
return "u and m layer color is effected/diseffected with b layer"; return "u and m layer color is effected/diseffected with b layer";
} }

View File

@ -178,9 +178,9 @@ class LayerBug3162A : public LayerTest
{ {
public: public:
CREATE_FUNC(LayerBug3162A); CREATE_FUNC(LayerBug3162A);
virtual void onEnter(); virtual void onEnter() override;
virtual std::string title(); virtual std::string title() const override;
virtual std::string subtitle(); virtual std::string subtitle() const override;
void step(float dt); void step(float dt);
@ -192,9 +192,9 @@ class LayerBug3162B : public LayerTest
{ {
public: public:
CREATE_FUNC(LayerBug3162B); CREATE_FUNC(LayerBug3162B);
virtual void onEnter(); virtual void onEnter() override;
virtual std::string title(); virtual std::string title() const override;
virtual std::string subtitle(); virtual std::string subtitle() const override;
void step(float dt); void step(float dt);

View File

@ -88,9 +88,7 @@ MenuLayerMainMenu::MenuLayerMainMenu()
auto s = Director::getInstance()->getWinSize(); auto s = Director::getInstance()->getWinSize();
int i=0; int i=0;
auto& children = menu->getChildren(); for(const auto &child : menu->getChildren()) {
std::for_each(children.begin(), children.end(), [&i, &s](Node* child){
auto dstPoint = child->getPosition(); auto dstPoint = child->getPosition();
int offset = (int) (s.width/2 + 50); int offset = (int) (s.width/2 + 50);
if( i % 2 == 0) if( i % 2 == 0)
@ -101,7 +99,7 @@ MenuLayerMainMenu::MenuLayerMainMenu()
EaseElasticOut::create(MoveBy::create(2, Point(dstPoint.x - offset,0)), 0.35f) EaseElasticOut::create(MoveBy::create(2, Point(dstPoint.x - offset,0)), 0.35f)
); );
i++; i++;
}); }
_disabledItem = item3; item3->retain(); _disabledItem = item3; item3->retain();
_disabledItem->setEnabled( false ); _disabledItem->setEnabled( false );

View File

@ -1530,13 +1530,13 @@ void MultipleParticleSystems::update(float dt)
unsigned int count = 0; unsigned int count = 0;
std::for_each(_children.begin(), _children.end(), [&count](Node* child){ for(const auto &child : _children) {
auto item = dynamic_cast<ParticleSystem*>(child); auto item = dynamic_cast<ParticleSystem*>(child);
if (item != NULL) if (item != NULL)
{ {
count += item->getParticleCount(); count += item->getParticleCount();
} }
}); }
char str[100] = {0}; char str[100] = {0};
sprintf(str, "%4d", count); sprintf(str, "%4d", count);
@ -1578,18 +1578,16 @@ void MultipleParticleSystemsBatched::update(float dt)
{ {
auto atlas = (LabelAtlas*) getChildByTag(kTagParticleCount); auto atlas = (LabelAtlas*) getChildByTag(kTagParticleCount);
unsigned count = 0; int count = 0;
auto batchNode = getChildByTag(2); auto batchNode = getChildByTag(2);
for(const auto &child : batchNode->getChildren()) {
auto& children = batchNode->getChildren();
std::for_each(children.begin(), children.end(), [&count](Node* child){
auto item = dynamic_cast<ParticleSystem*>(child); auto item = dynamic_cast<ParticleSystem*>(child);
if (item != NULL) if (item != NULL)
{ {
count += item->getParticleCount(); count += item->getParticleCount();
} }
}); }
char str[50] = {0}; char str[50] = {0};
sprintf(str, "%4d", count); sprintf(str, "%4d", count);
@ -1668,18 +1666,16 @@ void AddAndDeleteParticleSystems::update(float dt)
{ {
auto atlas = (LabelAtlas*) getChildByTag(kTagParticleCount); auto atlas = (LabelAtlas*) getChildByTag(kTagParticleCount);
unsigned int count = 0; int count = 0;
auto batchNode = getChildByTag(2); auto batchNode = getChildByTag(2);
for(const auto &child : batchNode->getChildren()) {
auto& children = batchNode->getChildren();
std::for_each(children.begin(), children.end(), [&count](Node* child){
auto item = dynamic_cast<ParticleSystem*>(child); auto item = dynamic_cast<ParticleSystem*>(child);
if (item != NULL) if (item != NULL)
{ {
count += item->getParticleCount(); count += item->getParticleCount();
} }
}); }
char str[100] = {0}; char str[100] = {0};
sprintf(str, "%4d", count); sprintf(str, "%4d", count);
@ -1805,18 +1801,16 @@ void ReorderParticleSystems::update(float dt)
{ {
auto atlas = static_cast<LabelAtlas*>(getChildByTag(kTagParticleCount)); auto atlas = static_cast<LabelAtlas*>(getChildByTag(kTagParticleCount));
unsigned int count = 0; int count = 0;
auto batchNode = getChildByTag(2); auto batchNode = getChildByTag(2);
for(const auto &child : batchNode->getChildren()) {
auto& children = batchNode->getChildren();
std::for_each(children.begin(), children.end(), [&count](Node* child){
auto item = dynamic_cast<ParticleSystem*>(child); auto item = dynamic_cast<ParticleSystem*>(child);
if (item != nullptr) if (item != nullptr)
{ {
count += item->getParticleCount(); count += item->getParticleCount();
} }
}); }
char str[100] = {0}; char str[100] = {0};
sprintf(str, "%4d", count); sprintf(str, "%4d", count);
atlas->setString(str); atlas->setString(str);

View File

@ -162,7 +162,7 @@ public:
_title = file; _title = file;
} }
virtual void onEnter(); virtual void onEnter();
virtual std::string title() virtual std::string title() const override
{ {
return _title; return _title;
} }

Some files were not shown because too many files have changed in this diff Show More