code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __CCSCHEDULER_H__
#define __CCSCHEDULER_H__

#include "CCObject.h"
#include "support/data_support/uthash.h"

namespace   cocos2d {

//
// CCTimer
//
/** @brief Light weight timer */
class CC_DLL CCTimer : public CCObject
{
public:
	CCTimer(void);

	/** get interval in seconds */
	inline ccTime getInterval(void) { return m_fInterval; }
	/** set interval in seconds */
	inline void setInterval(ccTime fInterval){ m_fInterval = fInterval; }

    /** Initializes a timer with a target and a selector. */
	bool initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector);

	/** Initializes a timer with a target, a selector and an interval in seconds. */
    bool initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector, ccTime fSeconds);

    /** Initializes a timer with a script callback function and an interval in seconds. */
    bool initWithScriptHandler(int nHandler, ccTime fSeconds);

	/** triggers the timer */
	void update(ccTime dt);

public:
	/** Allocates a timer with a target and a selector. */
	static CCTimer* timerWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector);

	/** Allocates a timer with a target, a selector and an interval in seconds. */
	static CCTimer* timerWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector, ccTime fSeconds);

    /** Allocates a timer with a script callback function and an interval in seconds. */
    static CCTimer* timerWithScriptHandler(int nHandler, ccTime fSeconds);

public:
	SEL_SCHEDULE m_pfnSelector;
	ccTime m_fInterval;

protected:
	CCObject *m_pTarget;
	ccTime m_fElapsed;
    int m_nScriptHandler;
};

//
// CCScheduler
//
struct _listEntry;
struct _hashSelectorEntry;
struct _hashUpdateEntry;

class CCArray;

/** @brief Scheduler is responsible of triggering the scheduled callbacks.
You should not use NSTimer. Instead use this class.

There are 2 different types of callbacks (selectors):

- update selector: the 'update' selector will be called every frame. You can customize the priority.
- custom selector: A custom selector will be called every frame, or with a custom interval of time

The 'custom selectors' should be avoided when possible. It is faster, and consumes less memory to use the 'update selector'.

*/
class CC_DLL CCScheduler : public CCObject
{
public:
    ~CCScheduler(void);

	inline ccTime getTimeScale(void) { return m_fTimeScale; }
	/** Modifies the time of all scheduled callbacks.
	You can use this property to create a 'slow motion' or 'fast forward' effect.
	Default is 1.0. To create a 'slow motion' effect, use values below 1.0.
	To create a 'fast forward' effect, use values higher than 1.0.
	@since v0.8
	@warning It will affect EVERY scheduled selector / action.
	*/
	inline void setTimeScale(ccTime fTimeScale) { m_fTimeScale = fTimeScale; }

	/** 'tick' the scheduler.
	 You should NEVER call this method, unless you know what you are doing.
	 */
	void tick(ccTime dt);

	/** The scheduled method will be called every 'interval' seconds.
	 If paused is YES, then it won't be called until it is resumed.
	 If 'interval' is 0, it will be called every frame, but if so, it recommened to use 'scheduleUpdateForTarget:' instead.
	 If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again.

	 @since v0.99.3
	 */
	void scheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget, ccTime fInterval, bool bPaused);
	/** Schedules the 'update' selector for a given target with a given priority.
	 The 'update' selector will be called every frame.
	 The lower the priority, the earlier it is called.
	 @since v0.99.3
	 */
	void scheduleUpdateForTarget(CCObject *pTarget, int nPriority, bool bPaused);

	/** Unschedule a selector for a given target.
	 If you want to unschedule the "update", use unscheudleUpdateForTarget.
	 @since v0.99.3
	 */
	void unscheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget);

	/** Unschedules the update selector for a given target
	 @since v0.99.3
	 */
	void unscheduleUpdateForTarget(const CCObject *pTarget);

	/** Unschedules all selectors for a given target.
	 This also includes the "update" selector.
	 @since v0.99.3
	 */
	void unscheduleAllSelectorsForTarget(CCObject *pTarget);

	/** Unschedules all selectors from all targets.
	 You should NEVER call this method, unless you know what you are doing.

	 @since v0.99.3
	 */
	void unscheduleAllSelectors(void);

    /** The scheduled script callback will be called every 'interval' seconds.
	 If paused is YES, then it won't be called until it is resumed.
	 If 'interval' is 0, it will be called every frame.
     return schedule script entry ID, used for unscheduleScriptFunc().
     */
    unsigned int scheduleScriptFunc(int nHandler, ccTime fInterval, bool bPaused);

	/** Unschedule a script entry. */
    void unscheduleScriptEntry(unsigned int uScheduleScriptEntryID);

	/** Pauses the target.
	 All scheduled selectors/update for a given target won't be 'ticked' until the target is resumed.
	 If the target is not present, nothing happens.
	 @since v0.99.3
	 */
	void pauseTarget(CCObject *pTarget);

	/** Resumes the target.
	 The 'target' will be unpaused, so all schedule selectors/update will be 'ticked' again.
	 If the target is not present, nothing happens.
	 @since v0.99.3
	 */
	void resumeTarget(CCObject *pTarget);

    /** Returns whether or not the target is paused
    @since v1.0.0
    */
    bool isTargetPaused(CCObject *pTarget);

public:
    /** returns a shared instance of the Scheduler */
	static CCScheduler* sharedScheduler(void);

	/** purges the shared scheduler. It releases the retained instance.
	 @since v0.99.0
	 */
	static void purgeSharedScheduler(void);

private:
	void removeHashElement(struct _hashSelectorEntry *pElement);
	void removeUpdateFromHash(struct _listEntry *entry);
	CCScheduler();
	bool init(void);

	// update specific

	void priorityIn(struct _listEntry **ppList, CCObject *pTarget, int nPriority, bool bPaused);
	void appendIn(struct _listEntry **ppList, CCObject *pTarget, bool bPaused);

protected:
	ccTime m_fTimeScale;

	//
	// "updates with priority" stuff
	//
	struct _listEntry *m_pUpdatesNegList;		// list of priority < 0
	struct _listEntry *m_pUpdates0List;			// list priority == 0
	struct _listEntry *m_pUpdatesPosList;		// list priority > 0
	struct _hashUpdateEntry *m_pHashForUpdates; // hash used to fetch quickly the list entries for pause,delete,etc

	// Used for "selectors with interval"
	struct _hashSelectorEntry *m_pHashForSelectors;
	struct _hashSelectorEntry *m_pCurrentTarget;
	bool m_bCurrentTargetSalvaged;
	// If true unschedule will not remove anything from a hash. Elements will only be marked for deletion.
	bool m_bUpdateHashLocked;
    CCArray* m_pScriptHandlerEntries;
};
}//namespace   cocos2d

#endif // __CCSCHEDULER_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __SCRIPT_SUPPORT_H__
#define __SCRIPT_SUPPORT_H__

#include "CCCommon.h"
#include "CCTouch.h"
#include "CCSet.h"

typedef struct lua_State lua_State;

NS_CC_BEGIN

class CCTimer;

// Lua support for CCScheduler
class CCSchedulerScriptHandlerEntry : public CCObject
{
public:
    // nHandler return by tolua_ref_function(), called from LuaCocos2d.cpp
    static CCSchedulerScriptHandlerEntry* entryWithHandler(int nHandler, ccTime fInterval, bool bPaused);
    ~CCSchedulerScriptHandlerEntry(void);

    inline cocos2d::CCTimer* getTimer(void) {
        return m_pTimer;
    }

    inline bool isPaused(void) {
        return m_bPaused;
    }

    inline int getEntryID(void) {
        return m_nEntryID;
    }

    inline void markedForDeletion(void) {
        m_bMarkedForDeletion = true;
    }

    inline bool isMarkedForDeletion(void) {
        return m_bMarkedForDeletion;
    }

private:
    CCSchedulerScriptHandlerEntry(void);
    bool initWithHandler(int nHandler, ccTime fInterval, bool bPaused);

    cocos2d::CCTimer*   m_pTimer;
    bool                m_bPaused;
    bool                m_bMarkedForDeletion;
    int                 m_nHandler;
    int                 m_nEntryID;
};

// Lua support for touch events
class CCTouchScriptHandlerEntry : public CCObject
{
public:
    static CCTouchScriptHandlerEntry* entryWithHandler(int nHandler, bool bIsMultiTouches, int nPriority, bool bSwallowsTouches);
    ~CCTouchScriptHandlerEntry(void);

    inline int getHandler(void) {
        return m_nHandler;
    }

    inline bool getIsMultiTouches(void) {
        return m_bIsMultiTouches;
    }

    inline int getPriority(void) {
        return m_nPriority;
    }

    inline bool getSwallowsTouches(void) {
        return m_bSwallowsTouches;
    }

private:
    CCTouchScriptHandlerEntry(void);
    bool initWithHandler(int nHandler, bool bIsMultiTouches, int nPriority, bool bSwallowsTouches);

    int     m_nHandler;
    bool    m_bIsMultiTouches;
    int     m_nPriority;
    bool    m_bSwallowsTouches;
};

class CC_DLL CCScriptEngineProtocol : public CCObject
{
public:
    /**
     @brief Method used to get a pointer to the lua_State that the script module is attached to.
     @return A pointer to the lua_State that the script module is attached to.
     */
    virtual lua_State* getLuaState(void) = 0;

    /**
     @brief Remove CCObject from lua state
     @param object to remove
     */
    virtual void removeCCObjectByID(int nLuaID) = 0;

    /**
     @brief Remove Lua function handler
     */
    virtual void removeLuaHandler(int nHandler) = 0;

    /**
     @brief Add a path to find lua files in
     @param path to be added to the Lua path
     */
    virtual void addSearchPath(const char* path) = 0;

