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_FILEUTILS_PLATFORM_H__
#define __CC_FILEUTILS_PLATFORM_H__

#include <string>
#include "CCMutableDictionary.h"

NS_CC_BEGIN;

//! @brief  Helper class to handle file operations
class CC_DLL CCFileUtils
{
public:

    /**
    @brief Get resource file data
    @param[in]  pszFileName The resource file name which contain the path
    @param[in]  pszMode The read mode of the file
    @param[out] pSize If get the file data succeed the it will be the data size,or it will be 0
    @return if success,the pointer of data will be returned,or NULL is returned
    @warning If you get the file data succeed,you must delete it after used.
    */
    static unsigned char* getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize);

    /**
    @brief Get resource file data from zip file
    @param[in]  pszFileName The resource file name which contain the relative path of zip file
    @param[out] pSize If get the file data succeed the it will be the data size,or it will be 0
    @return if success,the pointer of data will be returned,or NULL is returned
    @warning If you get the file data succeed,you must delete it after used.
    */
    static unsigned char* getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize);

    /** removes the suffix from a path
     * On RetinaDisplay it will remove the -hd suffix
     * On iPad it will remove the -ipad suffix
     * On iPhone it will remove the (empty) suffix
     Only valid on iOS. Not valid for OS X.

     @since v0.99.5
     */
    static std::string& removeSuffixFromFile(std::string& path);

    /**
    @brief   Generate the absolute path of the file.
    @param   pszRelativePath     The relative path of the file.
    @return  The absolute path of the file.
    @warning We only add the ResourcePath before the relative path of the file.
    If you have not set the ResourcePath,the function add "/NEWPLUS/TDA_DATA/UserData/" as default.
    You can set ResourcePath by function void setResourcePath(const char *pszResourcePath);
    */
    static const char* fullPathFromRelativePath(const char *pszRelativePath);

	/** Returns the fullpath of an filename including the resolution of the image.

        If in RetinaDisplay mode, and a RetinaDisplay file is found, it will return that path.
        If in iPad mode, and an iPad file is found, it will return that path.

        Examples:

        * In iPad mode: "image.png" -> "/full/path/image-ipad.png" (in case the -ipad file exists)
        * In RetinaDisplay mode: "image.png" -> "/full/path/image-hd.png" (in case the -hd file exists)

        If an iPad file is found, it will set resolution type to kCCResolutioniPad
        If a RetinaDisplay file is found, it will set resolution type to kCCResolutionRetinaDisplay

      */
	static const char* fullPathFromRelativePath(const char *pszRelativePath, ccResolutionType *pResolutionType);

    /// @cond
    static const char* fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile);
    /// @endcond

	/** Sets the iPhone RetinaDisplay suffix to load resources.
        By default it is "-hd".
        Only valid on iOS. Not valid for OS X.

        @since v1.1
     */
	static void setiPhoneRetinaDisplaySuffix(const char *suffix);

	/** Sets the iPad suffix to load resources.
        By default it is "".
        Only valid on iOS. Not valid for OS X.

     */
	static void setiPadSuffix(const char *suffix);

	/** Sets the iPad Retina Display suffix to load resources.
        By default it is "-ipadhd".
        Only valid on iOS. Not valid for OS X.

        @since v1.1
     */
	static void setiPadRetinaDisplaySuffix(const char *suffix);

	/** Returns whether or not a given filename exists with the iPad suffix.
        Only available on iOS. Not supported on OS X.
        @since v1.1
    */
	bool iPadFileExistsAtPath(const char *filename);

	/** Returns whether or not a given filename exists with the iPad RetinaDisplay suffix.
        Only available on iOS. Not supported on OS X.

     */
	bool iPadRetinaDisplayFileExistsAtPath(const char *filename);

	/** Returns whether or not a given path exists with the iPhone RetinaDisplay suffix.
        Only available on iOS. Not supported on OS X.
        @since v1.1
    */
	bool iPhoneRetinaDisplayFileExistsAtPath(const char *filename);

    /**
    @brief  Set the ResourcePath,we will find resource in this path
    @param pszResourcePath  The absolute resource path
	@warning Don't call this function in android and iOS, it has not effect.
	In android, if you want to read file other than apk, you shoud use invoke getFileData(), and pass the
	absolute path.
    */
    static void setResourcePath(const char *pszResourcePath);

    /**
    @brief   Generate a CCDictionary pointer by file
    @param   pFileName  The file name of *.plist file
    @return  The CCDictionary pointer generated from the file
    */
    static CCDictionary<std::string, CCObject*> *dictionaryWithContentsOfFile(const char *pFileName);

	/*
	@brief The same meaning as dictionaryWithContentsOfFile(), but it doesn't call autorelease, so the
	       invoker should call release().
	*/
	static CCDictionary<std::string, CCObject*> *dictionaryWithContentsOfFileThreadSafe(const char *pFileName);

	/**
	@brief   Get the writeable path
	@return  The path that can write/read file
	*/
	static std::string getWriteablePath();

    /**
    @brief Set/Get whether pop-up a message box when the image load failed
    */
    static void setIsPopupNotify(bool bNotify);
    static bool getIsPopupNotify();

    ///////////////////////////////////////////////////
    // interfaces on wophone
    ///////////////////////////////////////////////////
    /**
    @brief  Set the resource zip file name
    @param pszZipFileName The relative path of the .zip file
    */
    static void setResource(const char* pszZipFileName);

    ///////////////////////////////////////////////////
    // interfaces on ios
    ///////////////////////////////////////////////////
    static int ccLoadFileIntoMemory(const char *filename, unsigned char **out);
};

class CCFileData
{
public:
    CCFileData(const char* pszFileName, const char* pszMode)
        : m_pBuffer(0)
        , m_uSize(0)
    {
        m_pBuffer = CCFileUtils::getFileData(pszFileName, pszMode, &m_uSize);
    }
    ~CCFileData()
    {
        CC_SAFE_DELETE_ARRAY(m_pBuffer);
    }

    bool reset(const char* pszFileName, const char* pszMode)
    {
        CC_SAFE_DELETE_ARRAY(m_pBuffer);
        m_uSize = 0;
        m_pBuffer = CCFileUtils::getFileData(pszFileName, pszMode, &m_uSize);
        return (m_pBuffer) ? true : false;
    }

    CC_SYNTHESIZE_READONLY(unsigned char *, m_pBuffer, Buffer);
    CC_SYNTHESIZE_READONLY(unsigned long ,  m_uSize,   Size);
};

NS_CC_END;

#endif	// end of __CC_EGLVIEW_PLATFORM_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.
****************************************************************************/

#include "CCGL.h"
#include "CCStdC.h"

NS_CC_BEGIN;

void gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar)
{
    GLfloat xmin, xmax, ymin, ymax;

    ymax = zNear * (GLfloat)tanf(fovy * (float)M_PI / 360);
    ymin = -ymax;
    xmin = ymin * aspect;
    xmax = ymax * aspect;

    glFrustumf(xmin, xmax,
        ymin, ymax,
        zNear, zFar);
}

void gluLookAt(float fEyeX, float fEyeY, float fEyeZ,
    float fCenterX, float fCenterY, float fCenterZ,
    float fUpX, float fUpY, float fUpZ)
{
    GLfloat m[16];
    GLfloat x[3], y[3], z[3];
    GLfloat mag;

    /* Make rotation matrix */

    /* Z vector */
    z[0] = fEyeX - fCenterX;
    z[1] = fEyeY - fCenterY;
    z[2] = fEyeZ - fCenterZ;
    mag = (float)sqrtf(z[0] * z[0] + z[1] * z[1] + z[2] * z[2]);
    if (mag) {
        z[0] /= mag;
        z[1] /= mag;
        z[2] /= mag;
    }

    /* Y vector */
    y[0] = fUpX;
    y[1] = fUpY;
    y[2] = fUpZ;

    /* X vector = Y cross Z */
    x[0] = y[1] * z[2] - y[2] * z[1];
    x[1] = -y[0] * z[2] + y[2] * z[0];
    x[2] = y[0] * z[1] - y[1] * z[0];

    /* Recompute Y = Z cross X */
    y[0] = z[1] * x[2] - z[2] * x[1];
    y[1] = -z[0] * x[2] + z[2] * x[0];
    y[2] = z[0] * x[1] - z[1] * x[0];

    /* cross product gives area of parallelogram, which is < 1.0 for
    * non-perpendicular unit-length vectors; so normalize x, y here
    */

    mag = (float)sqrtf(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
    if (mag) {
        x[0] /= mag;
        x[1] /= mag;
        x[2] /= mag;
    }

    mag = (float)sqrtf(y[0] * y[0] + y[1] * y[1] + y[2] * y[2]);
    if (mag) {
        y[0] /= mag;
        y[1] /= mag;
        y[2] /= mag;
    }

#define M(row,col)  m[col*4+row]
    M(0, 0) = x[0];
    M(0, 1) = x[1];
    M(0, 2) = x[2];
    M(0, 3) = 0.0f;
    M(1, 0) = y[0];
    M(1, 1) = y[1];
    M(1, 2) = y[2];
    M(1, 3) = 0.0f;
    M(2, 0) = z[0];
    M(2, 1) = z[1];
    M(2, 2) = z[2];
    M(2, 3) = 0.0f;
    M(3, 0) = 0.0f;
    M(3, 1) = 0.0f;
    M(3, 2) = 0.0f;
    M(3, 3) = 1.0f;
#undef M
    {
        int a;
        GLfloat fixedM[16];
        for (a = 0; a < 16; ++a)
            fixedM[a] = m[a];
        glMultMatrixf(fixedM);
    }

    /* Translate Eye to Origin */
    glTranslatef(-fEyeX, -fEyeY, -fEyeZ);
}

NS_CC_END;

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 __PLATFOMR_CCGL_H__
#define __PLATFOMR_CCGL_H__

//
// Common layer for OpenGL stuff
//

#include "CCEGLView.h"

#define CC_GLVIEW                   cocos2d::CCEGLView
#define ccglOrtho					glOrthof
#define	ccglClearDepth				glClearDepthf
#if (CC_TARGET_PLATFORM == CC_PLATFORM_QNX) || defined(CC_BADA_2_0)
#define ccglGenerateMipmap			CCEGLView::glGenerateMipmapOES
#define ccglGenFramebuffers			CCEGLView::glGenFramebuffersOES
#define ccglBindFramebuffer			CCEGLView::glBindFramebufferOES
#define ccglFramebufferTexture2D	CCEGLView::glFramebufferTexture2DOES
#define ccglDeleteFramebuffers		CCEGLView::glDeleteFramebuffersOES
#define ccglCheckFramebufferStatus	CCEGLView::glCheckFramebufferStatusOES
#else
#define ccglGenerateMipmap			glGenerateMipmapOES
#define ccglGenFramebuffers			glGenFramebuffersOES
#define ccglBindFramebuffer			glBindFramebufferOES
#define ccglFramebufferTexture2D	glFramebufferTexture2DOES
#define ccglDeleteFramebuffers		glDeleteFramebuffersOES
#define ccglCheckFramebufferStatus	glCheckFramebufferStatusOES
#endif
#define ccglTranslate				glTranslatef

#define CC_GL_FRAMEBUFFER			GL_FRAMEBUFFER_OES
#define CC_GL_FRAMEBUFFER_BINDING	GL_FRAMEBUFFER_BINDING_OES
#define CC_GL_COLOR_ATTACHMENT0		GL_COLOR_ATTACHMENT0_OES
#define CC_GL_FRAMEBUFFER_COMPLETE	GL_FRAMEBUFFER_COMPLETE_OES

#include "CCCommon.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "OpenGLES/ES1/gl.h"
#include "OpenGLES/ES1/glext.h"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
// GL_GLEXT_PROTOTYPES isn't defined in glplatform.h on android ndk r7
// we manually define it here
#include <GLES/glplatform.h>
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES 1
#endif
// normal process
#include <GLES/gl.h>
#include <GLES/glext.h>
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)
#include <GLES/gl.h>
#include <GLES/glext.h>
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include <GLES/gl.h>
#include <GLES/glext.h>
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
#include <GL/gl.h>
#include "GL/glext.h"

//declare here while define in CCEGLView_linux.cpp
extern PFNGLGENFRAMEBUFFERSEXTPROC         	glGenFramebuffersEXT;
extern PFNGLDELETEFRAMEBUFFERSEXTPROC      	glDeleteFramebuffersEXT;
extern PFNGLBINDFRAMEBUFFEREXTPROC         	glBindFramebufferEXT;
extern PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC  	glCheckFramebufferStatusEXT;
extern PFNGLFRAMEBUFFERTEXTURE2DEXTPROC    	glFramebufferTexture2DEXT;
extern PFNGLGENERATEMIPMAPEXTPROC          	glGenerateMipmapEXT;

extern PFNGLGENBUFFERSARBPROC 			   	glGenBuffersARB;
extern PFNGLBINDBUFFERARBPROC 				glBindBufferARB;
extern PFNGLBUFFERDATAARBPROC 				glBufferDataARB;
extern PFNGLBUFFERSUBDATAARBPROC 			glBufferSubDataARB;
extern PFNGLDELETEBUFFERSARBPROC 			glDeleteBuffersARB;

#undef ccglOrtho
#undef ccglClearDepth
#undef ccglTranslate
#undef ccglGenerateMipmap
#undef ccglGenFramebuffers
#undef ccglBindFramebuffer
#undef ccglFramebufferTexture2D
#undef ccglDeleteFramebuffers
#undef ccglCheckFramebufferStatus

#undef CC_GL_FRAMEBUFFER
#undef CC_GL_FRAMEBUFFER_BINDING
#undef CC_GL_COLOR_ATTACHMENT0
#undef CC_GL_FRAMEBUFFER_COMPLETE

#define ccglOrtho					glOrtho
#define	ccglClearDepth				glClearDepth
#define ccglTranslate				glTranslated

#define ccglGenerateMipmap			glGenerateMipmapEXT
#define ccglGenFramebuffers			glGenFramebuffersEXT
#define ccglBindFramebuffer			glBindFramebufferEXT
#define ccglFramebufferTexture2D	glFramebufferTexture2DEXT
#define ccglDeleteFramebuffers		glDeleteFramebuffersEXT
#define ccglCheckFramebufferStatus	glCheckFramebufferStatusEXT

#define glFrustumf                  glFrustum
#define glGenBuffers                glGenBuffersARB
#define glBindBuffer                glBindBufferARB
#define glBufferData                glBufferDataARB
#define glBufferSubData             glBufferSubDataARB
#define glDeleteBuffers             glDeleteBuffersARB

#define CC_GL_FRAMEBUFFER			GL_FRAMEBUFFER
#define CC_GL_FRAMEBUFFER_BINDING	GL_FRAMEBUFFER_BINDING
#define CC_GL_COLOR_ATTACHMENT0		GL_COLOR_ATTACHMENT0
#define CC_GL_FRAMEBUFFER_COMPLETE	GL_FRAMEBUFFER_COMPLETE

#define GL_POINT_SPRITE_OES         GL_POINT_SPRITE_ARB
#define GL_COORD_REPLACE_OES        GL_COORD_REPLACE_ARB
#define GL_POINT_SIZE_ARRAY_OES     GL_POINT_SIZE
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
#include <IwGL.h>
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_BADA)
#include "GLES/gl.h"
#include "GLES/glext.h"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_QNX)
#include <GLES/gl.h>
#include <GLES/glext.h>
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_QT)
// TODO: include correct headers for qt and remove function pointers if not needed
#include <GLES/gl.h>
#include <GLES/glext.h>
extern PFNGLGENERATEMIPMAPOESPROC glGenerateMipmapOES;
extern PFNGLGENFRAMEBUFFERSOESPROC glGenFramebuffersOES;
extern PFNGLBINDFRAMEBUFFEROESPROC glBindFramebufferOES;
extern PFNGLFRAMEBUFFERTEXTURE2DOESPROC glFramebufferTexture2DOES;
extern PFNGLDELETEFRAMEBUFFERSOESPROC glDeleteFramebuffersOES;
extern PFNGLCHECKFRAMEBUFFERSTATUSOESPROC glCheckFramebufferStatusOES;
#endif

NS_CC_BEGIN;

/*
OpenGL GLU implementation
*/

//typedef float GLfloat;

/** OpenGL gluLookAt implementation */
void CC_DLL gluLookAt(GLfloat fEyeX, GLfloat fEyeY, GLfloat fEyeZ,
               GLfloat fLookAtX, GLfloat fLookAtY, GLfloat fLookAtZ,
               GLfloat fUpX, GLfloat fUpY, GLfloat fUpZ);

/** OpenGL gluPerspective implementation */
void CC_DLL gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar);

NS_CC_END;

#endif // __PLATFOMR_CCGL_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.
****************************************************************************/

#include "CCImage.h"
#include "CCCommon.h"
#include "CCStdC.h"
#include "CCFileUtils.h"

#if (CC_TARGET_PLATFORM != CC_PLATFORM_QT)
// with Qt we use the QImage for loading and saving images
#include "png.h"

#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_QT)

#include <string>
#include <ctype.h>

#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
// on ios, we should use platform/ios/CCImage_ios.mm instead

#if (CC_TARGET_PLATFORM != CC_PLATFORM_QT)
// with Qt we use the QImage for loading and saving images

#define  QGLOBAL_H        // defined for wophone
#include "jpeglib.h"
#undef   QGLOBAL_H

#define CC_RGB_PREMULTIPLY_APLHA(vr, vg, vb, va) \
    (unsigned)(((unsigned)((unsigned char)(vr) * ((unsigned char)(va) + 1)) >> 8) | \
    ((unsigned)((unsigned char)(vg) * ((unsigned char)(va) + 1) >> 8) << 8) | \
    ((unsigned)((unsigned char)(vb) * ((unsigned char)(va) + 1) >> 8) << 16) | \
    ((unsigned)(unsigned char)(va) << 24))

typedef struct
{
    unsigned char* data;
    int size;
    int offset;
}tImageSource;

static void pngReadCallback(png_structp png_ptr, png_bytep data, png_size_t length)
{
    tImageSource* isource = (tImageSource*)png_get_io_ptr(png_ptr);

    if((int)(isource->offset + length) <= isource->size)
    {
        memcpy(data, isource->data+isource->offset, length);
        isource->offset += length;
    }
    else
    {
        png_error(png_ptr, "pngReaderCallback failed");
    }
}

#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_QT)

NS_CC_BEGIN;

//////////////////////////////////////////////////////////////////////////
// Impliment CCImage
//////////////////////////////////////////////////////////////////////////

CCImage::CCImage()
: m_nWidth(0)
, m_nHeight(0)
, m_nBitsPerComponent(0)
, m_pData(0)
, m_bHasAlpha(false)
, m_bPreMulti(false)
{

}

CCImage::~CCImage()
{
    CC_SAFE_DELETE_ARRAY(m_pData);
}

bool CCImage::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFmtPng*/)
{
    CC_UNUSED_PARAM(eImgFmt);
    CCFileData data(CCFileUtils::fullPathFromRelativePath(strPath), "rb");
    return initWithImageData(data.getBuffer(), data.getSize(), eImgFmt);
}

bool CCImage::initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType)
{
	CC_UNUSED_PARAM(imageType);
    CCFileData data(fullpath, "rb");
    return initWithImageData(data.getBuffer(), data.getSize(), imageType);
}

bool CCImage::initWithImageData(void * pData,
								int nDataLen,
								EImageFormat eFmt/* = eSrcFmtPng*/,
								int nWidth/* = 0*/,
								int nHeight/* = 0*/,
								int nBitsPerComponent/* = 8*/)
{
    bool bRet = false;
    do
    {
    	CC_BREAK_IF(! pData || nDataLen <= 0);

        if (kFmtPng == eFmt)
        {
            bRet = _initWithPngData(pData, nDataLen);
            break;
        }
        else if (kFmtJpg == eFmt)
        {
            bRet = _initWithJpgData(pData, nDataLen);
            break;
        }
		else if (kFmtRawData == eFmt)
		{
			bRet = _initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent);
			break;
		}
    } while (0);
    return bRet;
}