    /**
     @brief Execute script code contained in the given string.
     @param codes holding the valid script code that should be executed.
     @return 0 if the string is excuted correctly.
     @return other if the string is excuted wrongly.
     */
    virtual int executeString(const char* codes) = 0;

    /**
     @brief Execute a script file.
     @param filename String object holding the filename of the script file that is to be executed
     */
    virtual int executeScriptFile(const char* filename) = 0;

    /**
     @brief Execute a scripted global function.
     @brief The function should not take any parameters and should return an integer.
     @param functionName String object holding the name of the function, in the global script environment, that is to be executed.
     @return The integer value returned from the script function.
     */
    virtual int executeGlobalFunction(const char* functionName) = 0;

    /**
     @brief Execute a function by handler
     @param The function handler
     @param Number of parameters
     @return The integer value returned from the script function.
     */
    virtual int executeFunctionByHandler(int nHandler, int numArgs = 0) = 0;
    virtual int executeFunctionWithIntegerData(int nHandler, int data) = 0;
    virtual int executeFunctionWithFloatData(int nHandler, float data) = 0;
    virtual int executeFunctionWithBooleanData(int nHandler, bool data) = 0;
    virtual int executeFunctionWithCCObject(int nHandler, CCObject* pObject, const char* typeName) = 0;
    virtual int pushIntegerToLuaStack(int data) = 0;
    virtual int pushFloatToLuaStack(int data) = 0;
    virtual int pushBooleanToLuaStack(int data) = 0;
    virtual int pushCCObjectToLuaStack(CCObject* pObject, const char* typeName) = 0;

    // functions for excute touch event
    virtual int executeTouchEvent(int nHandler, int eventType, CCTouch *pTouch) = 0;
    virtual int executeTouchesEvent(int nHandler, int eventType, CCSet *pTouches) = 0;

    // execute a schedule function
    virtual int executeSchedule(int nHandler, ccTime dt) = 0;
};

/**
 CCScriptEngineManager is a singleton which holds an object instance of CCScriptEngineProtocl
 It helps cocos2d-x and the user code to find back LuaEngine object
 @since v0.99.5-x-0.8.5
 */
class CC_DLL CCScriptEngineManager
{
public:
	~CCScriptEngineManager(void);

	CCScriptEngineProtocol* getScriptEngine(void) {
        return m_pScriptEngine;
    }
	void setScriptEngine(CCScriptEngineProtocol *pScriptEngine);
    void removeScriptEngine(void);

    static CCScriptEngineManager* sharedManager(void);
    static void purgeSharedManager(void);

private:
    CCScriptEngineManager(void)
    : m_pScriptEngine(NULL)
    {
    }

	CCScriptEngineProtocol *m_pScriptEngine;
};

NS_CC_END

#endif // __SCRIPT_SUPPORT_H__

license: mit


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __NS_SET_H__
#define __NS_SET_H__

#include <set>
#include "CCObject.h"

namespace   cocos2d {

typedef std::set<CCObject *>::iterator CCSetIterator;

class CC_DLL CCSet : public CCObject
{
public:
	CCSet(void);
	CCSet(const CCSet &rSetObject);
	virtual ~CCSet(void);

	/**
	*@brief Return a copy of the CCSet, it will copy all the elelments.
	*/
	CCSet* copy();
	/**
	*@brief It is the same as copy().
	*/
	CCSet* mutableCopy();
	/**
	*@brief Return the number of elements the CCSet contains.
	*/
	int count();
	/**
	*@brief Add a element into CCSet, it will retain the element.
	*/
	void addObject(CCObject *pObject);
	/**
	*@brief Remove the given element, nothing todo if no element equals pObject.
	*/
	void removeObject(CCObject *pObject);
	/**
	*@brief Check if CCSet contains a element equals pObject.
	*/
	bool containsObject(CCObject *pObject);
	/**
	*@brief Return the iterator that points to the first element.
	*/
	CCSetIterator begin();
	/**
	*@brief Return the iterator that points to the poisition after the last element.
	*/
	CCSetIterator end();
	/**
	*@brief Return the first element if it contains elements, or null if it doesn't contain any element.
	*/
    CCObject* anyObject();

private:
    std::set<CCObject *> *m_pSet;
};

}//namespace   cocos2d

#endif // __NS_SET_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __SPITE_NODE_CCSPRITE_H__
#define __SPITE_NODE_CCSPRITE_H__

#include "CCNode.h"
#include "CCProtocols.h"
#include "CCTextureAtlas.h"
#include "ccTypes.h"
#include "CCMutableDictionary.h"

#include <string>
namespace   cocos2d {

class CCSpriteBatchNode;
class CCSpriteFrame;
class CCAnimation;
class CCRect;
class CCPoint;
class CCSize;
class CCTexture2D;
struct transformValues_;

#define CCSpriteIndexNotInitialized 0xffffffff 	/// CCSprite invalid index on the CCSpriteBatchode

/**
 Whether or not an CCSprite will rotate, scale or translate with it's parent.
 Useful in health bars, when you want that the health bar translates with it's parent but you don't
 want it to rotate with its parent.
 @since v0.99.0
 */
typedef enum {
	//! Translate with it's parent
	CC_HONOR_PARENT_TRANSFORM_TRANSLATE =  1 << 0,
	//! Rotate with it's parent
	CC_HONOR_PARENT_TRANSFORM_ROTATE	=  1 << 1,
	//! Scale with it's parent
	CC_HONOR_PARENT_TRANSFORM_SCALE		=  1 << 2,
    //! Skew with it's parent
    CC_HONOR_PARENT_TRANSFORM_SKEW		=  1 << 3,

	//! All possible transformation enabled. Default value.
	CC_HONOR_PARENT_TRANSFORM_ALL		=  CC_HONOR_PARENT_TRANSFORM_TRANSLATE | CC_HONOR_PARENT_TRANSFORM_ROTATE | CC_HONOR_PARENT_TRANSFORM_SCALE | CC_HONOR_PARENT_TRANSFORM_SKEW,

} ccHonorParentTransform;

/** CCSprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) )
*
* CCSprite can be created with an image, or with a sub-rectangle of an image.
*
* If the parent or any of its ancestors is a CCSpriteBatchNode then the following features/limitations are valid
*	- Features when the parent is a CCBatchNode:
*		- MUCH faster rendering, specially if the CCSpriteBatchNode has many children. All the children will be drawn in a single batch.
*
*	- Limitations
*		- Camera is not supported yet (eg: CCOrbitCamera action doesn't work)
*		- GridBase actions are not supported (eg: CCLens, CCRipple, CCTwirl)
*		- The Alias/Antialias property belongs to CCSpriteBatchNode, so you can't individually set the aliased property.
*		- The Blending function property belongs to CCSpriteBatchNode, so you can't individually set the blending function property.
*		- Parallax scroller is not supported, but can be simulated with a "proxy" sprite.
*
*  If the parent is an standard CCNode, then CCSprite behaves like any other CCNode:
*    - It supports blending functions
*    - It supports aliasing / antialiasing
*    - But the rendering will be slower: 1 draw per children.
*
* The default anchorPoint in CCSprite is (0.5, 0.5).
*/
class CC_DLL CCSprite : public CCNode, public CCTextureProtocol, public CCRGBAProtocol
{
	/** Opacity: conforms to CCRGBAProtocol protocol */
	CC_PROPERTY(GLubyte, m_nOpacity, Opacity)
	/** Color: conforms with CCRGBAProtocol protocol */
	CC_PROPERTY_PASS_BY_REF(ccColor3B, m_sColor, Color);
public:
	virtual void draw(void);

public:
	// attributes

	/** whether or not the Sprite needs to be updated in the Atlas */
	inline bool isDirty(void) { return m_bDirty; }
	/** make the Sprite to be updated in the Atlas. */
	inline void setDirty(bool bDirty) { m_bDirty = bDirty; }

	/** get the quad (tex coords, vertex coords and color) information */
	inline ccV3F_C4B_T2F_Quad getQuad(void) { return m_sQuad; }

	/** returns whether or not the texture rectangle is rotated */
	inline bool isTextureRectRotated(void) { return m_bRectRotated; }

	/** Set the index used on the TextureAtlas. */
	inline unsigned int getAtlasIndex(void) { return m_uAtlasIndex; }
	/** Set the index used on the TextureAtlas.
	@warning Don't modify this value unless you know what you are doing
	*/
	inline void setAtlasIndex(unsigned int uAtlasIndex) { m_uAtlasIndex = uAtlasIndex; }

	/** returns the rect of the CCSprite in points */
	inline const CCRect& getTextureRect(void) { return m_obRect; }

	/** whether or not the Sprite is rendered using a CCSpriteBatchNode */
	inline bool isUsesBatchNode(void) { return m_bUsesBatchNode; }
	/** make the Sprite been rendered using a CCSpriteBatchNode */
	inline void setUsesSpriteBatchNode(bool bUsesSpriteBatchNode) { m_bUsesBatchNode = bUsesSpriteBatchNode; }

	inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas; }
	inline void setTextureAtlas(CCTextureAtlas *pobTextureAtlas) { m_pobTextureAtlas = pobTextureAtlas; }

	inline CCSpriteBatchNode* getSpriteBatchNode(void) { return m_pobBatchNode; }
	inline void setSpriteBatchNode(CCSpriteBatchNode *pobSpriteBatchNode) { m_pobBatchNode = pobSpriteBatchNode; }

	/** whether or not to transform according to its parent transformations.
	 Useful for health bars. eg: Don't rotate the health bar, even if the parent rotates.
	 IMPORTANT: Only valid if it is rendered using an CCSpriteSheet.
	 @since v0.99.0
	 */
	inline ccHonorParentTransform getHonorParentTransform(void) { return m_eHonorParentTransform; }
	/** whether or not to transform according to its parent transformations.
	Useful for health bars. eg: Don't rotate the health bar, even if the parent rotates.
	IMPORTANT: Only valid if it is rendered using an CCSpriteSheet.
	@since v0.99.0
	*/
	inline void setHonorParentTransform(ccHonorParentTransform eHonorParentTransform) { m_eHonorParentTransform = eHonorParentTransform; }

	/** Get offset position of the sprite. Calculated automatically by editors like Zwoptex.
	 @since v0.99.0
	 */
	inline const CCPoint& getOffsetPositionInPixels(void) { return m_obOffsetPositionInPixels; }

	/** conforms to CCTextureProtocol protocol */
	inline ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; }
	/** conforms to CCTextureProtocol protocol */
	inline void setBlendFunc(ccBlendFunc blendFunc) { m_sBlendFunc = blendFunc; }

public:
	/** Creates an sprite with a texture.
	 The rect used will be the size of the texture.
	 The offset will be (0,0).
	 */
	static CCSprite* spriteWithTexture(CCTexture2D *pTexture);

	/** Creates an sprite with a texture and a rect.
	 The offset will be (0,0).
	 */
	static CCSprite* spriteWithTexture(CCTexture2D *pTexture, const CCRect& rect);

	/** Creates an sprite with a texture, a rect and offset. */
    static CCSprite* spriteWithTexture(CCTexture2D *pTexture, const CCRect& rect, const CCPoint& offset);

	/** Creates an sprite with an sprite frame. */
	static CCSprite* spriteWithSpriteFrame(CCSpriteFrame *pSpriteFrame);

	/** Creates an sprite with an sprite frame name.
	 An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.
	 If the CCSpriteFrame doesn't exist it will raise an exception.
	 @since v0.9
	 */
	static CCSprite* spriteWithSpriteFrameName(const char *pszSpriteFrameName);

	/** Creates an sprite with an image filename.
	 The rect used will be the size of the image.
	 The offset will be (0,0).
	 */
    static CCSprite* spriteWithFile(const char *pszFileName);

	/** Creates an sprite with an image filename and a rect.
	 The offset will be (0,0).
	 */
	static CCSprite* spriteWithFile(const char *pszFileName, const CCRect& rect);

	/** Creates an sprite with an CCBatchNode and a rect
	*/
	static CCSprite* spriteWithBatchNode(CCSpriteBatchNode *batchNode, const CCRect& rect);
public:
    CCSprite(void);
	virtual ~CCSprite(void);
	virtual bool init(void);

	virtual void removeChild(CCNode* pChild, bool bCleanup);
	virtual void removeAllChildrenWithCleanup(bool bCleanup);
	virtual void reorderChild(CCNode *pChild, int zOrder);
	virtual void addChild(CCNode *pChild);
	virtual void addChild(CCNode *pChild, int zOrder);
	virtual void addChild(CCNode *pChild, int zOrder, int tag);

	virtual void setDirtyRecursively(bool bValue);
	virtual void setPosition(const CCPoint& pos);
	virtual void setPositionInPixels(const CCPoint& pos);
	virtual void setRotation(float fRotation);
    virtual void setSkewX(float sx);
    virtual void setSkewY(float sy);
	virtual void setScaleX(float fScaleX);
	virtual void setScaleY(float fScaleY);
	virtual void setScale(float fScale);
	virtual void setVertexZ(float fVertexZ);
	virtual void setAnchorPoint(const CCPoint& anchor);
	virtual void setIsRelativeAnchorPoint(bool bRelative);
	virtual void setIsVisible(bool bVisible);
	void setFlipX(bool bFlipX);
	void setFlipY(bool bFlipY);
	/** whether or not the sprite is flipped horizontally.
	It only flips the texture of the sprite, and not the texture of the sprite's children.
	Also, flipping the texture doesn't alter the anchorPoint.
	If you want to flip the anchorPoint too, and/or to flip the children too use:

	sprite->setScaleX(sprite->getScaleX() * -1);
	*/
	bool isFlipX(void);
	/** whether or not the sprite is flipped vertically.
	It only flips the texture of the sprite, and not the texture of the sprite's children.
	Also, flipping the texture doesn't alter the anchorPoint.
	If you want to flip the anchorPoint too, and/or to flip the children too use:

	sprite->setScaleY(sprite->getScaleY() * -1);
	*/
	bool isFlipY(void);

	void updateColor(void);
	// RGBAProtocol
	/** opacity: conforms to CCRGBAProtocol protocol */
	virtual void setIsOpacityModifyRGB(bool bValue);
	virtual bool getIsOpacityModifyRGB(void);

	// CCTextureProtocol
    virtual void setTexture(CCTexture2D *texture);
	virtual CCTexture2D* getTexture(void);

	/** Initializes an sprite with a texture.
	 The rect used will be the size of the texture.
	 The offset will be (0,0).
	 */
    bool initWithTexture(CCTexture2D *pTexture);

	/** Initializes an sprite with a texture and a rect.
	 The offset will be (0,0).
	 */
    bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect);

	// Initializes an sprite with an sprite frame.
    bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame);

	/** Initializes an sprite with an sprite frame name.
	 An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.
	 If the CCSpriteFrame doesn't exist it will raise an exception.
	 @since v0.9
	 */
    bool initWithSpriteFrameName(const char *pszSpriteFrameName);

	/** Initializes an sprite with an image filename.
	 The rect used will be the size of the image.
	 The offset will be (0,0).
	 */
    bool initWithFile(const char *pszFilename);

	/** Initializes an sprite with an image filename, and a rect.
	 The offset will be (0,0).
	 */
    bool initWithFile(const char *pszFilename, const CCRect& rect);

	/** Initializes an sprite with an CCSpriteBatchNode and a rect in points */
	bool initWithBatchNode(CCSpriteBatchNode *batchNode, const CCRect& rect);

	/** Initializes an sprite with an CCSpriteBatchNode and a rect in pixels
	@since v0.99.5
	*/
	bool initWithBatchNodeRectInPixels(CCSpriteBatchNode *batchNode, const CCRect& rect);

	// BatchNode methods

	/** updates the quad according the the rotation, position, scale values. */
	void updateTransform(void);

	/** tell the sprite to use self-render.
	 @since v0.99.0
	 */
	void useSelfRender(void);

	/** updates the texture rect of the CCSprite in points. */
     void setTextureRect(const CCRect& rect);

	 /** updates the texture rect, rectRotated and untrimmed size of the CCSprite in pixels
	 */
	 void setTextureRectInPixels(const CCRect& rect, bool rotated, const CCSize& size);

	/** tell the sprite to use batch node render.
	 @since v0.99.0
	 */
	 void useBatchNode(CCSpriteBatchNode *batchNode);

	// Frames

	/** sets a new display frame to the CCSprite. */
	void setDisplayFrame(CCSpriteFrame *pNewFrame);

	/** returns whether or not a CCSpriteFrame is being displayed */
	bool isFrameDisplayed(CCSpriteFrame *pFrame);

	/** returns the current displayed frame. */
	CCSpriteFrame* displayedFrame(void);

	// Animation

	/** changes the display frame with animation name and index.
	The animation name will be get from the CCAnimationCache
	@since v0.99.5
	*/
	void setDisplayFrameWithAnimationName(const char *animationName, int frameIndex);

protected:
	void updateTextureCoords(const CCRect& rect);
	void updateBlendFunc(void);
    void getTransformValues(struct transformValues_ *tv); // optimization

protected:
	//
	// Data used when the sprite is rendered using a CCSpriteSheet
	//
	CCTextureAtlas			*m_pobTextureAtlas;		// Sprite Sheet texture atlas (weak reference)
	unsigned int			m_uAtlasIndex;			// Absolute (real) Index on the SpriteSheet
	CCSpriteBatchNode       *m_pobBatchNode;        // Used batch node (weak reference)
	ccHonorParentTransform	m_eHonorParentTransform;// whether or not to transform according to its parent transformations
	bool					m_bDirty;				// Sprite needs to be updated
	bool					m_bRecursiveDirty;		// Subchildren needs to be updated
	bool					m_bHasChildren;			// optimization to check if it contain children

	//
	// Data used when the sprite is self-rendered
	//
	ccBlendFunc		m_sBlendFunc;	// Needed for the texture protocol
	CCTexture2D		*m_pobTexture;// Texture used to render the sprite

	//
	// Shared data
	//

	// whether or not it's parent is a CCSpriteBatchNode
	bool m_bUsesBatchNode;

	// texture
	CCRect m_obRect;
	CCRect m_obRectInPixels;
	bool   m_bRectRotated;

	// Offset Position (used by Zwoptex)
	CCPoint m_obOffsetPositionInPixels; // absolute
	CCPoint m_obUnflippedOffsetPositionFromCenter;

	// vertex coords, texture coords and color info
	ccV3F_C4B_T2F_Quad m_sQuad;

	// opacity and RGB protocol
	ccColor3B m_sColorUnmodified;
	bool m_bOpacityModifyRGB;

	// image is flipped
	bool m_bFlipX;
	bool m_bFlipY;
};
}//namespace   cocos2d

#endif // __SPITE_NODE_CCSPRITE_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2009-2010 Ricardo Quesada
Copyright (C) 2009      Matt Oswald
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __CC_SPRITE_BATCH_NODE_H__
#define __CC_SPRITE_BATCH_NODE_H__

#include "CCNode.h"
#include "CCProtocols.h"
#include "CCTextureAtlas.h"
#include "ccMacros.h"
#include "CCMutableArray.h"

namespace cocos2d
{
	class CCSprite;

	/** CCSpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
	* (often known as "batch draw").
	*
	* A CCSpriteBatchNode can reference one and only one texture (one image file, one texture atlas).
	* Only the CCSprites that are contained in that texture can be added to the CCSpriteBatchNode.
	* All CCSprites added to a CCSpriteBatchNode are drawn in one OpenGL ES draw call.
	* If the CCSprites are not added to a CCSpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.
	*
	*
	* Limitations:
	*  - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is CCSprite or any subclass of CCSprite. eg: particles, labels and layer can't be added to a CCSpriteBatchNode.
	*  - Either all its children are Aliased or Antialiased. It can't be a mix. This is because "alias" is a property of the texture, and all the sprites share the same texture.
	*
	* @since v0.7.1
	*/
	class CC_DLL CCSpriteBatchNode : public CCNode, public CCTextureProtocol
	{
	public:
		~CCSpriteBatchNode();