#if (CC_TARGET_PLATFORM != CC_PLATFORM_QT)
// with Qt we use the QImage for loading and saving images

bool CCImage::_initWithJpgData(void * data, int nSize)
{
    /* these are standard libjpeg structures for reading(decompression) */
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    /* libjpeg data structure for storing one row, that is, scanline of an image */
    JSAMPROW row_pointer[1] = {0};
    unsigned long location = 0;
    unsigned int i = 0;

    bool bRet = false;
    do
    {
        /* here we set up the standard libjpeg error handler */
        cinfo.err = jpeg_std_error( &jerr );

        /* setup decompression process and source, then read JPEG header */
        jpeg_create_decompress( &cinfo );

        jpeg_mem_src( &cinfo, (unsigned char *) data, nSize );

        /* reading the image header which contains image information */
        jpeg_read_header( &cinfo, true );

        // we only support RGB or grayscale
        if (cinfo.jpeg_color_space != JCS_RGB)
        {
            if (cinfo.jpeg_color_space == JCS_GRAYSCALE || cinfo.jpeg_color_space == JCS_YCbCr)
            {
                cinfo.out_color_space = JCS_RGB;
            }
        }
        else
        {
            break;
        }

        /* Start decompression jpeg here */
        jpeg_start_decompress( &cinfo );

        /* init image info */
        m_nWidth  = (short)(cinfo.image_width);
        m_nHeight = (short)(cinfo.image_height);
        m_bHasAlpha = false;
        m_bPreMulti = false;
        m_nBitsPerComponent = 8;
        row_pointer[0] = new unsigned char[cinfo.output_width*cinfo.output_components];
        CC_BREAK_IF(! row_pointer[0]);

        m_pData = new unsigned char[cinfo.output_width*cinfo.output_height*cinfo.output_components];
        CC_BREAK_IF(! m_pData);

        /* now actually read the jpeg into the raw buffer */
        /* read one scan line at a time */
        while( cinfo.output_scanline < cinfo.image_height )
        {
            jpeg_read_scanlines( &cinfo, row_pointer, 1 );
            for( i=0; i<cinfo.image_width*cinfo.num_components;i++)
                m_pData[location++] = row_pointer[0][i];
        }

        jpeg_finish_decompress( &cinfo );
        jpeg_destroy_decompress( &cinfo );
        /* wrap up decompression, destroy objects, free pointers and close open files */
        bRet = true;
    } while (0);

    CC_SAFE_DELETE_ARRAY(row_pointer[0]);
    return bRet;
}

bool CCImage::_initWithPngData(void * pData, int nDatalen)
{
    bool bRet = false;
    png_byte        header[8]   = {0};
    png_structp     png_ptr     =   0;
    png_infop       info_ptr    = 0;
    unsigned char * pImateData  = 0;

    do
    {
        // png header len is 8 bytes
    	CC_BREAK_IF(nDatalen < 8);

        // check the data is png or not
        memcpy(header, pData, 8);
        CC_BREAK_IF(png_sig_cmp(header, 0, 8));

        // init png_struct
        png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
        CC_BREAK_IF(! png_ptr);

        // init png_info
        info_ptr = png_create_info_struct(png_ptr);
        CC_BREAK_IF(!info_ptr);
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
        CC_BREAK_IF(setjmp(png_jmpbuf(png_ptr)));
#endif
        // set the read call back function
        tImageSource imageSource;
        imageSource.data    = (unsigned char*)pData;
        imageSource.size    = nDatalen;
        imageSource.offset  = 0;
        png_set_read_fn(png_ptr, &imageSource, pngReadCallback);

        // read png
        // PNG_TRANSFORM_EXPAND: perform set_expand()
        // PNG_TRANSFORM_PACKING: expand 1, 2 and 4-bit samples to bytes
        // PNG_TRANSFORM_STRIP_16: strip 16-bit samples to 8 bits
        // PNG_TRANSFORM_GRAY_TO_RGB: expand grayscale samples to RGB (or GA to RGBA)
        png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_PACKING
            | PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_GRAY_TO_RGB, 0);

        int         color_type  = 0;
        png_uint_32 nWidth = 0;
        png_uint_32 nHeight = 0;
        int         nBitsPerComponent = 0;
        png_get_IHDR(png_ptr, info_ptr, &nWidth, &nHeight, &nBitsPerComponent, &color_type, 0, 0, 0);

        // init image info
        m_bPreMulti = true;
        m_bHasAlpha = ( info_ptr->color_type & PNG_COLOR_MASK_ALPHA ) ? true : false;

        // allocate memory and read data
        int bytesPerComponent = 3;
        if (m_bHasAlpha)
        {
            bytesPerComponent = 4;
        }
        pImateData = new unsigned char[nHeight * nWidth * bytesPerComponent];
        CC_BREAK_IF(! pImateData);

        png_bytep * rowPointers = png_get_rows(png_ptr, info_ptr);

        // copy data to image info
        int bytesPerRow = nWidth * bytesPerComponent;
        if(m_bHasAlpha)
        {
            unsigned int *tmp = (unsigned int *)pImateData;
            for(unsigned int i = 0; i < nHeight; i++)
            {
                for(int j = 0; j < bytesPerRow; j += 4)
                {
                    *tmp++ = CC_RGB_PREMULTIPLY_APLHA( rowPointers[i][j], rowPointers[i][j + 1],
                        rowPointers[i][j + 2], rowPointers[i][j + 3] );
                }
            }
        }
        else
        {
            for (unsigned int j = 0; j < nHeight; ++j)
            {
                memcpy(pImateData + j * bytesPerRow, rowPointers[j], bytesPerRow);
            }
        }

        m_nBitsPerComponent = nBitsPerComponent;
        m_nHeight   = (short)nHeight;
        m_nWidth    = (short)nWidth;
        m_pData     = pImateData;
        pImateData  = 0;
        bRet        = true;
    } while (0);

    CC_SAFE_DELETE_ARRAY(pImateData);

    if (png_ptr)
    {
        png_destroy_read_struct(&png_ptr, (info_ptr) ? &info_ptr : 0, 0);
    }

    return bRet;
}

#endif // (CC_TARGET_PLATFORM != TARGET_OS_QT)
// with Qt we use the QImage for loading and saving images

bool CCImage::_initWithRawData(void * pData, int nDatalen, int nWidth, int nHeight, int nBitsPerComponent)
{
	bool bRet = false;
	do
	{
		CC_BREAK_IF(0 == nWidth || 0 == nHeight);

		m_nBitsPerComponent = nBitsPerComponent;
		m_nHeight   = (short)nHeight;
		m_nWidth    = (short)nWidth;
		m_bHasAlpha = true;

		// only RGBA8888 surported
		int nBytesPerComponent = 4;
		int nSize = nHeight * nWidth * nBytesPerComponent;
		m_pData = new unsigned char[nSize];
		CC_BREAK_IF(! m_pData);
		memcpy(m_pData, pData, nSize);

		bRet = true;
	} while (0);
	return bRet;
}

bool CCImage::saveToFile(const char *pszFilePath, bool bIsToRGB)
{
	bool bRet = false;

	do
	{
		CC_BREAK_IF(NULL == pszFilePath);

		std::string strFilePath(pszFilePath);
		CC_BREAK_IF(strFilePath.size() <= 4);

		std::string strLowerCasePath(strFilePath);
		for (unsigned int i = 0; i < strLowerCasePath.length(); ++i)
		{
			strLowerCasePath[i] = tolower(strFilePath[i]);
		}

		if (std::string::npos != strLowerCasePath.find(".png"))
		{
			CC_BREAK_IF(!_saveImageToPNG(pszFilePath, bIsToRGB));
		}
		else if (std::string::npos != strLowerCasePath.find(".jpg"))
		{
			CC_BREAK_IF(!_saveImageToJPG(pszFilePath));
		}
		else
		{
			break;
		}

		bRet = true;
	} while (0);

	return bRet;
}

#if (CC_TARGET_PLATFORM != CC_PLATFORM_QT)
// with Qt we use the QImage for loading and saving images