		// property

		// retain
		inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas; }
		inline void setTextureAtlas(CCTextureAtlas* textureAtlas)
		{
			if (textureAtlas != m_pobTextureAtlas)
			{
				CC_SAFE_RETAIN(textureAtlas);
				CC_SAFE_RELEASE(m_pobTextureAtlas);
				m_pobTextureAtlas = textureAtlas;
			}
		}

		inline CCArray* getDescendants(void) { return m_pobDescendants; }

		/** creates a CCSpriteBatchNode with a texture2d and a default capacity of 29 children.
		The capacity will be increased in 33% in runtime if it run out of space.
		*/
		static CCSpriteBatchNode* batchNodeWithTexture(CCTexture2D *tex);

		/** creates a CCSpriteBatchNode with a texture2d and capacity of children.
		The capacity will be increased in 33% in runtime if it run out of space.
		*/
		static CCSpriteBatchNode* batchNodeWithTexture(CCTexture2D* tex, unsigned int capacity);

		/** creates a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) with a default capacity of 29 children.
		The capacity will be increased in 33% in runtime if it run out of space.
		The file will be loaded using the TextureMgr.
		*/
		static CCSpriteBatchNode* batchNodeWithFile(const char* fileImage);

		/** creates a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and capacity of children.
		The capacity will be increased in 33% in runtime if it run out of space.
		The file will be loaded using the TextureMgr.
		*/
		static CCSpriteBatchNode* batchNodeWithFile(const char* fileImage, unsigned int capacity);

		/** initializes a CCSpriteBatchNode with a texture2d and capacity of children.
		The capacity will be increased in 33% in runtime if it run out of space.
		*/
		bool initWithTexture(CCTexture2D *tex, unsigned int capacity);
		/** initializes a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.
		The capacity will be increased in 33% in runtime if it run out of space.
		The file will be loaded using the TextureMgr.
		*/
		bool initWithFile(const char* fileImage, unsigned int capacity);

		void increaseAtlasCapacity();

		/** removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.
		@warning Removing a child from a CCSpriteBatchNode is very slow
		*/
		void removeChildAtIndex(unsigned int index, bool doCleanup);

		void insertChild(CCSprite *child, unsigned int index);
		void removeSpriteFromAtlas(CCSprite *sprite);

		unsigned int rebuildIndexInOrder(CCSprite *parent, unsigned int index);
		unsigned int highestAtlasIndexInChild(CCSprite *sprite);
		unsigned int lowestAtlasIndexInChild(CCSprite *sprite);
		unsigned int atlasIndexForChild(CCSprite *sprite, int z);

		// CCTextureProtocol
	    virtual CCTexture2D* getTexture(void);
	    virtual void setTexture(CCTexture2D *texture);
	    virtual void setBlendFunc(ccBlendFunc blendFunc);
	    virtual ccBlendFunc getBlendFunc(void);

	    virtual void visit(void);
	    virtual void addChild(CCNode * child);
	    virtual void addChild(CCNode * child, int zOrder);
	    virtual void addChild(CCNode * child, int zOrder, int tag);
	    virtual void reorderChild(CCNode * child, int zOrder);

	    virtual void removeChild(CCNode* child, bool cleanup);
	    virtual void removeAllChildrenWithCleanup(bool cleanup);
	    virtual void draw(void);

    protected:
        /* IMPORTANT XXX IMPORTNAT:
        * These 2 methods can't be part of CCTMXLayer since they call [super add...], and CCSpriteSheet#add SHALL not be called
        */

        /* Adds a quad into the texture atlas but it won't be added into the children array.
        This method should be called only when you are dealing with very big AtlasSrite and when most of the CCSprite won't be updated.
        For example: a tile map (CCTMXMap) or a label with lots of characters (BitmapFontAtlas)
        */
        void addQuadFromSprite(CCSprite *sprite, unsigned int index);
        /* This is the opposite of "addQuadFromSprite.
        It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas
        */
        CCSpriteBatchNode * addSpriteWithoutQuad(CCSprite*child, unsigned int z, int aTag);

	private:
		void updateBlendFunc();

	protected:
		CCTextureAtlas *m_pobTextureAtlas;
		ccBlendFunc m_blendFunc;

		// all descendants: chlidren, gran children, etc...
		CCArray* m_pobDescendants;
	};
}

#endif // __CC_SPRITE_BATCH_NODE_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2011 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __SPRITE_CCSPRITE_FRAME_H__
#define __SPRITE_CCSPRITE_FRAME_H__

#include "CCNode.h"
#include "CCProtocols.h"
#include "CCObject.h"

namespace   cocos2d {
class CCRect;
class CCPoint;
class CCSize;
class CCTexture2D;
class CCZone;

/** @brief A CCSpriteFrame has:
	- texture: A CCTexture2D that will be used by the CCSprite
	- rectangle: A rectangle of the texture

 You can modify the frame of a CCSprite by doing:

	CCSpriteFrame *frame = CCSpriteFrame::frameWithTexture(texture, rect, offset);
	sprite->setDisplayFrame(frame);
 */
class CC_DLL CCSpriteFrame : public CCObject
{
public:
	// attributes

	inline const CCRect& getRectInPixels(void) { return m_obRectInPixels; }
	void setRectInPixels(const CCRect& rectInPixels);

	inline bool isRotated(void) { return m_bRotated; }
	inline void setRotated(bool bRotated) { m_bRotated = bRotated; }

	/** get rect of the frame */
	inline const CCRect& getRect(void) { return m_obRect; }
	/** set rect of the frame */
	void setRect(const CCRect& rect);

	/** get offset of the frame */
	inline const CCPoint& getOffsetInPixels(void) { return m_obOffsetInPixels; }
	/** set offset of the frame */
	inline void setOffsetInPixels(const CCPoint& offsetInPixels) { m_obOffsetInPixels = offsetInPixels; }

	/** get original size of the trimmed image */
	inline const CCSize& getOriginalSizeInPixels(void) { return m_obOriginalSizeInPixels; }
	/** set original size of the trimmed image */
	inline void setOriginalSizeInPixels(const CCSize& sizeInPixels) { m_obOriginalSizeInPixels = sizeInPixels; }

	/** get texture of the frame */
	inline CCTexture2D* getTexture(void) { return m_pobTexture; }
	/** set texture of the frame, the texture is retained */
	inline void setTexture(CCTexture2D* pobTexture)
	{
		CC_SAFE_RETAIN(pobTexture);
		CC_SAFE_RELEASE(m_pobTexture);
		m_pobTexture = pobTexture;
	}

public:
	~CCSpriteFrame(void);
	virtual CCObject* copyWithZone(CCZone *pZone);

	/** Create a CCSpriteFrame with a texture, rect in points.
	 It is assumed that the frame was not trimmed.
	 */
	static CCSpriteFrame* frameWithTexture(CCTexture2D* pobTexture, const CCRect& rect);

	/** Create a CCSpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
	 The originalSize is the size in points of the frame before being trimmed.
	 */
    static CCSpriteFrame* frameWithTexture(CCTexture2D* pobTexture, const CCRect& rect, bool rotated, const CCPoint& offset, const CCSize& originalSize);

public:
	/** Initializes a CCSpriteFrame with a texture, rect in points.
	 It is assumed that the frame was not trimmed.
	 */
	bool initWithTexture(CCTexture2D* pobTexture, const CCRect& rect);

	/** Initializes a CCSpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
	The originalSize is the size in points of the frame before being trimmed.
	*/
	bool initWithTexture(CCTexture2D* pobTexture, const CCRect& rect, bool rotated, const CCPoint& offset, const CCSize& originalSize);
protected:
	CCRect m_obRectInPixels;
	bool   m_bRotated;
	CCRect m_obRect;
	CCPoint m_obOffsetInPixels;
	CCSize m_obOriginalSizeInPixels;
	CCTexture2D *m_pobTexture;
};

}//namespace   cocos2d

#endif //__SPRITE_CCSPRITE_FRAME_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009      Jason Booth
Copyright (c) 2009      Robert J Payne
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __SPRITE_CCSPRITE_FRAME_CACHE_H__
#define __SPRITE_CCSPRITE_FRAME_CACHE_H__

/*
 * To create sprite frames and texture atlas, use this tool:
 * http://zwoptex.zwopple.com/
 */

#include <string>
#include "CCSpriteFrame.h"
#include "CCTexture2D.h"
#include "CCObject.h"
#include "CCMutableDictionary.h"

namespace   cocos2d {
class CCSprite;

/** @brief Singleton that handles the loading of the sprite frames.
 It saves in a cache the sprite frames.
 @since v0.9
 */
class CC_DLL CCSpriteFrameCache : public CCObject
{
public:
	bool init(void);
	~CCSpriteFrameCache(void);

	/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
	 */
	void addSpriteFramesWithDictionary(CCDictionary<std::string, CCObject*> *pobDictionary, CCTexture2D *pobTexture);

	/** Adds multiple Sprite Frames from a plist file.
	 * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png
	 * If you want to use another texture, you should use the addSpriteFramesWithFile:texture method.
	 */
	void addSpriteFramesWithFile(const char *pszPlist);

	/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
	@since v0.99.5
	*/
	void addSpriteFramesWithFile(const char* plist, const char* textureFileName);

	/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. */
	void addSpriteFramesWithFile(const char *pszPlist, CCTexture2D *pobTexture);