bool CCImage::_saveImageToPNG(const char * pszFilePath, bool bIsToRGB)
{
	bool bRet = false;
	do
	{
		CC_BREAK_IF(NULL == pszFilePath);

		FILE *fp;
		png_structp png_ptr;
		png_infop info_ptr;
		png_colorp palette;
		png_bytep *row_pointers;

		fp = fopen(pszFilePath, "wb");
		CC_BREAK_IF(NULL == fp);

		png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

		if (NULL == png_ptr)
		{
			fclose(fp);
			break;
		}

		info_ptr = png_create_info_struct(png_ptr);
		if (NULL == info_ptr)
		{
			fclose(fp);
			png_destroy_write_struct(&png_ptr, NULL);
			break;
		}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
		if (setjmp(png_jmpbuf(png_ptr)))
		{
			fclose(fp);
			png_destroy_write_struct(&png_ptr, &info_ptr);
			break;
		}
#endif
		png_init_io(png_ptr, fp);

		if (!bIsToRGB && m_bHasAlpha)
		{
			png_set_IHDR(png_ptr, info_ptr, m_nWidth, m_nHeight, 8, PNG_COLOR_TYPE_RGB_ALPHA,
				PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
		}
		else
		{
			png_set_IHDR(png_ptr, info_ptr, m_nWidth, m_nHeight, 8, PNG_COLOR_TYPE_RGB,
				PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
		}

		palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color));
		png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH);

		png_write_info(png_ptr, info_ptr);

		png_set_packing(png_ptr);

		row_pointers = (png_bytep *)malloc(m_nHeight * sizeof(png_bytep));
		if(row_pointers == NULL)
		{
			fclose(fp);
			png_destroy_write_struct(&png_ptr, &info_ptr);
			break;
		}

		if (!m_bHasAlpha)
		{
			for (int i = 0; i < (int)m_nHeight; i++)
			{
				row_pointers[i] = (png_bytep)m_pData + i * m_nWidth * 3;
			}

			png_write_image(png_ptr, row_pointers);

			free(row_pointers);
			row_pointers = NULL;
		}
		else
		{
			if (bIsToRGB)
			{
				unsigned char *pTempData = new unsigned char[m_nWidth * m_nHeight * 3];
				if (NULL == pTempData)
				{
					fclose(fp);
					png_destroy_write_struct(&png_ptr, &info_ptr);
					break;
				}

				for (int i = 0; i < m_nHeight; ++i)
				{
					for (int j = 0; j < m_nWidth; ++j)
					{
						pTempData[(i * m_nWidth + j) * 3] = m_pData[(i * m_nWidth + j) * 4];
						pTempData[(i * m_nWidth + j) * 3 + 1] = m_pData[(i * m_nWidth + j) * 4 + 1];
						pTempData[(i * m_nWidth + j) * 3 + 2] = m_pData[(i * m_nWidth + j) * 4 + 2];
					}
				}

				for (int i = 0; i < (int)m_nHeight; i++)
				{
					row_pointers[i] = (png_bytep)pTempData + i * m_nWidth * 3;
				}

				png_write_image(png_ptr, row_pointers);

				free(row_pointers);
				row_pointers = NULL;

				CC_SAFE_DELETE_ARRAY(pTempData);
			}
			else
			{
				for (int i = 0; i < (int)m_nHeight; i++)
				{
					row_pointers[i] = (png_bytep)m_pData + i * m_nWidth * 4;
				}

				png_write_image(png_ptr, row_pointers);

				free(row_pointers);
				row_pointers = NULL;
			}
		}

		png_write_end(png_ptr, info_ptr);

		png_free(png_ptr, palette);
		palette = NULL;

		png_destroy_write_struct(&png_ptr, &info_ptr);

		fclose(fp);

		bRet = true;
	} while (0);
	return bRet;
}
bool CCImage::_saveImageToJPG(const char * pszFilePath)
{
	bool bRet = false;
	do
	{
		CC_BREAK_IF(NULL == pszFilePath);

		struct jpeg_compress_struct cinfo;
		struct jpeg_error_mgr jerr;
		FILE * outfile;                 /* target file */
		JSAMPROW row_pointer[1];        /* pointer to JSAMPLE row[s] */
		int     row_stride;          /* physical row width in image buffer */

		cinfo.err = jpeg_std_error(&jerr);
		/* Now we can initialize the JPEG compression object. */
		jpeg_create_compress(&cinfo);

		CC_BREAK_IF((outfile = fopen(pszFilePath, "wb")) == NULL);

		jpeg_stdio_dest(&cinfo, outfile);

		cinfo.image_width = m_nWidth;    /* image width and height, in pixels */
		cinfo.image_height = m_nHeight;
		cinfo.input_components = 3;       /* # of color components per pixel */
		cinfo.in_color_space = JCS_RGB;       /* colorspace of input image */

		jpeg_set_defaults(&cinfo);

		jpeg_start_compress(&cinfo, TRUE);

		row_stride = m_nWidth * 3; /* JSAMPLEs per row in image_buffer */

		if (m_bHasAlpha)
		{
			unsigned char *pTempData = new unsigned char[m_nWidth * m_nHeight * 3];
			if (NULL == pTempData)
			{
				jpeg_finish_compress(&cinfo);
				jpeg_destroy_compress(&cinfo);
				fclose(outfile);
				break;
			}

			for (int i = 0; i < m_nHeight; ++i)
			{
				for (int j = 0; j < m_nWidth; ++j)

				{
					pTempData[(i * m_nWidth + j) * 3] = m_pData[(i * m_nWidth + j) * 4];
					pTempData[(i * m_nWidth + j) * 3 + 1] = m_pData[(i * m_nWidth + j) * 4 + 1];
					pTempData[(i * m_nWidth + j) * 3 + 2] = m_pData[(i * m_nWidth + j) * 4 + 2];
				}
			}

			while (cinfo.next_scanline < cinfo.image_height) {
				row_pointer[0] = & pTempData[cinfo.next_scanline * row_stride];
				(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
			}

			CC_SAFE_DELETE_ARRAY(pTempData);
		}
		else
		{
			while (cinfo.next_scanline < cinfo.image_height) {
				row_pointer[0] = & m_pData[cinfo.next_scanline * row_stride];
				(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
			}
		}

		jpeg_finish_compress(&cinfo);
		fclose(outfile);
		jpeg_destroy_compress(&cinfo);

		bRet = true;
	} while (0);
	return bRet;
}

#endif // (CC_TARGET_PLATFORM != TARGET_OS_QT)
// with Qt we use the QImage for loading and saving images

NS_CC_END;

#endif // (CC_TARGET_PLATFORM != TARGET_OS_IPHONE)
/* ios/CCImage_ios.mm uses "mm" as the extension,
   so we cannot inclue it in this CCImage.cpp.
   It makes a little difference on ios */

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "win32/CCImage_win32.cpp"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)
#include "wophone/CCImage_wophone.cpp"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "android/CCImage_android.cpp"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_BADA)
#include "bada/CCImage_bada.cpp"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_QNX)
#include "qnx/CCImage_qnx.cpp"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
#include "linux/CCImage_linux.cpp"
#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_IMAGE_H_YANGWS_20110115__
#define __CC_IMAGE_H_YANGWS_20110115__

#include "CCCommon.h"

NS_CC_BEGIN;

class CC_DLL CCImage
{
public:
    CCImage();
    ~CCImage();

    typedef enum
    {
        kFmtJpg = 0,
        kFmtPng,
		kFmtRawData,
		kFmtUnKnown
    }EImageFormat;

    typedef enum
    {
        kAlignCenter        = 0x33, ///< Horizontal center and vertical center.
        kAlignTop           = 0x13, ///< Horizontal center and vertical top.
        kAlignTopRight      = 0x12, ///< Horizontal right and vertical top.
        kAlignRight         = 0x32, ///< Horizontal right and vertical center.
        kAlignBottomRight   = 0x22, ///< Horizontal right and vertical bottom.
        kAlignBottom        = 0x23, ///< Horizontal center and vertical bottom.
        kAlignBottomLeft    = 0x21, ///< Horizontal left and vertical bottom.
        kAlignLeft          = 0x31, ///< Horizontal left and vertical center.
        kAlignTopLeft       = 0x11, ///< Horizontal left and vertical top.
    }ETextAlign;

    /**
    @brief  Load the image from the specified path.
    @param strPath   the absolute file path
    @param imageType the type of image, now only support tow types.
    @return  true if load correctly
    */
    bool initWithImageFile(const char * strPath, EImageFormat imageType = kFmtPng);

	/*
	 @brief The same meaning as initWithImageFile, but it is thread safe. It is casued by
	        loadImage() in CCTextureCache.cpp.
	 @param fullpath  full path of the file
     @param imageType the type of image, now only support tow types.
     @return  true if load correctly
	 */
	bool initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType = kFmtPng);

    /**
    @brief  Load image from stream buffer.

	@warning kFmtRawData only support RGBA8888
    @param pBuffer  stream buffer that hold the image data
    @param nLength  the length of data(managed in byte)
	@param nWidth, nHeight, nBitsPerComponent are used for kFmtRawData
    @return true if load correctly
    */
    bool initWithImageData(void * pData,
						   int nDataLen,
						   EImageFormat eFmt = kFmtPng,
						   int nWidth = 0,
						   int nHeight = 0,
						   int nBitsPerComponent = 8);

    /**
    @brief	Create image with specified string.
    @param  pText       the text which the image show, nil cause init fail
    @param  nWidth      the image width, if 0, the width match the text's width
    @param  nHeight     the image height, if 0, the height match the text's height
    @param  eAlignMask  the test Alignment
    @param  pFontName   the name of the font which use to draw the text. If nil, use the default system font.
    @param  nSize       the font size, if 0, use the system default size.
    */
    bool initWithString(
        const char *    pText,
        int             nWidth = 0,
        int             nHeight = 0,
        ETextAlign      eAlignMask = kAlignCenter,
        const char *    pFontName = 0,
        int             nSize = 0);

    unsigned char *   getData()               { return m_pData; }
    int         getDataLen()            { return m_nWidth * m_nHeight; }

    bool hasAlpha()                     { return m_bHasAlpha; }
    bool isPremultipliedAlpha()         { return m_bPreMulti; }

    void release();

    /**
    @brief	Save the CCImage data to specified file with specified format.
	@param	pszFilePath		the file's absolute path, including file subfix
	@param	bIsToRGB		if the image is saved as RGB format
    */
    bool saveToFile(const char *pszFilePath, bool bIsToRGB = true);

    CC_SYNTHESIZE_READONLY(short,   m_nWidth,       Width);
    CC_SYNTHESIZE_READONLY(short,   m_nHeight,      Height);
    CC_SYNTHESIZE_READONLY(int,     m_nBitsPerComponent,   BitsPerComponent);

protected:
    bool _initWithJpgData(void *pData, int nDatalen);
    bool _initWithPngData(void *pData, int nDatalen);

	// @warning kFmtRawData only support RGBA8888
	bool _initWithRawData(void *pData, int nDatalen, int nWidth, int nHeight, int nBitsPerComponent);

	bool _saveImageToPNG(const char *pszFilePath, bool bIsToRGB = true);
	bool _saveImageToJPG(const char *pszFilePath);

    unsigned char *m_pData;
    bool m_bHasAlpha;
    bool m_bPreMulti;

private:
    // noncopyable
    CCImage(const CCImage&    rImg);
    CCImage & operator=(const CCImage&);
};

NS_CC_END;

#endif	// __CC_IMAGE_H_YANGWS_20110115__


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_LIBXML2_H__
#define __CC_LIBXML2_H__

#include "CCPlatformConfig.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

#endif  // CC_PLATFORM_WIN32

#endif	// __CC_LIBXML2_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 __CC_PLATFORM_CONFIG_H__
#define __CC_PLATFORM_CONFIG_H__

/**
Config of cocos2d-x project.

There are config below:
build for which target platform
*/

//////////////////////////////////////////////////////////////////////////
// pre configure
//////////////////////////////////////////////////////////////////////////

// define supported target platform macro which CC uses.
#define CC_PLATFORM_UNKNOWN            0
#define CC_PLATFORM_IOS                1
#define CC_PLATFORM_ANDROID            2
#define CC_PLATFORM_WOPHONE            3
#define CC_PLATFORM_WIN32              4
#define CC_PLATFORM_MARMALADE          5
#define CC_PLATFORM_LINUX              6
#define CC_PLATFORM_BADA               7
#define CC_PLATFORM_QNX				   8
#define CC_PLATFORM_QT				   9

// Determine tartet platform by compile environment macro.
#define CC_TARGET_PLATFORM             CC_PLATFORM_UNKNOWN

// iphone
#if ! CC_TARGET_PLATFORM && (defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR))
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_IOS
    #define CC_SUPPORT_MULTITHREAD 0
    #define CC_SUPPORT_UNICODE 0
    #define CC_SUPPORT_PVRTC
#endif

// android
#if ! CC_TARGET_PLATFORM && defined(ANDROID)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_ANDROID
#endif

// wophone
#if ! CC_TARGET_PLATFORM && defined(_TRANZDA_VM_)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_WOPHONE
#endif

// win32
#if ! CC_TARGET_PLATFORM && (defined(WIN32) && defined(_WINDOWS))
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_WIN32

    #define CC_SUPPORT_MULTITHREAD     1
    #if defined(UNICODE)
        #define CC_SUPPORT_UNICODE     1
    #else
        #define CC_SUPPORT_UNICODE     0
    #endif
#endif

// linux
#if ! CC_TARGET_PLATFORM && defined(LINUX)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_LINUX
#endif

// marmalade
#if ! CC_TARGET_PLATFORM && defined(MARMALADE)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM         CC_PLATFORM_MARMALADE
#endif
// bada
#if ! CC_TARGET_PLATFORM && defined(SHP)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM         CC_PLATFORM_BADA
#endif

// qnx
#if ! CC_TARGET_PLATFORM && defined(__QNX__)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM     CC_PLATFORM_QNX
#endif

// qt
#if ! CC_TARGET_PLATFORM && (defined(MEEGO_EDITION_HARMATTAN) || defined(Q_OS_SYMBIAN))
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM     CC_PLATFORM_QT
#endif

//////////////////////////////////////////////////////////////////////////
// user configure
//////////////////////////////////////////////////////////////////////////

// Check user assigned target platform.
#if defined(CC_UNDER_IOS)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_IOS
#endif

#if defined(CC_UNDER_ANDROID)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_ANDROID
#endif

#if defined(CC_UNDER_WOPHONE)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_WOPHONE
#endif

#if defined(CC_UNDER_WIN32)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_WIN32
#endif

#if defined(CC_UNDER_MARMALADE)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM			   CC_PLATFORM_MARMALADE
#endif
#if defined(CC_UNDER_LINUX)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM			   CC_PLATFORM_LINUX
#endif

#if defined(CC_UNDER_BADA)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM			   CC_PLATFORM_BADA
#endif

#if defined(CC_UNDER_QNX)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM        	  CC_PLATFORM_QNX
#endif

#if defined(CC_UNDER_QT)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM        	  CC_PLATFORM_QT
#endif

// Check user assigned supportive of multi-thread
#if defined(CC_ENABLE_MULTITHREAD)
    #undef  CC_SUPPORT_MULTITHREAD
    #define CC_SUPPORT_MULTITHREAD     1
#elif defined(CC_DISABLE_MULTITHREAD)
    #undef  CC_SUPPORT_MULTITHREAD
    #define CC_SUPPORT_MULTITHREAD     0
#endif

// Check user assigned supportive of unicode
#if defined(CC_ENABLE_UNICODE)
#undef  CC_SUPPORT_UNICODE
#define CC_SUPPORT_UNICODE             1
#elif defined(CC_DISABLE_UNICODE)
#undef  CC_SUPPORT_UNICODE
#define CC_SUPPORT_UNICODE             0
#endif

//////////////////////////////////////////////////////////////////////////
// post configure
//////////////////////////////////////////////////////////////////////////

// check user set platform
#if ! CC_TARGET_PLATFORM
    #error  "Can not recognize the target platform, compling under a unsupported platform?"
#endif

// cocos2d-x havn't support multi-thread yet
#undef  CC_SUPPORT_MULTITHREAD
#define CC_SUPPORT_MULTITHREAD         0

// cocos2d-x havn't support unicode yet
#undef  CC_SUPPORT_UNICODE
#define CC_SUPPORT_UNICODE             0

// Check the supportive of platform
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#pragma warning (disable:4127)
#endif  // CC_PLATFORM_WIN32

#endif  // __CC_PLATFORM_CONFIG_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 __CC_PLATFORM_MACROS_H__
#define __CC_PLATFORM_MACROS_H__

/**
 * define some platform specific macros
 */
#include "ccConfig.h"
#include "CCPlatformConfig.h"

#define MacGLView					void
#define NSWindow					        void

/** @def CC_ENABLE_CACHE_TEXTTURE_DATA
Enable it if you want to cache the texture data.
Basically,it's only enabled in android

It's new in cocos2d-x since v0.99.5
*/
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    #define CC_ENABLE_CACHE_TEXTTURE_DATA       1
#else
    #define CC_ENABLE_CACHE_TEXTTURE_DATA       0
#endif

// generic macros

// namespace cocos2d {}
#define NS_CC_BEGIN                     namespace cocos2d {
#define NS_CC_END                       }
#define USING_NS_CC                     using namespace cocos2d

/** CC_PROPERTY_READONLY is used to declare a protected variable.
 We can use getter to read the variable.
 @param varType : the type of variable.
 @param varName : variable name.
 @param funName : "get + funName" is the name of the getter.
 @warning : The getter is a public virtual function, you should rewrite it first.
 The variables and methods declared after CC_PROPERTY_READONLY are all public.
 If you need protected or private, please declare.
 */
#define CC_PROPERTY_READONLY(varType, varName, funName)\
protected: varType varName;\
public: virtual varType get##funName(void);

#define CC_PROPERTY_READONLY_PASS_BY_REF(varType, varName, funName)\
protected: varType varName;\
public: virtual const varType& get##funName(void);

/** CC_PROPERTY is used to declare a protected variable.
 We can use getter to read the variable, and use the setter to change the variable.
 @param varType : the type of variable.
 @param varName : variable name.
 @param funName : "get + funName" is the name of the getter.
 "set + funName" is the name of the setter.
 @warning : The getter and setter are public virtual functions, you should rewrite them first.
 The variables and methods declared after CC_PROPERTY are all public.
 If you need protected or private, please declare.
 */
#define CC_PROPERTY(varType, varName, funName)\
protected: varType varName;\
public: virtual varType get##funName(void);\
public: virtual void set##funName(varType var);

#define CC_PROPERTY_PASS_BY_REF(varType, varName, funName)\
protected: varType varName;\
public: virtual const varType& get##funName(void);\
public: virtual void set##funName(const varType& var);

/** CC_SYNTHESIZE_READONLY is used to declare a protected variable.
 We can use getter to read the variable.
 @param varType : the type of variable.
 @param varName : variable name.
 @param funName : "get + funName" is the name of the getter.
 @warning : The getter is a public inline function.
 The variables and methods declared after CC_SYNTHESIZE_READONLY are all public.
 If you need protected or private, please declare.
 */
#define CC_SYNTHESIZE_READONLY(varType, varName, funName)\
protected: varType varName;\
public: virtual varType get##funName(void) const { return varName; }

#define CC_SYNTHESIZE_READONLY_PASS_BY_REF(varType, varName, funName)\
protected: varType varName;\
public: virtual const varType& get##funName(void) const { return varName; }

/** CC_SYNTHESIZE is used to declare a protected variable.
 We can use getter to read the variable, and use the setter to change the variable.
 @param varType : the type of variable.
 @param varName : variable name.
 @param funName : "get + funName" is the name of the getter.
 "set + funName" is the name of the setter.
 @warning : The getter and setter are public  inline functions.
 The variables and methods declared after CC_SYNTHESIZE are all public.
 If you need protected or private, please declare.
 */
#define CC_SYNTHESIZE(varType, varName, funName)\
protected: varType varName;\
public: virtual varType get##funName(void) const { return varName; }\
public: virtual void set##funName(varType var){ varName = var; }

#define CC_SYNTHESIZE_PASS_BY_REF(varType, varName, funName)\
protected: varType varName;\
public: virtual const varType& get##funName(void) const { return varName; }\
public: virtual void set##funName(const varType& var){ varName = var; }

#define CC_SYNTHESIZE_RETAIN(varType, varName, funName)    \
protected: varType varName; \
public: virtual varType get##funName(void) const { return varName; } \
public: virtual void set##funName(varType var)   \
{ \
    CC_SAFE_RETAIN(var); \
    CC_SAFE_RELEASE(varName); \
    varName = var; \
}

#define CC_SAFE_DELETE(p)			if(p) { delete (p); (p) = 0; }
#define CC_SAFE_DELETE_ARRAY(p)    if(p) { delete[] (p); (p) = 0; }
#define CC_SAFE_FREE(p)			if(p) { free(p); (p) = 0; }
#define CC_SAFE_RELEASE(p)			if(p) { (p)->release(); }
#define CC_SAFE_RELEASE_NULL(p)	if(p) { (p)->release(); (p) = 0; }
#define CC_SAFE_RETAIN(p)			if(p) { (p)->retain(); }
#define CC_BREAK_IF(cond)			if(cond) break;

// cocos2d debug
#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0
#define CCLOG(...)
#define CCLOGINFO(...)
#define CCLOGERROR(...)

#elif COCOS2D_DEBUG == 1
#define CCLOG(format, ...)      cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGERROR(format,...)  cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGINFO(format,...)   do {} while (0)

#elif COCOS2D_DEBUG > 1
#define CCLOG(format, ...)      cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGERROR(format,...)  cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGINFO(format,...)   cocos2d::CCLog(format, ##__VA_ARGS__)
#endif // COCOS2D_DEBUG

// Lua engine debug
#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 || CC_LUA_ENGINE_DEBUG == 0
#define LUALOG(...)
#else
#define LUALOG(format, ...)     cocos2d::CCLog(format, ##__VA_ARGS__)
#endif // Lua engine debug

// shared library declartor
#define CC_DLL

#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
// assertion
#include <assert.h>
#define CC_ASSERT(cond)                assert(cond)
#else
// bada platform