	/** Adds an sprite frame with a given name.
	 If the name already exists, then the contents of the old name will be replaced with the new one.
	 */
	void addSpriteFrame(CCSpriteFrame *pobFrame, const char *pszFrameName);

	/** Purges the dictionary of loaded sprite frames.
	 * Call this method if you receive the "Memory Warning".
	 * In the short term: it will free some resources preventing your app from being killed.
	 * In the medium term: it will allocate more resources.
	 * In the long term: it will be the same.
	 */
	void removeSpriteFrames(void);

	/** Removes unused sprite frames.
	 * Sprite Frames that have a retain count of 1 will be deleted.
	 * It is convenient to call this method after when starting a new Scene.
	 */
	void removeUnusedSpriteFrames(void);

	/** Deletes an sprite frame from the sprite frame cache. */
	void removeSpriteFrameByName(const char *pszName);

	/** Removes multiple Sprite Frames from a plist file.
	* Sprite Frames stored in this file will be removed.
	* It is convinient to call this method when a specific texture needs to be removed.
	* @since v0.99.5
	*/
	void removeSpriteFramesFromFile(const char* plist);

	/** Removes multiple Sprite Frames from CCDictionary.
	* @since v0.99.5
	*/
	void removeSpriteFramesFromDictionary(CCDictionary<std::string, CCSpriteFrame*> *dictionary);

	/** Removes all Sprite Frames associated with the specified textures.
	* It is convinient to call this method when a specific texture needs to be removed.
	* @since v0.995.
	*/
	void removeSpriteFramesFromTexture(CCTexture2D* texture);

	/** Returns an Sprite Frame that was previously added.
	 If the name is not found it will return nil.
	 You should retain the returned copy if you are going to use it.
	 */
	CCSpriteFrame* spriteFrameByName(const char *pszName);

public:
	/** Returns the shared instance of the Sprite Frame cache */
	static CCSpriteFrameCache* sharedSpriteFrameCache(void);

	/** Purges the cache. It releases all the Sprite Frames and the retained instance. */
	static void purgeSharedSpriteFrameCache(void);

private:
	CCSpriteFrameCache(void) : m_pSpriteFrames(NULL), m_pSpriteFramesAliases(NULL){}
	const char * valueForKey(const char *key, CCDictionary<std::string, CCObject*> *dict);

protected:
	CCDictionary<std::string, CCSpriteFrame*> *m_pSpriteFrames;
	CCDictionary<std::string, CCString*> *m_pSpriteFramesAliases;
};
}//namespace   cocos2d

#endif // __SPRITE_CCSPRITE_FRAME_CACHE_H__


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCSTRING_H__
#define __CCSTRING_H__
#include <string>
#include <stdlib.h>
#include "CCObject.h"
#include "CCFileUtils.h"

namespace cocos2d {

	class CC_DLL CCString : public CCObject
	{
	public:
		std::string m_sString;
	public:
		CCString()
			:m_sString("")
		{}
		CCString(const char * str)
		{
			m_sString = str;
		}
		virtual ~CCString(){ m_sString.clear(); }

		int toInt()
		{
			return atoi(m_sString.c_str());
		}
		unsigned int toUInt()
		{
			return (unsigned int)atoi(m_sString.c_str());
		}
		float toFloat()
		{
			return (float)atof(m_sString.c_str());
		}
		std::string toStdString()
		{
			return m_sString;
		}

		bool isEmpty()
		{
			return m_sString.empty();
		}

        virtual bool isEqual(const CCObject* pObject)
        {
            bool bRet = false;
            const CCString* pStr = dynamic_cast<const CCString*>(pObject);
            if (pStr != NULL)
            {
                if (0 == m_sString.compare(pStr->m_sString))
                {
                    bRet = true;
                }
            }
            return bRet;
        }

        /** @brief: Get string from a file.
        *   @return: a pointer which needs to be deleted manually by 'delete[]' .
        */
        static char* stringWithContentsOfFile(const char* pszFileName)
        {
            unsigned long size = 0;
            unsigned char* pData = 0;
            char* pszRet = 0;
            pData = CCFileUtils::getFileData(pszFileName, "rb", &size);
            do
            {
                CC_BREAK_IF(!pData || size <= 0);
                pszRet = new char[size+1];
                pszRet[size] = '\0';
                memcpy(pszRet, pData, size);
                CC_SAFE_DELETE_ARRAY(pData);
            } while (false);
            return pszRet;
        }
	};
}// namespace cocos2d
#endif //__CCSTRING_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2009-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCTMX_LAYER_H__
#define __CCTMX_LAYER_H__
#include "CCTMXObjectGroup.h"
#include "CCAtlasNode.h"
#include "CCSpriteBatchNode.h"
namespace cocos2d {

	class CCTMXMapInfo;
	class CCTMXLayerInfo;
	class CCTMXTilesetInfo;
	struct _ccCArray;

	/** @brief CCTMXLayer represents the TMX layer.

	It is a subclass of CCSpriteBatchNode. By default the tiles are rendered using a CCTextureAtlas.
	If you modify a tile on runtime, then, that tile will become a CCSprite, otherwise no CCSprite objects are created.
	The benefits of using CCSprite objects as tiles are:
	- tiles (CCSprite) can be rotated/scaled/moved with a nice API

	If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
	then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.

	On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
	Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawin them. The used alpha func will be:

	glAlphaFunc( GL_GREATER, value )

	"value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
	The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a differnt
	value, like 0.5.

	For further information, please see the programming guide:

	http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps

	@since v0.8.1
	*/
	class CC_DLL CCTMXLayer : public CCSpriteBatchNode
	{
		/** size of the layer in tiles */
		CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tLayerSize, LayerSize);
		/** size of the map's tile (could be differnt from the tile's size) */
		CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapTileSize, MapTileSize);
		/** pointer to the map of tiles */
		CC_SYNTHESIZE(unsigned int*, m_pTiles, Tiles);
		/** Tilset information for the layer */
		CC_PROPERTY(CCTMXTilesetInfo*, m_pTileSet, TileSet);
		/** Layer orientation, which is the same as the map orientation */
		CC_SYNTHESIZE(unsigned int, m_uLayerOrientation, LayerOrientation);
		/** properties from the layer. They can be added using Tiled */
		CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties);
	public:
		CCTMXLayer();
		virtual ~CCTMXLayer();
		/** creates a CCTMXLayer with an tileset info, a layer info and a map info */
		static CCTMXLayer * layerWithTilesetInfo(CCTMXTilesetInfo *tilesetInfo, CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo);
		/** initializes a CCTMXLayer with a tileset info, a layer info and a map info */
		bool initWithTilesetInfo(CCTMXTilesetInfo *tilesetInfo, CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo);

		/** dealloc the map that contains the tile position from memory.
		Unless you want to know at runtime the tiles positions, you can safely call this method.
		If you are going to call layer->tileGIDAt() then, don't release the map
		*/
		void releaseMap();

		/** returns the tile (CCSprite) at a given a tile coordinate.
		The returned CCSprite will be already added to the CCTMXLayer. Don't add it again.
		The CCSprite can be treated like any other CCSprite: rotated, scaled, translated, opacity, color, etc.
		You can remove either by calling:
		- layer->removeChild(sprite, cleanup);
		- or layer->removeTileAt(ccp(x,y));
		*/
		CCSprite* tileAt(const CCPoint& tileCoordinate);

		/** returns the tile gid at a given tile coordinate.
		if it returns 0, it means that the tile is empty.
		This method requires the the tile map has not been previously released (eg. don't call layer->releaseMap())
		*/
		unsigned int  tileGIDAt(const CCPoint& tileCoordinate);

		/** sets the tile gid (gid = tile global id) at a given tile coordinate.
		The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
		If a tile is already placed at that position, then it will be removed.
		*/
		void setTileGID(unsigned int gid, const CCPoint& tileCoordinate);

		/** removes a tile at given tile coordinate */
		void removeTileAt(const CCPoint& tileCoordinate);

		/** returns the position in pixels of a given tile coordinate */
		CCPoint positionAt(const CCPoint& tileCoordinate);

		/** return the value for the specific property name */
		CCString *propertyNamed(const char *propertyName);

		/** Creates the tiles */
		void setupTiles();

		/** CCTMXLayer doesn't support adding a CCSprite manually.
		@warning addchild(z, tag); is not supported on CCTMXLayer. Instead of setTileGID.
		*/
		virtual void addChild(CCNode * child, int zOrder, int tag);
		// super method
		void removeChild(CCNode* child, bool cleanup);
		void draw();

		inline const char* getLayerName(){ return m_sLayerName.c_str(); }
		inline void setLayerName(const char *layerName){ m_sLayerName = layerName; }
	private:
		CCPoint positionForIsoAt(const CCPoint& pos);
		CCPoint positionForOrthoAt(const CCPoint& pos);
		CCPoint positionForHexAt(const CCPoint& pos);

		CCPoint calculateLayerOffset(const CCPoint& offset);

		/* optimization methos */
		CCSprite* appendTileForGID(unsigned int gid, const CCPoint& pos);
		CCSprite* insertTileForGID(unsigned int gid, const CCPoint& pos);
		CCSprite* updateTileForGID(unsigned int gid, const CCPoint& pos);

		/* The layer recognizes some special properties, like cc_vertez */
		void parseInternalProperties();
		int vertexZForPos(const CCPoint& pos);

		// index
		unsigned int atlasIndexForExistantZ(unsigned int z);
		unsigned int atlasIndexForNewZ(int z);
	protected:
		//! name of the layer
		std::string m_sLayerName;
		//! TMX Layer supports opacity
		unsigned char		m_cOpacity;

		unsigned int		m_uMinGID;
		unsigned int		m_uMaxGID;

		//! Only used when vertexZ is used
		int					m_nVertexZvalue;
		bool				m_bUseAutomaticVertexZ;
		float				m_fAlphaFuncValue;

		//! used for optimization
		CCSprite			*m_pReusedTile;
		_ccCArray			*m_pAtlasIndexArray;

        // used for retina display
        float               m_fContentScaleFactor;
	};

}// namespace cocos2d
#endif //__CCTMX_LAYER_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2010      Neophit
Copyright (c) 2010      Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCTMX_OBJECT_GROUP_H__
#define __CCTMX_OBJECT_GROUP_H__