#include <FBaseConfig.h>
#include <FBaseSys.h>

#undef CC_DLL
#define CC_DLL  _EXPORT_

#include "CCPlatformFunc_bada.h"

#ifdef _DEBUG
#define CC_ASSERT(cond)  (void)( (!!(cond)) || (badaAssert(__PRETTY_FUNCTION__ , __LINE__ , #cond),0) )
#else
#define CC_ASSERT(cond)  void(0)
#endif /* _DEBUG */
#endif

#define CC_UNUSED_PARAM(unusedparam)   (void)unusedparam

#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
#undef CC_UNUSED_PARAM
#define CC_UNUSED_PARAM(unusedparam)   //unusedparam
#endif

// platform depended macros

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

    #undef CC_DLL
    #if defined(_USRDLL)
        #define CC_DLL     __declspec(dllexport)
    #else 		/* use a DLL library */
        #define CC_DLL     __declspec(dllimport)
    #endif

#endif  // CC_PLATFORM_WIN32

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE && defined(_TRANZDA_VM_))

    #undef CC_DLL
    #if defined(SS_MAKEDLL)
        #define CC_DLL     __declspec(dllexport)
    #else 		/* use a DLL library */
        #define CC_DLL     __declspec(dllimport)
    #endif

#endif  // wophone VM

#if (CC_TARGET_PLATFORM == CC_PLATFORM_QT)
    #include <QtCore/qglobal.h>
    #undef CC_DLL
    #define CC_DLL Q_DECL_EXPORT
#endif

#endif // __CC_PLATFORM_MACROS_H__


code:
/****************************************************************************
 Copyright (c) 2010 cocos2d-x.org  http://cocos2d-x.org
 Copyright (c) 2010 Максим Аксенов

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

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

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

#include "CCSAXParser.h"
#include "CCMutableDictionary.h"
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include "CCLibxml2.h"
#include "CCFileUtils.h"

NS_CC_BEGIN;

CCSAXParser::CCSAXParser()
{
	m_pDelegator = NULL;

}

CCSAXParser::~CCSAXParser(void)
{
}

bool CCSAXParser::init(const char *pszEncoding)
{
    CC_UNUSED_PARAM(pszEncoding);
	// nothing to do
	return true;
}

bool CCSAXParser::parse(const char *pszFile)
{
	CCFileData data(pszFile, "rt");
	unsigned long size = data.getSize();
	char *pBuffer = (char*) data.getBuffer();

	if (!pBuffer)
	{
		return false;
	}

	/*
	 * this initialize the library and check potential ABI mismatches
	 * between the version it was compiled for and the actual shared
	 * library used.
	 */
	LIBXML_TEST_VERSION
	xmlSAXHandler saxHandler;
	memset( &saxHandler, 0, sizeof(saxHandler) );
	// Using xmlSAXVersion( &saxHandler, 2 ) generate crash as it sets plenty of other pointers...
	saxHandler.initialized = XML_SAX2_MAGIC;  // so we do this to force parsing as SAX2.
	saxHandler.startElement = &CCSAXParser::startElement;
	saxHandler.endElement = &CCSAXParser::endElement;
	saxHandler.characters = &CCSAXParser::textHandler;

	int result = xmlSAXUserParseMemory( &saxHandler, this, pBuffer, size );
	if ( result != 0 )
	{
		return false;
	}
	/*
	 * Cleanup function for the XML library.
	 */
	xmlCleanupParser();
	/*
	 * this is to debug memory for regression tests
	 */
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
	xmlMemoryDump();
#endif

	return true;
}

void CCSAXParser::startElement(void *ctx, const CC_XML_CHAR *name, const CC_XML_CHAR **atts)
{
	((CCSAXParser*)(ctx))->m_pDelegator->startElement(ctx, (char*)name, (const char**)atts);
}

void CCSAXParser::endElement(void *ctx, const CC_XML_CHAR *name)
{
	((CCSAXParser*)(ctx))->m_pDelegator->endElement(ctx, (char*)name);
}
void CCSAXParser::textHandler(void *ctx, const CC_XML_CHAR *name, int len)
{
	((CCSAXParser*)(ctx))->m_pDelegator->textHandler(ctx, (char*)name, len);
}
void CCSAXParser::setDelegator(CCSAXDelegator* pDelegator)
{
	m_pDelegator = pDelegator;
}

NS_CC_END;


code:
/****************************************************************************
 Copyright (c) 2010 cocos2d-x.org  http://cocos2d-x.org
 Copyright (c) 2010 Максим Аксенов

 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 __CCSAXPARSER_H__
#define __CCSAXPARSER_H__

#include "CCPlatformConfig.h"
#include "CCCommon.h"

NS_CC_BEGIN;

typedef unsigned char CC_XML_CHAR;

class CC_DLL CCSAXDelegator
{
public:
	virtual void startElement(void *ctx, const char *name, const char **atts) = 0;
	virtual void endElement(void *ctx, const char *name) = 0;
	virtual void textHandler(void *ctx, const char *s, int len) = 0;
};

class CC_DLL CCSAXParser
{
	CCSAXDelegator*	m_pDelegator;
public:

	CCSAXParser();
	~CCSAXParser(void);

	bool init(const char *pszEncoding);
	bool parse(const char *pszFile);
	void setDelegator(CCSAXDelegator* pDelegator);

	static void startElement(void *ctx, const CC_XML_CHAR *name, const CC_XML_CHAR **atts);
	static void endElement(void *ctx, const CC_XML_CHAR *name);
	static void textHandler(void *ctx, const CC_XML_CHAR *name, int len);
};
NS_CC_END;

#endif //__CCSAXPARSER_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.
****************************************************************************/

#include "CCStdC.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

int CC_DLL gettimeofday(struct timeval * val, struct timezone *)
{
    if (val)
    {
        LARGE_INTEGER liTime, liFreq;
		QueryPerformanceFrequency( &liFreq );
        QueryPerformanceCounter( &liTime );
        val->tv_sec     = (long)( liTime.QuadPart / liFreq.QuadPart );
        val->tv_usec    = (long)( liTime.QuadPart * 1000000.0 / liFreq.QuadPart - val->tv_sec * 1000000.0 );
    }
    return 0;
}
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_BADA)

using namespace Osp::System;

int CC_DLL gettimeofday(struct timeval * val, struct timezone *)
{
    if (val)
    {
    	long long curTick = 0;
    	SystemTime::GetTicks(curTick);
    	unsigned int ms = curTick;
    	val->tv_sec = ms / 1000;
    	val->tv_usec = (ms % 1000) * 1000;
    }
    return 0;
}

#endif  // CC_PLATFORM_WIN32


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_STD_C_H__
#define __CC_STD_C_H__

#include "CCPlatformMacros.h"

#include <float.h>

// for math.h on win32 platform
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

    #if ! defined(_USE_MATH_DEFINES)
        #define _USE_MATH_DEFINES       // make M_PI can be use
    #endif

    #if ! defined(isnan)
        #define isnan   _isnan
    #endif

#endif  // CC_PLATFORM_WIN32

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE && defined(_TRANZDA_VM_))

    #if ! defined(_USE_MATH_DEFINES)
        #define _USE_MATH_DEFINES       // make M_PI can be use
    #endif

    #if ! defined(isnan)
        #define isnan   _isnan
    #endif

#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE && defined(_TRANZDA_VM_)

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)

#include "TG3.h"

#endif  // CC_PLATFORM_WOPHONE

#include <math.h>

#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// for MIN MAX and sys/time.h on win32 platform
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

#define MIN     min
#define MAX     max

// Structure timeval has define in winsock.h, include windows.h for it.
#include <Windows.h>

struct timezone
{
    int tz_minuteswest;
    int tz_dsttime;
};

int CC_DLL gettimeofday(struct timeval *, struct timezone *);

#endif  // CC_PLATFORM_WIN32

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX || CC_TARGET_PLATFORM == CC_PLATFORM_QNX || CC_TARGET_PLATFORM == CC_PLATFORM_QT)

#include <sys/time.h>

#ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif  // MIN

#ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif  // MAX

#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)

// some function linux do not have
#define tanf tan
#define sqrtf sqrt
#define cosf cos
#define sinf sin

#endif

#endif  // CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)

#include <s3e.h>
#include <sys/time.h>

#ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif  // MIN

#ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif  // MAX

#endif  // CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE

#if (CC_TARGET_PLATFORM == CC_PLATFORM_BADA)

#include <FSysSystemTime.h>

struct timeval
{
 	long tv_sec;		// seconds
 	long tv_usec;    // microSeconds
};

struct timezone
{
    int tz_minuteswest;
    int tz_dsttime;
};

int CC_DLL gettimeofday(struct timeval *, struct timezone *);

#ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif  // MIN

#ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif  // MAX

#ifndef UINT_MAX
#define UINT_MAX      0xffffffff    /* maximum unsigned int value */
#endif  // UINT_MAX

#endif  // CC_TARGET_PLATFORM == CC_PLATFORM_BADA

#endif  // __CC_STD_C_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.
****************************************************************************/

#include "CCThread.h"

NS_CC_BEGIN;

CCThread::~CCThread()
{

}

void CCThread::createAutoreleasePool()
{

}

NS_CC_END;


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_PLATFORM_THREAD_H__
#define __CC_PLATFORM_THREAD_H__

#include "CCCommon.h"
#include "CCPlatformMacros.h"

NS_CC_BEGIN;

/* On iOS, should create autorelease pool when create a new thread
 * and release it when the thread end.
 */
class CC_DLL CCThread
{
public:
	CCThread() : m_pAutoreasePool(0) {}
	~CCThread();

	void createAutoreleasePool();

private:
	void *m_pAutoreasePool;
};

NS_CC_END;

#endif	// __CC_PLATFORM_THREAD_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.
****************************************************************************/
#include "CCAccelerometer_android.h"
#include "jni/SensorJni.h"
#include <stdio.h>
#include <android/log.h>

#define TG3_GRAVITY_EARTH                    (9.80665f)
#define  LOG_TAG    "CCAccelerometer_android"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)

namespace cocos2d
{
	CCAccelerometer* CCAccelerometer::m_spCCAccelerometer = NULL;

	CCAccelerometer::CCAccelerometer() : m_pAccelDelegate(NULL)
	{
	}