#include "CCGeometry.h"
#include "CCString.h"
#include "CCMutableArray.h"
#include "CCMutableDictionary.h"

namespace cocos2d {

	/** @brief CCTMXObjectGroup represents the TMX object group.
	@since v0.99.0
	*/
	class CC_DLL CCTMXObjectGroup : public CCObject
	{
		/** offset position of child objects */
		CC_SYNTHESIZE_PASS_BY_REF(CCPoint, m_tPositionOffset, PositionOffset);
		/** list of properties stored in a dictionary */
		CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties);
		/** array of the objects */
		CC_PROPERTY(CCMutableArray<CCStringToStringDictionary*>*, m_pObjects, Objects);
	public:
		CCTMXObjectGroup();
		virtual ~CCTMXObjectGroup();

		inline const char* getGroupName(){ return m_sGroupName.c_str(); }
		inline void setGroupName(const char *groupName){ m_sGroupName = groupName; }

		/** return the value for the specific property name */
		CCString *propertyNamed(const char* propertyName);

		/** return the dictionary for the specific object name.
		It will return the 1st object found on the array for the given name.
		*/
		CCStringToStringDictionary *objectNamed(const char *objectName);
	protected:
		/** name of the group */
		std::string m_sGroupName;
	};

}// namespace cocos2d
#endif //__CCTMX_OBJECT_GROUP_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2009-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCTMX_TILE_MAP_H__
#define __CCTMX_TILE_MAP_H__
#include "CCNode.h"
#include "CCTMXObjectGroup.h"

namespace cocos2d {

	class CCTMXObjectGroup;
	class CCTMXLayer;
	class CCTMXLayerInfo;
	class CCTMXTilesetInfo;
	class CCTMXMapInfo;

	/** Possible oritentations of the TMX map */
	enum
	{
		/** Orthogonal orientation */
		CCTMXOrientationOrtho,

		/** Hexagonal orientation */
		CCTMXOrientationHex,

		/** Isometric orientation */
		CCTMXOrientationIso,
	};

	/** @brief CCTMXTiledMap knows how to parse and render a TMX map.

	It adds support for the TMX tiled map format used by http://www.mapeditor.org
	It supports isometric, hexagonal and orthogonal tiles.
	It also supports object groups, objects, and properties.

	Features:
	- Each tile will be treated as an CCSprite
	- The sprites are created on demand. They will be created only when you call "layer->tileAt(position)"
	- Each tile can be rotated / moved / scaled / tinted / "opacitied", since each tile is a CCSprite
	- Tiles can be added/removed in runtime
	- The z-order of the tiles can be modified in runtime
	- Each tile has an anchorPoint of (0,0)
	- The anchorPoint of the TMXTileMap is (0,0)
	- The TMX layers will be added as a child
	- The TMX layers will be aliased by default
	- The tileset image will be loaded using the CCTextureCache
	- Each tile will have a unique tag
	- Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z
	- Each object group will be treated as an CCMutableArray
	- Object class which will contain all the properties in a dictionary
	- Properties can be assigned to the Map, Layer, Object Group, and Object

	Limitations:
	- It only supports one tileset per layer.
	- Embeded images are not supported
	- It only supports the XML format (the JSON format is not supported)

	Technical description:
	Each layer is created using an CCTMXLayer (subclass of CCSpriteBatchNode). If you have 5 layers, then 5 CCTMXLayer will be created,
	unless the layer visibility is off. In that case, the layer won't be created at all.
	You can obtain the layers (CCTMXLayer objects) at runtime by:
	- map->getChildByTag(tag_number);  // 0=1st layer, 1=2nd layer, 2=3rd layer, etc...
	- map->layerNamed(name_of_the_layer);

	Each object group is created using a CCTMXObjectGroup which is a subclass of CCMutableArray.
	You can obtain the object groups at runtime by:
	- map->objectGroupNamed(name_of_the_object_group);

	Each object is a CCTMXObject.

	Each property is stored as a key-value pair in an CCMutableDictionary.
	You can obtain the properties at runtime by:

	map->propertyNamed(name_of_the_property);
	layer->propertyNamed(name_of_the_property);
	objectGroup->propertyNamed(name_of_the_property);
	object->propertyNamed(name_of_the_property);

	@since v0.8.1
	*/
	class CC_DLL CCTMXTiledMap : public CCNode
	{
		/** the map's size property measured in tiles */
		CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize);
		/** the tiles's size property measured in pixels */
		CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize);
		/** map orientation */
		CC_SYNTHESIZE(int, m_nMapOrientation, MapOrientation);
		/** object groups */
		CC_PROPERTY(CCMutableArray<CCTMXObjectGroup*>*, m_pObjectGroups, ObjectGroups);
		/** properties */
		CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties);
	public:
		CCTMXTiledMap();
		virtual ~CCTMXTiledMap();

		/** creates a TMX Tiled Map with a TMX file.*/
		static CCTMXTiledMap * tiledMapWithTMXFile(const char *tmxFile);

		/** initializes a TMX Tiled Map with a TMX file */
		bool initWithTMXFile(const char *tmxFile);

		/** return the TMXLayer for the specific layer */
		CCTMXLayer* layerNamed(const char *layerName);

		/** return the TMXObjectGroup for the secific group */
		CCTMXObjectGroup* objectGroupNamed(const char *groupName);

		/** return the value for the specific property name */
		CCString *propertyNamed(const char *propertyName);

		/** return properties dictionary for tile GID */
		CCDictionary<std::string, CCString*> *propertiesForGID(int GID);

	private:
 		CCTMXLayer * parseLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo);
 		CCTMXTilesetInfo * tilesetForLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo);

	protected:
		//! tile properties
        CCDictionary<int, CCStringToStringDictionary*> *m_pTileProperties;
        CCDictionary<std::string, CCTMXLayer*> *m_pTMXLayers;

	};

}// namespace cocos2d
#endif //__CCTMX_TILE_MAP_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2009-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __CC_TM_XML_PARSER__
#define __CC_TM_XML_PARSER__
#include "CCMutableArray.h"
#include "CCMutableDictionary.h"
#include "CCGeometry.h"

#include "../platform/CCSAXParser.h"

namespace cocos2d {

	class CCTMXObjectGroup;

	/** @file
	* Internal TMX parser
	*
	* IMPORTANT: These classed should not be documented using doxygen strings
	* since the user should not use them.
	*
	*/

	enum {
		TMXLayerAttribNone = 1 << 0,
		TMXLayerAttribBase64 = 1 << 1,
		TMXLayerAttribGzip = 1 << 2,
		TMXLayerAttribZlib = 1 << 3,
	};

	enum {
		TMXPropertyNone,
		TMXPropertyMap,
		TMXPropertyLayer,
		TMXPropertyObjectGroup,
		TMXPropertyObject,
		TMXPropertyTile
	};

	/** @brief CCTMXLayerInfo contains the information about the layers like:
	- Layer name
	- Layer size
	- Layer opacity at creation time (it can be modified at runtime)
	- Whether the layer is visible (if it's not visible, then the CocosNode won't be created)

	This information is obtained from the TMX file.
	*/
	class CC_DLL CCTMXLayerInfo : public CCObject
	{
		CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties);
	public:
		std::string			m_sName;
		CCSize				m_tLayerSize;
		unsigned int		*m_pTiles;
		bool				m_bVisible;
		unsigned char		m_cOpacity;
		bool				m_bOwnTiles;
		unsigned int		m_uMinGID;
		unsigned int		m_uMaxGID;
		CCPoint				m_tOffset;
	public:
		CCTMXLayerInfo();
		virtual ~CCTMXLayerInfo();
	};

	/** @brief CCTMXTilesetInfo contains the information about the tilesets like:
	- Tileset name
	- Tilset spacing
	- Tileset margin
	- size of the tiles
	- Image used for the tiles
	- Image size

	This information is obtained from the TMX file.
	*/
	class CC_DLL CCTMXTilesetInfo : public CCObject
	{
	public:
		std::string		m_sName;
		unsigned int	m_uFirstGid;
		CCSize			m_tTileSize;
		unsigned int	m_uSpacing;
		unsigned int	m_uMargin;
		//! filename containing the tiles (should be spritesheet / texture atlas)
		std::string		m_sSourceImage;
		//! size in pixels of the image
		CCSize			m_tImageSize;
	public:
		CCTMXTilesetInfo();
		virtual ~CCTMXTilesetInfo();
		CCRect rectForGID(unsigned int gid);
	};

	/** @brief CCTMXMapInfo contains the information about the map like:
	- Map orientation (hexagonal, isometric or orthogonal)
	- Tile size
	- Map size

	And it also contains:
	- Layers (an array of TMXLayerInfo objects)
	- Tilesets (an array of TMXTilesetInfo objects)
	- ObjectGroups (an array of TMXObjectGroupInfo objects)

	This information is obtained from the TMX file.

	*/
	class CC_DLL CCTMXMapInfo : public CCObject, public CCSAXDelegator
	{
	public:
		/// map orientation
		CC_SYNTHESIZE(int,	m_nOrientation, Orientation);
		/// map width & height
		CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize);
		/// tiles width & height
		CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize);
		/// Layers
		CC_PROPERTY(CCMutableArray<CCTMXLayerInfo*>*, m_pLayers, Layers);
		/// tilesets
		CC_PROPERTY(CCMutableArray<CCTMXTilesetInfo*>*, m_pTilesets, Tilesets);
		/// ObjectGroups
		CC_PROPERTY(CCMutableArray<CCTMXObjectGroup*>*, m_pObjectGroups, ObjectGroups);
		/// parent element
		CC_SYNTHESIZE(int, m_nParentElement, ParentElement);
		/// parent GID
		CC_SYNTHESIZE(unsigned int, m_uParentGID, ParentGID);
		/// layer attribs
		CC_SYNTHESIZE(int, m_nLayerAttribs, LayerAttribs);
		/// is stroing characters?
		CC_SYNTHESIZE(bool, m_bStoringCharacters, StoringCharacters);
		/// properties
		CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties);
	public:
		CCTMXMapInfo();
		virtual ~CCTMXMapInfo();
		/** creates a TMX Format with a tmx file */
		static CCTMXMapInfo * formatWithTMXFile(const char *tmxFile);
		/** initializes a TMX format witha  tmx file */
		bool initWithTMXFile(const char *tmxFile);
		/** initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */
		bool parseXMLFile(const char *xmlFilename);

		CCDictionary<int, CCStringToStringDictionary*> * getTileProperties();
		void setTileProperties(CCDictionary<int, CCStringToStringDictionary*> * tileProperties);

		// implement pure virtual methods of CCSAXDelegator
		void startElement(void *ctx, const char *name, const char **atts);
		void endElement(void *ctx, const char *name);
		void textHandler(void *ctx, const char *ch, int len);

		inline const char* getCurrentString(){ return m_sCurrentString.c_str(); }
		inline void setCurrentString(const char *currentString){ m_sCurrentString = currentString; }
		inline const char* getTMXFileName(){ return m_sTMXFileName.c_str(); }
		inline void setTMXFileName(const char *fileName){ m_sTMXFileName = fileName; }

	protected:
		//! tmx filename
		std::string m_sTMXFileName;
		//! current string
		std::string m_sCurrentString;
		//! tile properties
		CCDictionary<int, CCStringToStringDictionary*>* m_pTileProperties;
	};

}// namespace cocos2d

#endif


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __CC_TEXT_FIELD_H__
#define __CC_TEXT_FIELD_H__

#include "CCLabelTTF.h"
#include "CCIMEDelegate.h"
#include "CCTouchDelegateProtocol.h"

NS_CC_BEGIN;

class CCTextFieldTTF;

class CC_DLL CCTextFieldDelegate
{
public:
    /**
    @brief	If the sender doesn't want to attach with IME, return true;
    */
    virtual bool onTextFieldAttachWithIME(CCTextFieldTTF * sender)
    {
        CC_UNUSED_PARAM(sender);
        return false;
    }

    /**
    @brief	If the sender doesn't want to detach with IME, return true;
    */
    virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * sender)
    {
        CC_UNUSED_PARAM(sender);
        return false;
    }

    /**
    @brief	If the sender doesn't want to insert the text, return true;
    */
    virtual bool onTextFieldInsertText(CCTextFieldTTF * sender, const char * text, int nLen)
    {
        CC_UNUSED_PARAM(sender);
        CC_UNUSED_PARAM(text);
        CC_UNUSED_PARAM(nLen);
        return false;
    }

    /**
    @brief	If the sender doesn't want to delete the delText, return true;
    */
    virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * sender, const char * delText, int nLen)
    {
        CC_UNUSED_PARAM(sender);
        CC_UNUSED_PARAM(delText);
        CC_UNUSED_PARAM(nLen);
        return false;
    }

    /**
    @brief	If doesn't want draw sender as default, return true.
    */
    virtual bool onDraw(CCTextFieldTTF * sender)
    {
        CC_UNUSED_PARAM(sender);
        return false;
    }
};

/**
@brief	A simple text input field with TTF font.
*/
class CC_DLL CCTextFieldTTF : public CCLabelTTF, public CCIMEDelegate
{
public:
    CCTextFieldTTF();
    virtual ~CCTextFieldTTF();

    //char * description();

    /** creates a CCTextFieldTTF from a fontname, alignment, dimension and font size */
    static CCTextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float fontSize);
    /** creates a CCLabelTTF from a fontname and font size */
    static CCTextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize);
    /** initializes the CCTextFieldTTF with a font name, alignment, dimension and font size */
    bool initWithPlaceHolder(const char *placeholder, const CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float fontSize);
    /** initializes the CCTextFieldTTF with a font name and font size */
    bool initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize);

    /**
    @brief	Open keyboard and receive input text.
    */
    virtual bool attachWithIME();

    /**
    @brief	End text input  and close keyboard.
    */
    virtual bool detachWithIME();

    //////////////////////////////////////////////////////////////////////////
    // properties
    //////////////////////////////////////////////////////////////////////////

    CC_SYNTHESIZE(CCTextFieldDelegate *, m_pDelegate, Delegate);
    CC_SYNTHESIZE_READONLY(int, m_nCharCount, CharCount);
	CC_SYNTHESIZE_PASS_BY_REF(ccColor3B, m_ColorSpaceHolder, ColorSpaceHolder);

    // input text property
public:
    virtual void setString(const char *text);
    virtual const char* getString(void);
protected:
    std::string * m_pInputText;

    // place holder text property
    // place holder text displayed when there is no text in the text field.
public:
    virtual void setPlaceHolder(const char * text);
    virtual const char * getPlaceHolder(void);
protected:
    std::string * m_pPlaceHolder;
protected:

    virtual void draw();

    //////////////////////////////////////////////////////////////////////////
    // CCIMEDelegate interface
    //////////////////////////////////////////////////////////////////////////

    virtual bool canAttachWithIME();
    virtual bool canDetachWithIME();
    virtual void insertText(const char * text, int len);
    virtual void deleteBackward();
    virtual const char * getContentText();
private:
    class LengthStack;
    LengthStack * m_pLens;
};

NS_CC_END;

#endif	// __CC_TEXT_FIELD_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (C) 2008      Apple Inc. All Rights Reserved.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __CCTEXTURE2D_H__
#define __CCTEXTURE2D_H__

#include <string>
#include "CCObject.h"
#include "CCGeometry.h"
#include "ccTypes.h"

namespace   cocos2d {
class CCImage;

//CONSTANTS:

/** @typedef CCTexture2DPixelFormat
Possible texture pixel formats
*/
typedef enum {
	kCCTexture2DPixelFormat_Automatic = 0,
	//! 32-bit texture: RGBA8888
	kCCTexture2DPixelFormat_RGBA8888,
	//! 24-bit texture: RGBA888
	kCCTexture2DPixelFormat_RGB888,
	//! 16-bit texture without Alpha channel
	kCCTexture2DPixelFormat_RGB565,
	//! 8-bit textures used as masks
	kCCTexture2DPixelFormat_A8,
	//! 8-bit intensity texture
	kCCTexture2DPixelFormat_I8,
	//! 16-bit textures used as masks
	kCCTexture2DPixelFormat_AI88,
	//! 16-bit textures: RGBA4444
	kCCTexture2DPixelFormat_RGBA4444,
	//! 16-bit textures: RGB5A1
	kCCTexture2DPixelFormat_RGB5A1,
	//! 4-bit PVRTC-compressed texture: PVRTC4
	kCCTexture2DPixelFormat_PVRTC4,
	//! 2-bit PVRTC-compressed texture: PVRTC2
	kCCTexture2DPixelFormat_PVRTC2,

	//! Default texture format: RGBA8888
	kCCTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_RGBA8888,

	// backward compatibility stuff
	kTexture2DPixelFormat_Automatic = kCCTexture2DPixelFormat_Automatic,
	kTexture2DPixelFormat_RGBA8888 = kCCTexture2DPixelFormat_RGBA8888,
	kTexture2DPixelFormat_RGB888 = kCCTexture2DPixelFormat_RGB888,
	kTexture2DPixelFormat_RGB565 = kCCTexture2DPixelFormat_RGB565,
	kTexture2DPixelFormat_A8 = kCCTexture2DPixelFormat_A8,
	kTexture2DPixelFormat_RGBA4444 = kCCTexture2DPixelFormat_RGBA4444,
	kTexture2DPixelFormat_RGB5A1 = kCCTexture2DPixelFormat_RGB5A1,
	kTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_Default

} CCTexture2DPixelFormat;

/**
Extension to set the Min / Mag filter
*/
typedef struct _ccTexParams {
	GLuint	minFilter;
	GLuint	magFilter;
	GLuint	wrapS;
	GLuint	wrapT;
} ccTexParams;

//CLASS INTERFACES:

/** @brief CCTexture2D class.
* This class allows to easily create OpenGL 2D textures from images, text or raw data.
* The created CCTexture2D object will always have power-of-two dimensions.
* Depending on how you create the CCTexture2D object, the actual image area of the texture might be smaller than the texture dimensions i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
* Be aware that the content of the generated textures will be upside-down!
*/
class CC_DLL CCTexture2D : public CCObject
{
	/** pixel format of the texture */
	CC_PROPERTY_READONLY(CCTexture2DPixelFormat, m_ePixelFormat, PixelFormat)
	/** width in pixels */
	CC_PROPERTY_READONLY(unsigned int, m_uPixelsWide, PixelsWide)
	/** hight in pixels */
	CC_PROPERTY_READONLY(unsigned int, m_uPixelsHigh, PixelsHigh)

	/** texture name */
	CC_PROPERTY_READONLY(GLuint, m_uName, Name)

	/** content size */
	CC_PROPERTY_READONLY_PASS_BY_REF(CCSize, m_tContentSize, ContentSizeInPixels)
	/** texture max S */
	CC_PROPERTY(GLfloat, m_fMaxS, MaxS)
	/** texture max T */
	CC_PROPERTY(GLfloat, m_fMaxT, MaxT)
	/** whether or not the texture has their Alpha premultiplied */
	CC_PROPERTY_READONLY(bool, m_bHasPremultipliedAlpha, HasPremultipliedAlpha);
	CC_PROPERTY(ccResolutionType, m_eResolutionType, ResolutionType);

public:
	CCTexture2D();
	virtual ~CCTexture2D();