    CCAccelerometer::~CCAccelerometer()
	{
		m_spCCAccelerometer = NULL;
    }

    CCAccelerometer* CCAccelerometer::sharedAccelerometer()
	{

    	if (m_spCCAccelerometer == NULL)
    	{
    		m_spCCAccelerometer = new CCAccelerometer();
    	}

    	return m_spCCAccelerometer;
    }

    void CCAccelerometer::setDelegate(CCAccelerometerDelegate* pDelegate)
	{
		m_pAccelDelegate = pDelegate;

		if (pDelegate)
		{
			enableAccelerometerJNI();
		}
		else
		{
			disableAccelerometerJNI();
		}
    }

    void CCAccelerometer::update(float x, float y, float z, long sensorTimeStamp)
	{
		if (m_pAccelDelegate)
		{
			m_obAccelerationValue.x = -((double)x / TG3_GRAVITY_EARTH);
			m_obAccelerationValue.y = -((double)y / TG3_GRAVITY_EARTH);
			m_obAccelerationValue.z = -((double)z / TG3_GRAVITY_EARTH);
			m_obAccelerationValue.timestamp = (double)sensorTimeStamp;

			m_pAccelDelegate->didAccelerate(&m_obAccelerationValue);
		}
    }
} // end of namespace cococs2d


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 __PLATFORM_ANDROID_CCACCELEROMETER_H__
#define __PLATFORM_ANDROID_CCACCELEROMETER_H__

#include "CCCommon.h"
#include "CCAccelerometerDelegate.h"

namespace   cocos2d {

class CC_DLL CCAccelerometer
{
public:
	CCAccelerometer();
    ~CCAccelerometer();

    static CCAccelerometer* sharedAccelerometer();

    void setDelegate(CCAccelerometerDelegate* pDelegate);
    void update(float x, float y, float z, long sensorTimeStamp);

private:
	static CCAccelerometer* m_spCCAccelerometer;
	CCAccelerometerDelegate* m_pAccelDelegate;
	CCAcceleration m_obAccelerationValue;
};

}//namespace cocos2d

#endif


code:
#include "CCApplication.h"
#include "jni/JniHelper.h"
#include "CCDirector.h"
#include "CCEGLView.h"
#include "android/jni/SystemInfoJni.h"
#include <android/log.h>
#include <jni.h>

#include <cstring>

#define  LOG_TAG    "CCApplication_android Debug"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)

NS_CC_BEGIN;

// sharedApplication pointer
CCApplication * CCApplication::sm_pSharedApplication = 0;

CCApplication::CCApplication()
{
    CC_ASSERT(! sm_pSharedApplication);
    sm_pSharedApplication = this;
}

CCApplication::~CCApplication()
{
    CC_ASSERT(this == sm_pSharedApplication);
    sm_pSharedApplication = NULL;
}

int CCApplication::run()
{
        // Initialize instance and cocos2d.
        if (! initInstance() || ! applicationDidFinishLaunching())
        {
                return 0;
        }

	return -1;
}

void CCApplication::setAnimationInterval(double interval)
{
	JniMethodInfo methodInfo;
	if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxRenderer", "setAnimationInterval",
		"(D)V"))
	{
		CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__);
	}
	else
	{
		methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, interval);
	}
}

CCApplication::Orientation CCApplication::setOrientation(Orientation orientation)
{
    return orientation;
}

void CCApplication::statusBarFrame(CCRect * rect)
{
    if (rect)
    {
        // android doesn't have status bar.
        *rect = CCRectMake(0, 0, 0, 0);
    }
}

//////////////////////////////////////////////////////////////////////////
// static member function
//////////////////////////////////////////////////////////////////////////
CCApplication& CCApplication::sharedApplication()
{
    CC_ASSERT(sm_pSharedApplication);
    return *sm_pSharedApplication;
}

ccLanguageType CCApplication::getCurrentLanguage()
{
    const char *pLanguageName = getCurrentLanguageJNI();
    ccLanguageType ret = kLanguageEnglish;

    if (0 == strcmp("zh", pLanguageName))
    {
        ret = kLanguageChinese;
    }
    else if (0 == strcmp("en", pLanguageName))
    {
        ret = kLanguageEnglish;
    }
    else if (0 == strcmp("fr", pLanguageName))
    {
        ret = kLanguageFrench;
    }
    else if (0 == strcmp("it", pLanguageName))
    {
        ret = kLanguageItalian;
    }
    else if (0 == strcmp("de", pLanguageName))
    {
        ret = kLanguageGerman;
    }
    else if (0 == strcmp("es", pLanguageName))
    {
        ret = kLanguageSpanish;
    }
	else if (0 == strcmp("ru", pLanguageName))
    {
        ret = kLanguageRussian;
    }

    return ret;
}

NS_CC_END;


code:
#ifndef __CC_APPLICATION_ANDROID_H__
#define __CC_APPLICATION_ANDROID_H__

#include "CCApplication.h"

#include "CCCommon.h"

NS_CC_BEGIN;

class CCRect;

class CC_DLL CCApplication
{
public:
    CCApplication();
    virtual ~CCApplication();

    /**
    @brief	Implement for initialize OpenGL instance, set source path, etc...
    */
    virtual bool initInstance() = 0;

    /**
    @brief	Implement CCDirector and CCScene init code here.
    @return true    Initialize success, app continue.
    @return false   Initialize failed, app terminate.
    */
    virtual bool applicationDidFinishLaunching() = 0;

    /**
    @brief  The function be called when the application enter background
    @param  the pointer of the application
    */
    virtual void applicationDidEnterBackground() = 0;

    /**
    @brief  The function be called when the application enter foreground
    @param  the pointer of the application
    */
    virtual void applicationWillEnterForeground() = 0;

    /**
    @brief	Callback by CCDirector for limit FPS.
    @interval       The time, which expressed in second in second, between current frame and next.
    */
    void setAnimationInterval(double interval);

    typedef enum
    {
        /// Device oriented vertically, home button on the bottom
        kOrientationPortrait = 0,
        /// Device oriented vertically, home button on the top
        kOrientationPortraitUpsideDown = 1,
        /// Device oriented horizontally, home button on the right
        kOrientationLandscapeLeft = 2,
        /// Device oriented horizontally, home button on the left
        kOrientationLandscapeRight = 3,
    } Orientation;

    /**
    @brief	Callback by CCDirector for change device orientation.
    @orientation    The defination of orientation which CCDirector want change to.
    @return         The actual orientation of the application.
    */
    Orientation setOrientation(Orientation orientation);

    /**
    @brief	Get status bar rectangle in EGLView window.
    */
    void    statusBarFrame(CCRect * rect);

    /**
    @brief	Run the message loop.
    */
    int run();

    /**
    @brief	Get current applicaiton instance.
    @return Current application instance pointer.
    */
    static CCApplication& sharedApplication();

    /**
    @brief Get current language config
    @return Current language config
    */
    static ccLanguageType getCurrentLanguage();

protected:
    static CCApplication * sm_pSharedApplication;
};

NS_CC_END;

#endif	// __CCX_APPLICATION_ANDROID_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.
****************************************************************************/
#include "CCEGLView_android.h"
#include "GLES/gl.h"
#include "CCSet.h"
#include "CCDirector.h"
#include "ccMacros.h"
#include "CCTouchDispatcher.h"
#include "jni/IMEJni.h"
#include "jni/MessageJni.h"

#include <stdlib.h>

namespace cocos2d {

CCEGLView::CCEGLView()
    : m_bNotHVGA(false),
      m_pDelegate(NULL),
      m_fScreenScaleFactor(1.0)
{
}

void CCEGLView::setFrameWidthAndHeight(int width, int height)
{
	m_sSizeInPixel.width = width;
	m_sSizeInPixel.height = height;
}

bool CCEGLView::isIpad()
{
    return false;
}

void CCEGLView::create(int width, int height)
{
	if (width == 0 || height == 0)
	{
		return;
	}

	m_sSizeInPoint.width = width;
	m_sSizeInPoint.height = height;

	// calculate the factor and the rect of viewport
	m_fScreenScaleFactor =  MIN((float)m_sSizeInPixel.width / m_sSizeInPoint.width,
		                         (float)m_sSizeInPixel.height / m_sSizeInPoint.height);
	int viewPortW = (int)(m_sSizeInPoint.width * m_fScreenScaleFactor);
	int viewPortH = (int)(m_sSizeInPoint.height * m_fScreenScaleFactor);
	m_rcViewPort.origin.x = (m_sSizeInPixel.width - viewPortW) / 2;
	m_rcViewPort.origin.y = (m_sSizeInPixel.height - viewPortH) / 2;
	m_rcViewPort.size.width = viewPortW;
	m_rcViewPort.size.height = viewPortH;

	m_bNotHVGA = true;

}

CCEGLView::~CCEGLView()
{
	CC_SAFE_DELETE(m_pDelegate);
}

CCSize  CCEGLView::getSize()
{
        if (m_bNotHVGA)
        {
                CCSize size(m_sSizeInPoint.width, m_sSizeInPoint.height);
	        return size;
        }
        else
        {
                CCSize size(m_sSizeInPixel.width, m_sSizeInPixel.height);
	        return size;
        }

}

bool CCEGLView::isOpenGLReady()
{
	return (m_sSizeInPixel.width != 0 && m_sSizeInPixel.height != 0);
}

void CCEGLView::release()
{
	terminateProcessJNI();
}

void CCEGLView::setTouchDelegate(EGLTouchDelegate * pDelegate)
{
	m_pDelegate = pDelegate;
}

EGLTouchDelegate* CCEGLView::getDelegate(void)
{
	return m_pDelegate;
}

void CCEGLView::swapBuffers()
{
}

bool CCEGLView::canSetContentScaleFactor()
{
    // can scale content?
    return false;
}

void CCEGLView::setContentScaleFactor(float contentScaleFactor)
{
	m_fScreenScaleFactor = contentScaleFactor;
}

void CCEGLView::setViewPortInPoints(float x, float y, float w, float h)
{
    if (m_bNotHVGA)
    {
        float factor = m_fScreenScaleFactor / CC_CONTENT_SCALE_FACTOR();
        glViewport((GLint)(x * factor) + m_rcViewPort.origin.x,
            (GLint)(y * factor) + m_rcViewPort.origin.y,
            (GLint)(w * factor),
            (GLint)(h * factor));
    }
    else
    {
        glViewport((GLint)x,
            (GLint)y,
            (GLint)w,
            (GLint)h);
    }
}

void CCEGLView::setScissorInPoints(float x, float y, float w, float h)
{
    if (m_bNotHVGA)
    {
        float factor = m_fScreenScaleFactor / CC_CONTENT_SCALE_FACTOR();
        glScissor((GLint)(x * factor) + m_rcViewPort.origin.x,
            (GLint)(y * factor) + m_rcViewPort.origin.y,
            (GLint)(w * factor),
            (GLint)(h * factor));
    }
    else
    {
        glScissor((GLint)x,
            (GLint)y,
            (GLint)w,
            (GLint)h);
    }
}

CCEGLView& CCEGLView::sharedOpenGLView()
{
	static CCEGLView instance;
	return instance;
}

float CCEGLView::getScreenScaleFactor()
{
        return m_fScreenScaleFactor;
}

CCRect CCEGLView::getViewPort()
{
    if (m_bNotHVGA)
    {
        return m_rcViewPort;
    }
    else
    {
        CCRect rect(0, 0, 0, 0);
        return rect;
    }
}

void CCEGLView::setIMEKeyboardState(bool bOpen)
{

    setKeyboardStateJNI((int)bOpen);
}

}       // end of namespace cocos2d


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_EGLVIEW_ANDROID_H__
#define __CC_EGLVIEW_ANDROID_H__

#include "CCGeometry.h"

namespace   cocos2d {
class CCSet;
class CCTouch;
class EGLTouchDelegate;

class CC_DLL CCEGLView
{
public:
    CCEGLView();
    virtual ~CCEGLView();

    CCSize  getSize();
    bool    isOpenGLReady();
    bool    isIpad();
	/**
	 * the width and height is the real size of phone
	 */
    void    setFrameWidthAndHeight(int width, int height);
	/**
	 * create a drawing rect,
	 * the width and heiht is the resource size match best
	 */
	void    create(int width, int height);
    EGLTouchDelegate* getDelegate(void);

    // keep compatible
    void    release();
    void    setTouchDelegate(EGLTouchDelegate * pDelegate);
    void    swapBuffers();
    bool    canSetContentScaleFactor();
    void    setContentScaleFactor(float contentScaleFactor);
	void    setViewPortInPoints(float x, float y, float w, float h);
    void    setScissorInPoints(float x, float y, float w, float h);
	CCRect  getViewPort();
	float   getScreenScaleFactor();
    void    setIMEKeyboardState(bool bOpen);

    float   getMainScreenScale() { return -1.0f; }

	// static function
	/**
	@brief	get the shared main open gl window
	*/
	static CCEGLView& sharedOpenGLView();

private:
	CCSize m_sSizeInPixel;
	CCSize m_sSizeInPoint;
	CCRect m_rcViewPort;
	bool   m_bNotHVGA;

	EGLTouchDelegate *m_pDelegate;
	float  m_fScreenScaleFactor;
};

}   // end of namespace   cocos2d

#endif	// end of __CC_EGLVIEW_ANDROID_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.
****************************************************************************/

NS_CC_BEGIN;

#include "CCCommon.h"
#include "jni/SystemInfoJni.h"

// record the resource path
static string s_strResourcePath = "";

/*
 * This function is implemented for jni to set apk path.
 */
void CCFileUtils::setResourcePath(const char* pszResourcePath)
{
	CCAssert(pszResourcePath != NULL, "[FileUtils setRelativePath] -- wrong relative path");

	string tmp(pszResourcePath);

	if ((! pszResourcePath) || tmp.find(".apk") == string::npos)
	{
		return;
	}

	s_strResourcePath = pszResourcePath;
}

const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath)
{
	return pszRelativePath;
}

const char* CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile)
{
	std::string relativeFile = pszRelativeFile;
	CCString *pRet = new CCString();
	pRet->autorelease();
	pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1);
	pRet->m_sString += pszFilename;
	return pRet->m_sString.c_str();
}

unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
{
	unsigned char * pData = 0;
	string fullPath(pszFileName);

	if ((! pszFileName) || (! pszMode))
	{
		return 0;
	}

	if (pszFileName[0] != '/')
	{
		// read from apk
		fullPath.insert(0, "assets/");
		pData =  CCFileUtils::getFileDataFromZip(s_strResourcePath.c_str(), fullPath.c_str(), pSize);
	}
	else
	{
		do
		{
			// read rrom other path than user set it
			FILE *fp = fopen(pszFileName, pszMode);
			CC_BREAK_IF(!fp);

			unsigned long size;
			fseek(fp,0,SEEK_END);
			size = ftell(fp);
			fseek(fp,0,SEEK_SET);
			pData = new unsigned char[size];
			size = fread(pData,sizeof(unsigned char), size,fp);
			fclose(fp);

			if (pSize)
			{
				*pSize = size;
			}
		} while (0);
	}

    if (! pData && getIsPopupNotify())
    {
        std::string title = "Notification";
        std::string msg = "Get data from file(";
        msg.append(fullPath.c_str()).append(") failed!");
        CCMessageBox(msg.c_str(), title.c_str());
    }

    return pData;
}

void CCFileUtils::setResource(const char* pszZipFileName)
{
    CCAssert(0, "Have not implement!");
}

int CCFileUtils::ccLoadFileIntoMemory(const char *filename, unsigned char **out)
{
    CCAssert(0, "Have not implement!");
    return 0;
}

string CCFileUtils::getWriteablePath()
{
	// the path is: /data/data/ + package name
	string dir("/data/data/");
	const char *tmp = getPackageNameJNI();

	if (tmp)
	{
		dir.append(tmp).append("/");

		return dir;
	}
	else
	{
		return "";
	}
}

NS_CC_END;


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.
****************************************************************************/

//#define COCOS2D_DEBUG 1

#include <android/log.h>
#include <string.h>
#include <jni.h>

#include "CCPlatformMacros.h"
#include "CCImage.h"
#include "jni/JniHelper.h"

NS_CC_BEGIN;

class BitmapDC
{
public:
    BitmapDC()
	: m_pData(NULL)
	, m_nWidth(0)
	, m_nHeight(0)
    {
    }

    ~BitmapDC(void)
    {
		if (m_pData)
		{
			delete [] m_pData;
		}
    }

	bool getBitmapFromJava(const char *text, int nWidth, int nHeight, CCImage::ETextAlign eAlignMask, const char * pFontName, float fontSize)
	{
		JniMethodInfo methodInfo;
		if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxBitmap", "createTextBitmap",
			"(Ljava/lang/String;Ljava/lang/String;IIII)V"))
		{
			CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__);
			return false;
		}

		/**create bitmap
		 * this method call Cococs2dx.createBitmap()(java code) to create the bitmap, the java code
		 * will call Java_org_cocos2dx_lib_Cocos2dxBitmap_nativeInitBitmapDC() to init the width, height
		 * and data.
		 * use this appoach to decrease the jni call number
		*/
		jstring jstrText = methodInfo.env->NewStringUTF(text);
		jstring jstrFont = methodInfo.env->NewStringUTF(pFontName);

		methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, jstrText,
			jstrFont, (int)fontSize, eAlignMask, nWidth, nHeight);

		methodInfo.env->DeleteLocalRef(jstrText);
		methodInfo.env->DeleteLocalRef(jstrFont);
		methodInfo.env->DeleteLocalRef(methodInfo.classID);

		return true;
	}

	// ARGB -> RGBA
	unsigned int swapAlpha(unsigned int value)
	{
		return ((value << 8 & 0xffffff00) | (value >> 24 & 0x000000ff));
	}

public:
	int m_nWidth;
	int m_nHeight;
	unsigned char *m_pData;
	JNIEnv *env;
};

static BitmapDC& sharedBitmapDC()
{
    static BitmapDC s_BmpDC;
    return s_BmpDC;
}

bool CCImage::initWithString(
                               const char *    pText,
                               int             nWidth/* = 0*/,
                               int             nHeight/* = 0*/,
                               ETextAlign      eAlignMask/* = kAlignCenter*/,
                               const char *    pFontName/* = nil*/,
                               int             nSize/* = 0*/)
{
    bool bRet = false;

    do
    {
        CC_BREAK_IF(! pText);

        BitmapDC &dc = sharedBitmapDC();

		CC_BREAK_IF(! dc.getBitmapFromJava(pText, nWidth, nHeight, eAlignMask, pFontName, nSize));

		// assign the dc.m_pData to m_pData in order to save time
		m_pData = dc.m_pData;
		CC_BREAK_IF(! m_pData);

		m_nWidth    = (short)dc.m_nWidth;
		m_nHeight   = (short)dc.m_nHeight;
		m_bHasAlpha = true;
		m_bPreMulti = true;
		m_nBitsPerComponent = 8;

		bRet = true;
    } while (0);

    return bRet;
}

NS_CC_END;

// this method is called by Cocos2dxBitmap
extern "C"
{
	/**
	* this method is called by java code to init width, height and pixels data
	*/
	void Java_org_cocos2dx_lib_Cocos2dxBitmap_nativeInitBitmapDC(JNIEnv*  env, jobject thiz, int width, int height, jbyteArray pixels)
	{
		int size = width * height * 4;
		cocos2d::sharedBitmapDC().m_nWidth = width;
		cocos2d::sharedBitmapDC().m_nHeight = height;
		cocos2d::sharedBitmapDC().m_pData = new unsigned char[size];
		env->GetByteArrayRegion(pixels, 0, size, (jbyte*)cocos2d::sharedBitmapDC().m_pData);

		// swap data
		unsigned int *tempPtr = (unsigned int*)cocos2d::sharedBitmapDC().m_pData;
		unsigned int tempdata = 0;
		for (int i = 0; i < height; ++i)
		{
			for (int j = 0; j < width; ++j)
			{
				tempdata = *tempPtr;
				*tempPtr++ = cocos2d::sharedBitmapDC().swapAlpha(tempdata);
			}
		}
	}
};