	char * description(void);

	/** These functions are needed to create mutable textures */
	void releaseData(void *data);
	void* keepData(void *data, unsigned int length);

	/** Intializes with a texture2d with data */
	bool initWithData(const void* data, CCTexture2DPixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const CCSize& contentSize);

	/**
	Drawing extensions to make it easy to draw basic quads using a CCTexture2D object.
	These functions require GL_TEXTURE_2D and both GL_VERTEX_ARRAY and GL_TEXTURE_COORD_ARRAY client states to be enabled.
	*/
	/** draws a texture at a given point */
	void drawAtPoint(const CCPoint& point);
	/** draws a texture inside a rect */
	void drawInRect(const CCRect& rect);

	/**
	Extensions to make it easy to create a CCTexture2D object from an image file.
	Note that RGBA type textures will have their alpha premultiplied - use the blending mode (GL_ONE, GL_ONE_MINUS_SRC_ALPHA).
	*/
	/** Initializes a texture from a UIImage object */
	bool initWithImage(CCImage * uiImage);

	bool initWithImage(CCImage *uiImage, ccResolutionType resolution);

	/**
	Extensions to make it easy to create a CCTexture2D object from a string of text.
	Note that the generated textures are of type A8 - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA).
	*/
	/** Initializes a texture from a string with dimensions, alignment, font name and font size */
	bool initWithString(const char *text, const CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float fontSize);
	/** Initializes a texture from a string with font name and font size */
	bool initWithString(const char *text, const char *fontName, float fontSize);

	/** returns the content size of the texture in points */
	CCSize getContentSize(void);

#ifdef CC_SUPPORT_PVRTC
	/**
	Extensions to make it easy to create a CCTexture2D object from a PVRTC file
	Note that the generated textures don't have their alpha premultiplied - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA).
	*/
	/** Initializes a texture from a PVRTC buffer */
    bool initWithPVRTCData(const void *data, int level, int bpp, bool hasAlpha, int length, CCTexture2DPixelFormat pixelFormat);
#endif // CC_SUPPORT_PVRTC

    /** Initializes a texture from a PVR file */
	bool initWithPVRFile(const char* file);

	/** sets the min filter, mag filter, wrap s and wrap t texture parameters.
	If the texture size is NPOT (non power of 2), then in can only use GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}.
	@since v0.8
	*/
	void setTexParameters(ccTexParams* texParams);

	/** sets antialias texture parameters:
	- GL_TEXTURE_MIN_FILTER = GL_LINEAR
	- GL_TEXTURE_MAG_FILTER = GL_LINEAR

	@since v0.8
	*/
	void setAntiAliasTexParameters();

	/** sets alias texture parameters:
	- GL_TEXTURE_MIN_FILTER = GL_NEAREST
	- GL_TEXTURE_MAG_FILTER = GL_NEAREST

	@since v0.8
	*/
	void setAliasTexParameters();

	/** Generates mipmap images for the texture.
	It only works if the texture size is POT (power of 2).
	@since v0.99.0
	*/
	void generateMipmap();

	/** returns the bits-per-pixel of the in-memory OpenGL texture
	@since v1.0
	*/
    unsigned int bitsPerPixelForFormat();

	/** sets the default pixel format for UIImagescontains alpha channel.
	If the UIImage contains alpha channel, then the options are:
	- generate 32-bit textures: kCCTexture2DPixelFormat_RGBA8888 (default one)
	- generate 24-bit textures: kCCTexture2DPixelFormat_RGB888
	- generate 16-bit textures: kCCTexture2DPixelFormat_RGBA4444
	- generate 16-bit textures: kCCTexture2DPixelFormat_RGB5A1
	- generate 16-bit textures: kCCTexture2DPixelFormat_RGB565
	- generate 8-bit textures: kCCTexture2DPixelFormat_A8 (only use it if you use just 1 color)

	How does it work ?
	- If the image is an RGBA (with Alpha) then the default pixel format will be used (it can be a 8-bit, 16-bit or 32-bit texture)
	- If the image is an RGB (without Alpha) then an RGB565 or RGB888 texture will be used (16-bit texture)

	@since v0.8
	*/
	static void setDefaultAlphaPixelFormat(CCTexture2DPixelFormat format);

	/** returns the alpha pixel format
	@since v0.8
	*/
	static CCTexture2DPixelFormat defaultAlphaPixelFormat();

	/** treats (or not) PVR files as if they have alpha premultiplied.
	 Since it is impossible to know at runtime if the PVR images have the alpha channel premultiplied, it is
	 possible load them as if they have (or not) the alpha channel premultiplied.

	 By default it is disabled.

	 @since v0.99.5
	 */
	static void PVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied);

private:
	bool initPremultipliedATextureWithImage(CCImage * image, unsigned int pixelsWide, unsigned int pixelsHigh);

    // By default PVR images are treated as if they don't have the alpha channel premultiplied
    bool m_bPVRHaveAlphaPremultiplied;

};
}//namespace   cocos2d

#endif //__CCTEXTURE2D_H__


code:
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __CCTEXTURE_ATLAS_H__
#define __CCTEXTURE_ATLAS_H__

#include <string>
#include "ccTypes.h"
#include "CCObject.h"
#include "ccConfig.h"

namespace   cocos2d {
class CCTexture2D;

/** @brief A class that implements a Texture Atlas.
Supported features:
* The atlas file can be a PVRTC, PNG or any other fomrat supported by Texture2D
* Quads can be udpated in runtime
* Quads can be added in runtime
* Quads can be removed in runtime
* Quads can be re-ordered in runtime
* The TextureAtlas capacity can be increased or decreased in runtime
* OpenGL component: V3F, C4B, T2F.
The quads are rendered using an OpenGL ES VBO.
To render the quads using an interleaved vertex array list, you should modify the ccConfig.h file
*/
class CC_DLL CCTextureAtlas : public CCObject
{
protected:
	GLushort			*m_pIndices;
#if CC_USES_VBO
	GLuint				m_pBuffersVBO[2]; //0: vertex  1: indices
	bool				m_bDirty; //indicates whether or not the array buffer of the VBO needs to be updated
#endif // CC_USES_VBO

	/** quantity of quads that are going to be drawn */
	CC_PROPERTY_READONLY(unsigned int, m_uTotalQuads, TotalQuads)
	/** quantity of quads that can be stored with the current texture atlas size */
	CC_PROPERTY_READONLY(unsigned int, m_uCapacity, Capacity)
	/** Texture of the texture atlas */
	CC_PROPERTY(CCTexture2D *, m_pTexture, Texture)
	/** Quads that are going to be rendered */
	CC_PROPERTY(ccV3F_C4B_T2F_Quad *, m_pQuads, Quads)

public:

	CCTextureAtlas();
	virtual ~CCTextureAtlas();

	char * description();

	/** creates a TextureAtlas with an filename and with an initial capacity for Quads.
	* The TextureAtlas capacity can be increased in runtime.
	*/
	static CCTextureAtlas * textureAtlasWithFile(const char* file , unsigned int capacity);

	/** initializes a TextureAtlas with a filename and with a certain capacity for Quads.
	* The TextureAtlas capacity can be increased in runtime.
	*
	* WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706)
	*/
	bool initWithFile(const char* file, unsigned int capacity);

	/** creates a TextureAtlas with a previously initialized Texture2D object, and
	* with an initial capacity for n Quads.
	* The TextureAtlas capacity can be increased in runtime.
	*/
	static CCTextureAtlas * textureAtlasWithTexture(CCTexture2D *texture, unsigned int capacity);

	/** initializes a TextureAtlas with a previously initialized Texture2D object, and
	* with an initial capacity for Quads.
	* The TextureAtlas capacity can be increased in runtime.
	*
	* WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706)
	*/
	bool initWithTexture(CCTexture2D *texture, unsigned int capacity);

	/** updates a Quad (texture, vertex and color) at a certain index
	* index must be between 0 and the atlas capacity - 1
	@since v0.8
	*/
	void updateQuad(ccV3F_C4B_T2F_Quad* quad, unsigned int index);

	/** Inserts a Quad (texture, vertex and color) at a certain index
	index must be between 0 and the atlas capacity - 1
	@since v0.8
	*/
	void insertQuad(ccV3F_C4B_T2F_Quad* quad, unsigned int index);

	/** Removes the quad that is located at a certain index and inserts it at a new index
	This operation is faster than removing and inserting in a quad in 2 different steps
	@since v0.7.2
	*/
	void insertQuadFromIndex(unsigned int fromIndex, unsigned int newIndex);

	/** removes a quad at a given index number.
	The capacity remains the same, but the total number of quads to be drawn is reduced in 1
	@since v0.7.2
	*/
	void removeQuadAtIndex(unsigned int index);

	/** removes all Quads.
	The TextureAtlas capacity remains untouched. No memory is freed.
	The total number of quads to be drawn will be 0
	@since v0.7.2
	*/
	void removeAllQuads();

	/** resize the capacity of the CCTextureAtlas.
	* The new capacity can be lower or higher than the current one
	* It returns YES if the resize was successful.
	* If it fails to resize the capacity it will return NO with a new capacity of 0.
	*/
	bool resizeCapacity(unsigned int n);

	/** draws n quads
	* n can't be greater than the capacity of the Atlas
	*/
	void drawNumberOfQuads(unsigned int n);

	/** draws n quads from an index (offset).
	n + start can't be greater than the capacity of the atlas

	@since v1.0
	*/
	void drawNumberOfQuads(unsigned int n, unsigned int start);

	/** draws all the Atlas's Quads
	*/
	void drawQuads();
private:
	void initIndices();
};
}//namespace   cocos2d

#endif //__CCTEXTURE_ATLAS_H__