cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/)
{
    std::string fileExtension = cocos2d::FileUtils::getInstance()->getFileExtension(fileName);
    if (fileExtension == ".json")
    {
        _node = nullptr;
        rapidjson::Document jsonDict;
        do {
            CC_BREAK_IF(!readJson(fileName, jsonDict));
            _node = createObject(jsonDict, nullptr, attachComponent);
            TriggerMng::getInstance()->parse(jsonDict);
        } while (0);
        
        return _node;
    }
    else if(fileExtension == ".csb")
    {
        do {
            std::string binaryFilePath = FileUtils::getInstance()->fullPathForFilename(fileName);
            auto fileData = FileUtils::getInstance()->getDataFromFile(binaryFilePath);
            auto fileDataBytes = fileData.getBytes();
            CC_BREAK_IF(fileData.isNull());
            CocoLoader tCocoLoader;
            if (tCocoLoader.ReadCocoBinBuff((char*)fileDataBytes))
            {
                stExpCocoNode *tpRootCocoNode = tCocoLoader.GetRootCocoNode();
                rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
                if (rapidjson::kObjectType  == tType)
                {
                    stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray(&tCocoLoader);
                    CC_BREAK_IF(tpRootCocoNode->GetChildNum() == 0);
                    _node = Node::create();
                    int  nCount = 0;
                    std::vector<Component*> _vecComs;
                    ComRender *pRender = nullptr;
                    std::string key = tpChildArray[15].GetName(&tCocoLoader);
                    if (key == "components")
                    {
                        nCount = tpChildArray[15].GetChildNum();
                    }
                    stExpCocoNode *pComponents = tpChildArray[15].GetChildArray(&tCocoLoader);
                    SerData *data = new (std::nothrow) SerData();
                    for (int i = 0; i < nCount; i++)
                    {
                        stExpCocoNode *subDict = pComponents[i].GetChildArray(&tCocoLoader);
                        if (subDict == nullptr)
                        {
                            continue;
                        }
                        std::string key1 = subDict[1].GetName(&tCocoLoader);
                        const char *comName = subDict[1].GetValue(&tCocoLoader);
                        Component *pCom = nullptr;
                        if (key1 == "classname" && comName != nullptr)
                        {
                            pCom = createComponent(comName);
                        }
                        CCLOG("classname = %s", comName);
                        if (pCom != nullptr)
                        {
                            data->_rData = nullptr;
                            data->_cocoNode = subDict;
                            data->_cocoLoader = &tCocoLoader;
                            if (pCom->serialize(data))
                            {
                                ComRender *pTRender = dynamic_cast<ComRender*>(pCom);
                                if (pTRender != nullptr)
                                {
                                    pRender = pTRender;
                                }
                                else
                                {
                                    _vecComs.push_back(pCom);
                                }
                            }
                            else
                            {
                                CC_SAFE_RELEASE_NULL(pCom);
                            }
                        }
                        if(_fnSelector != nullptr)
                        {
                            _fnSelector(pCom, (void*)(data));
                        }
                    }
                    
                    setPropertyFromJsonDict(&tCocoLoader, tpRootCocoNode, _node);
                    for (std::vector<Component*>::iterator iter = _vecComs.begin(); iter != _vecComs.end(); ++iter)
                    {
                        _node->addComponent(*iter);
                    }
                    
                    stExpCocoNode *pGameObjects = tpChildArray[11].GetChildArray(&tCocoLoader);
                    int length = tpChildArray[11].GetChildNum();
                    for (int i = 0; i < length; ++i)
                    {
                        createObject(&tCocoLoader, &pGameObjects[i], _node, attachComponent);
                    }
                    TriggerMng::getInstance()->parse(&tCocoLoader, tpChildArray);
                }
                
            }
        }while (0);
        return _node;
    }
    else
    {
        log("read file [%s] error!\n", fileName.c_str());
    }
    return nullptr;
}
/* get buffer as Image */
Image* RenderTexture::newImage(bool fliimage)
{
    CCASSERT(_pixelFormat == Texture2D::PixelFormat::RGBA8888, "only RGBA8888 can be saved as image");

    if (nullptr == _texture)
    {
        return nullptr;
    }

    const Size& s = _texture->getContentSizeInPixels();

    // to get the image size to save
    //        if the saving image domain exceeds the buffer texture domain,
    //        it should be cut
    int savedBufferWidth = (int)s.width;
    int savedBufferHeight = (int)s.height;

    GLubyte *buffer = nullptr;
    GLubyte *tempData = nullptr;
    Image *image = new (std::nothrow) Image();

    do
    {
        CC_BREAK_IF(! (buffer = new (std::nothrow) GLubyte[savedBufferWidth * savedBufferHeight * 4]));

        if(! (tempData = new (std::nothrow) GLubyte[savedBufferWidth * savedBufferHeight * 4]))
        {
            delete[] buffer;
            buffer = nullptr;
            break;
        }

        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
        glBindFramebuffer(GL_FRAMEBUFFER, _FBO);

        // TODO: move this to configuration, so we don't check it every time
        /*  Certain Qualcomm Andreno gpu's will retain data in memory after a frame buffer switch which corrupts the render to the texture. The solution is to clear the frame buffer before rendering to the texture. However, calling glClear has the unintended result of clearing the current texture. Create a temporary texture to overcome this. At the end of RenderTexture::begin(), switch the attached texture to the second one, call glClear, and then switch back to the original texture. This solution is unnecessary for other devices as they don't have the same issue with switching frame buffers.
         */
        if (Configuration::getInstance()->checkForGLExtension("GL_QCOM"))
        {
            // -- bind a temporary texture so we can clear the render buffer without losing our texture
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _textureCopy->getName(), 0);
            CHECK_GL_ERROR_DEBUG();
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);
        }
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glReadPixels(0,0,savedBufferWidth, savedBufferHeight,GL_RGBA,GL_UNSIGNED_BYTE, tempData);
        glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);

        if ( fliimage ) // -- flip is only required when saving image to file
        {
            // to get the actual texture data
            // #640 the image read from rendertexture is dirty
            for (int i = 0; i < savedBufferHeight; ++i)
            {
                memcpy(&buffer[i * savedBufferWidth * 4],
                       &tempData[(savedBufferHeight - i - 1) * savedBufferWidth * 4],
                       savedBufferWidth * 4);
            }

            image->initWithRawData(buffer, savedBufferWidth * savedBufferHeight * 4, savedBufferWidth, savedBufferHeight, 8);
        }
        else
        {
            image->initWithRawData(tempData, savedBufferWidth * savedBufferHeight * 4, savedBufferWidth, savedBufferHeight, 8);
        }
        
    } while (0);

    CC_SAFE_DELETE_ARRAY(buffer);
    CC_SAFE_DELETE_ARRAY(tempData);

    return image;
}
Beispiel #3
0
bool CCEGLView::Create()
{
    bool bRet = false;
    do
    {
        CC_BREAK_IF(m_hWnd);

        HINSTANCE hInstance = GetModuleHandle( NULL );
        WNDCLASS  wc;        // Windows Class Structure

		// set the wnd icon
		HICON hIcon = LoadIcon( hInstance, MAKEINTRESOURCE(MAKEFOURCC('c', 'c', '2', 'd')) );
		if (!hIcon)
			hIcon = LoadIcon( NULL, IDI_WINLOGO );

        // Redraw On Size, And Own DC For Window.
        wc.style          = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
        wc.lpfnWndProc    = _WindowProc;                    // WndProc Handles Messages
        wc.cbClsExtra     = 0;                              // No Extra Window Data
        wc.cbWndExtra     = 0;                                // No Extra Window Data
        wc.hInstance      = hInstance;                        // Set The Instance
        wc.hIcon          = hIcon;							// Load The Default Icon
        wc.hCursor        = LoadCursor( NULL, IDC_ARROW );    // Load The Arrow Pointer
        wc.hbrBackground  = NULL;                           // No Background Required For GL
        wc.lpszMenuName   = m_menu;                         //
        wc.lpszClassName  = kWindowClassName;               // Set The Class Name

        CC_BREAK_IF(! RegisterClass(&wc) && 1410 != GetLastError());

        // center window position
        RECT rcDesktop;
        GetWindowRect(GetDesktopWindow(), &rcDesktop);

        WCHAR wszBuf[50] = {0};
        MultiByteToWideChar(CP_UTF8, 0, m_szViewName, -1, wszBuf, sizeof(wszBuf));

        // create window
        m_hWnd = CreateWindowEx(
            WS_EX_APPWINDOW | WS_EX_WINDOWEDGE,    // Extended Style For The Window
            kWindowClassName,                                    // Class Name
            wszBuf,                                                // Window Title
            WS_CAPTION | WS_POPUPWINDOW | WS_MINIMIZEBOX,        // Defined Window Style
            0, 0,                                                // Window Position
            //TODO: Initializing width with a large value to avoid getting a wrong client area by 'GetClientRect' function.
            1000,                                               // Window Width
            1000,                                               // Window Height
            NULL,                                                // No Parent Window
            NULL,                                                // No Menu
            hInstance,                                            // Instance
            NULL );

        CC_BREAK_IF(! m_hWnd);

        bRet = initGL();
		if(!bRet) destroyGL();
        CC_BREAK_IF(!bRet);

        s_pMainWindow = this;
        bRet = true;
    } while (0);

#if(_MSC_VER >= 1600)
    m_bSupportTouch = CheckTouchSupport();
    if(m_bSupportTouch)
	{
	    m_bSupportTouch = (s_pfRegisterTouchWindowFunction(m_hWnd, 0) != 0);
    }
#endif /* #if(_MSC_VER >= 1600) */

    return bRet;
}
Beispiel #4
0
bool S4HeZuo::setUpSubClass()
{
	bool bRet = false;
	do
	{
        float firstStrFontSize = ScriptParser::getFontSizeFromPlist(plistDic,"firstTitle");
        CCLabelTTF *firstTitleLabel = CCLabelTTF::create(ScriptParser::getStringFromPlist(plistDic,"firstTitle"), s1FontName_macro, firstStrFontSize);
        firstTitleLabel->setColor(ccc3(193.0,159.0,113.0));
        firstTitleLabel->setPosition(ScriptParser::getPositionFromPlist(plistDic,"firstTitle"));
        this->addChild(firstTitleLabel,zNum+1);
        
        CCSprite * S1PSubBottomSprite = CCSprite::create("S1PSubBottom.png");
        S1PSubBottomSprite->setPosition( ccp(origin.x+visibleSize.width/2,firstTitleLabel->getPosition().y-firstTitleLabel->getContentSize().height/2-10));
        this->addChild(S1PSubBottomSprite,zNum);
        
        
        map<string, string> naviGroupStrMap =  ScriptParser::getGroupStringFromPlist(plistDic,"naviTitle");
        float naviFontSize = ScriptParser::getFontSizeFromPlist(plistDic,"naviTitle");
        CCPoint naviStrPosition = ScriptParser::getPositionFromPlist(plistDic,"naviTitle");
        
        for (int i=0; i<(int)naviGroupStrMap.size(); i++)
        {
            const char * labelStr = naviGroupStrMap[PersonalApi::convertIntToString(i+1)].c_str();
            
            CCLabelTTF *pLabel = CCLabelTTF::create(labelStr, s1FontName_macro, naviFontSize);
            pLabel->setPosition(ccp(naviStrPosition.x+(pLabel->getContentSize().width+20)*i,naviStrPosition.y));
            pLabel->setColor(ccc3(128.0,128.0,128.0));
            this->addChild(pLabel,zNum+1);
            
            if ( AppDelegate::S4SelectNavi == i+1)
            {
                pLabel->setColor(ccc3(255.0,255.0,255.0));
                CCSprite * selectFrameSprite = CCSprite::create("PSubNavBackground.png");
                selectFrameSprite->setScaleX(pLabel->getContentSize().width/selectFrameSprite->getContentSize().width);
                selectFrameSprite ->setPosition(pLabel->getPosition());
                this->addChild(selectFrameSprite,zNum);
            }
            
            CCSprite * sprite1 = CCSprite::create();
			CCSprite * sprite2 = CCSprite::create();
            
			CCMenuItemSprite *aItem = CCMenuItemSprite::create(
                                                               sprite1,
                                                               sprite2,
                                                               this,
                                                               menu_selector(S4HeZuo::menuCallback));
			CC_BREAK_IF(! aItem);
			aItem->setPosition(pLabel->getPosition());
            aItem->setContentSize(pLabel->getContentSize());
            aItem->setTag(btnTag+i+1);
			_menu ->addChild(aItem,zNum);
            
        }
        
        CC_BREAK_IF(! setUpSubClass2());
        
		bRet = true;
	} while (0);
    
	return bRet;
}
Beispiel #5
0
bool GameSceneLayer::init(){
	bool bRet = false;
	do{
		CC_BREAK_IF(!CCLayer::init());
		setKeypadEnabled(true);

		//CCLOG("init1");
		//创建物理世界
		b2Vec2 gravity;
		gravity.Set(0.0f,-10.0f);
		m_pMyworld = new b2World(gravity);
		m_pMyworld->SetAllowSleeping(true);

		m_pMyContactListener = new MyContactListener();
		m_pMyworld->SetContactListener(m_pMyContactListener);

		//m_pDebugDraw = new GLESDebugDraw( PT_RATIO );
		//m_pMyworld->SetDebugDraw(m_pDebugDraw);
		//uint32 flags = 0;
		//flags += b2Draw::e_shapeBit;
		//flags += b2Draw::e_jointBit;
		//flags += b2Draw::e_aabbBit;
		//flags += b2Draw::e_pairBit;
		//flags += b2Draw::e_centerOfMassBit;
		//m_pDebugDraw->SetFlags(flags);

		//创建一个地面
		//b2BodyDef groundboxDef;
		////groundboxDef.

		//b2Body *groundBody = m_pMyworld->CreateBody(&groundboxDef);
	
		//b2EdgeShape groundbox;
		////groundbox.m_type
		//groundbox.Set(b2Vec2(0,220/32),b2Vec2(640.0f/32,220/32));
		//groundBody->CreateFixture(&groundbox,0);

		//groundbox.Set(b2Vec2(0,0/32),b2Vec2(0,480.0f/32));
		//groundBody->CreateFixture(&groundbox,0);

		//groundbox.Set(b2Vec2(640.0f/32,0/32),b2Vec2(640.0f/32,480.0f/32));
		//groundBody->CreateFixture(&groundbox,0);

		//groundbox.Set(b2Vec2(0,480.0f/32),b2Vec2(640.0f/32,480.0f/32));
		//groundBody->CreateFixture(&groundbox,0);

		//创建几个动态刚体

		//for (int i = 0; i < 4; i++){

		//	CCSprite *sprite = CCSprite::create("image 277.png");
		//	sprite->setPosition(ccp(200+100*i,200));
		//	addChild(sprite);
		//	addBoxbodyFromSprite(sprite);
		//	//b2BodyDef bodydef;
		//	//bodydef.type = b2_dynamicBody;
		//	//bodydef.position.Set(200/32+100/32*i,200/32);

		//	//b2Body *body = m_pMyworld->CreateBody(&bodydef);

		//	//b2PolygonShape dynamicbox;
		//	//dynamicbox.SetAsBox(0.5f,0.5f);

		//	//b2FixtureDef fixturedef;
		//	//fixturedef.shape = &dynamicbox;
		//	//fixturedef.density = 1.0f;
		//	//fixturedef.friction = 0.3f;
		//	//fixturedef.restitution = 0.5f;
		//	//body->CreateFixture(&fixturedef);
		//}

		//init 
		CCSprite* bg;
		if (Setting::g_icurrentGate < 10)
		{
			 bg = CCSprite::create("gamebg_1.png");
		}else
		{
		  bg = CCSprite::create("gamebg_2.png");
		}
		bg->setPosition(ccp(Setting::g_ResolusionWidth/2,Setting::g_ResolusionHeight/2));
		addChild(bg,-1);

		m_bDrawlineFlag = false;
		m_LineEndpos = m_LineStartpos = ccp(105,155);

		m_iResuduoMonsterNum = 0;
		//CCLOG("init2");
		initTiledMap();


		//添加一个炮台
		CCSprite*cannonSprite = CCSprite::createWithSpriteFrameName("cannon.png");
		addChild(cannonSprite,1);
		cannonSprite->setPosition(ccp(105,155));
		cannonSprite->setTag(m_iCannonSpriteTag);

		CCSprite*batterySprite = CCSprite::createWithSpriteFrameName("battery.png");
		addChild(batterySprite,1);
		batterySprite->setPosition(ccp(100,140));
		batterySprite->setTag(m_iBatterySpriteTag);

		CCAnimation *pCannonAnimation = CCAnimation::create();
		CCSpriteFrameCache *framecache = CCSpriteFrameCache::sharedSpriteFrameCache();
		for(int i = 0 ; i < 5 ; i++){
			pCannonAnimation->addSpriteFrame(framecache->spriteFrameByName(CCString::createWithFormat("cannon%d.png",i+1)->getCString()));
		}
		pCannonAnimation->setDelayPerUnit(0.08f);
		pCannonAnimation->setRestoreOriginalFrame(true);
		m_pCannonAnimate = CCAnimate::create(pCannonAnimation);
		m_pCannonAnimate->retain();
		m_pCannonAnimate->setTag(m_iCannonAnimateTag);

		CCAnimation *pBatteryAnimation = CCAnimation::create();
		for (int i = 0 ; i < 3 ; i++)	{
			pBatteryAnimation->addSpriteFrame(framecache->spriteFrameByName(CCString::createWithFormat("battery%d.png",i+1)->getCString()));
		}
		pBatteryAnimation->setDelayPerUnit(0.08f);
		pBatteryAnimation->setRestoreOriginalFrame(true);
		m_pBatteryAnimate = CCAnimate::create(pBatteryAnimation);
		m_pBatteryAnimate->retain();


		CCMenuItem* menuItem = CCMenuItemImage::create("button/btn_pause.png","button/btn_pause.png",this,menu_selector(GameSceneLayer::onPause));
		menuItem->setPosition(ccp(60,460));
		menuItem->setScale(0.5f,0.5f);
		CCMenu* menu = CCMenu::create(menuItem,NULL);
		menu->setPosition(ccp(0,0));
        menu->setAnchorPoint(ccp(0,0));
		this->addChild(menu,10);



		schedule(schedule_selector(GameSceneLayer::tick));

		bRet = true;

		
	} while (0);
	return bRet;
}
KDbool Image::initWithImageData ( const KDubyte* pData, KDint32 nDataLen )
{
	KDbool	bRet = false;

	do
	{
		CC_BREAK_IF ( !pData || nDataLen <= 0 );

		KDubyte*	pUnpackedData = nullptr;
		KDint		nUnpackedLen = 0;

		// detecgt and unzip the compress file
		if ( ZipUtils::isCCZBuffer ( pData, nDataLen ) )
		{
			nUnpackedLen = ZipUtils::inflateCCZBuffer ( pData, nDataLen, &pUnpackedData );
		}
		else if ( ZipUtils::isGZipBuffer ( pData, nDataLen ) )
		{
			nUnpackedLen = ZipUtils::inflateMemory ( const_cast<KDubyte*> ( pData ), nDataLen, &pUnpackedData );
		}
		else
		{
			pUnpackedData = const_cast<KDubyte*> ( pData );
			nUnpackedLen = nDataLen;
		}

		KDFile*		pFile   = kdFmemopen ( pUnpackedData, nUnpackedLen, "rb" );
		KDoff		uOffset = kdFtell ( pFile );
		KDImageATX	pImage  = KD_NULL;

		do 
		{
			Texture2D::PixelFormat  eFormat = Texture2D::getDefaultAlphaPixelFormat ( );
			
			if ( eFormat == Texture2D::PixelFormat::AUTO )
			{			
				pImage = kdGetImageInfoFromStreamATX ( pFile );
				CC_BREAK_IF ( !pImage );

				KDint  nFormat = kdGetImageIntATX ( pImage, KD_IMAGE_FORMAT_ATX );
				KDint  nBpp    = kdGetImageIntATX ( pImage, KD_IMAGE_BITSPERPIXEL_ATX );
				KDint  nAlpha  = kdGetImageIntATX ( pImage, KD_IMAGE_ALPHA_ATX );
				KDint  nType   = kdGetImageIntATX ( pImage, KD_IMAGE_TYPE );

				m_eFileType = (Format) nType;
		
				kdFreeImageATX ( pImage );
				kdFseek ( pFile, uOffset, KD_SEEK_SET );

				switch ( nFormat )
				{
					case KD_IMAGE_FORMAT_COMPRESSED_ATX :	
						if ( ( nType == KD_IMAGE_TYPE_PVR   && !Configuration::getInstance ( )->supportsPVRTC ( ) ) ||
							 ( nType == KD_IMAGE_TYPE_S3TC  && !Configuration::getInstance ( )->supportsS3TC  ( ) ) ||
							 ( nType == KD_IMAGE_TYPE_ATITC && !Configuration::getInstance ( )->supportsATITC ( ) ) ||
							 ( nType == KD_IMAGE_TYPE_ETC   && !Configuration::getInstance ( )->supportsETC   ( ) ) )
						{
							eFormat = Texture2D::PixelFormat::RGBA8888;
						}
						else
						{
							eFormat = Texture2D::PixelFormat::COMPRESSED;
						}
						break;

					case KD_IMAGE_FORMAT_ALPHA8_ATX:
						eFormat = Texture2D::PixelFormat::A8;
						break;

					case KD_IMAGE_FORMAT_LUMINANCE_ATX:
						eFormat = Texture2D::PixelFormat::I8;
						break;

					case KD_IMAGE_FORMAT_LUMALPHA_ATX:
						eFormat = Texture2D::PixelFormat::AI88;
						break;

					case KD_IMAGE_FORMAT_PALETTED_ATX:
						eFormat = Texture2D::PixelFormat::RGB5A1;
						break;

					case KD_IMAGE_FORMAT_RGB_ATX:
						if ( nBpp == 24 || nBpp == 48 )
						{
							eFormat = Texture2D::PixelFormat::RGB888;
						}
						else
						{
							eFormat = Texture2D::PixelFormat::RGB565;
						}						
						break;

					case KD_IMAGE_FORMAT_RGBA_ATX:
						if ( nBpp == 16 )
						{
							eFormat = ( nAlpha == 4 ) ? Texture2D::PixelFormat::RGBA4444 : Texture2D::PixelFormat::RGB5A1;
						}
						else
						{
							eFormat = Texture2D::PixelFormat::RGBA8888;
						}
						break;

					default:
						break; break;
				}
			}
	
			pImage = kdGetImageFromStreamATX ( pFile, (KDint) eFormat, KD_IMAGE_FLAG_PREMULTIPLIED_ALPHA );
			CC_BREAK_IF ( !pImage );
			
			m_eRenderFormat				= (Texture2D::PixelFormat) kdGetImageIntATX ( pImage, KD_IMAGE_FORMAT_ATX );
			m_nWidth					= kdGetImageIntATX ( pImage, KD_IMAGE_WIDTH_ATX );
			m_nHeight					= kdGetImageIntATX ( pImage, KD_IMAGE_HEIGHT_ATX );
			m_bHasPremultipliedAlpha	= kdGetImageIntATX ( pImage, KD_IMAGE_FLAG_PREMULTIPLIED_ALPHA ) ? KD_TRUE : KD_FALSE;
			m_nDataLen					= kdGetImageIntATX ( pImage, KD_IMAGE_DATASIZE_ATX );
			m_nNumberOfMipmaps			= kdGetImageIntATX ( pImage, KD_IMAGE_LEVELS_ATX );
			m_pData						= (KDubyte*) kdGetImagePointerATX ( pImage, KD_IMAGE_POINTER_BUFFER_ATX );
			m_pImageAtx					= pImage;

			for ( KDint i = 0; i < m_nNumberOfMipmaps; i++ )
			{
				m_aMipmaps [ i ].address = m_pData + kdGetImageLevelIntATX ( pImage, KD_IMAGE_BUFFEROFFSET_ATX, i );
				m_aMipmaps [ i ].len     = kdGetImageLevelIntATX ( pImage, KD_IMAGE_DATASIZE_ATX, i );
			}

			bRet = true;

		} while ( 0 );

		if ( pFile )
		{
			kdFclose ( pFile );
		}
	
		if ( pUnpackedData != pData )
		{
			kdFree ( pUnpackedData );
		}

	} while ( 0 );

	return bRet;
}
bool GameSuccessfullyLayer::setUpdateView(){
	bool isRet=false;
	do
	{
		char temp[12];
		// 添加背景图片
		CCSprite* laybg=CCSprite::createWithTexture(CCTextureCache::sharedTextureCache()->textureForKey("stats_bg.png"));
		CC_BREAK_IF(!laybg);
		laybg->setPosition(getWinCenter());
		this->addChild(laybg);
		// 添加当前关卡
		CCLabelAtlas* stage= CCLabelAtlas::create("0","numtips.png",25,31,'0');
		CC_BREAK_IF(!stage);
		int lve=CCUserDefault::sharedUserDefault()->getIntegerForKey("lve",1);
	    sprintf(temp,"%d",lve);
		stage->setString(temp);
		stage->setAnchorPoint(ccp(0,0));
		stage->setPosition(ccp(415,370));
		this->addChild(stage,1);
		CCUserDefault::sharedUserDefault()->setIntegerForKey("lve",lve+1);
        
		// 添加击杀怪物数目
		CCLabelAtlas* killcount= CCLabelAtlas::create("0","numtips.png",25,31,'0');
		CC_BREAK_IF(!killcount);
		int killtemp=CCUserDefault::sharedUserDefault()->getIntegerForKey("killtemp",0);
		sprintf(temp,"%d",killtemp);
		killcount->setString(temp);
		killcount->setAnchorPoint(ccp(0,0));
		killcount->setPosition(ccp(415,320));
		this->addChild(killcount,1);
		CCUserDefault::sharedUserDefault()->setIntegerForKey("killtemp",0);
        
        
		// 显示剩余生命值
		CCLabelAtlas* lifecount= CCLabelAtlas::create("0","numtips.png",25,31,'0');
		CC_BREAK_IF(!lifecount);
		int lifetemp=CCUserDefault::sharedUserDefault()->getIntegerForKey("lifetemp",0);
		sprintf(temp,"%d",lifetemp);
		lifecount->setString(temp);
		lifecount->setAnchorPoint(ccp(0,0));
		lifecount->setPosition(ccp(415,280));
		this->addChild(lifecount,1);
		CCUserDefault::sharedUserDefault()->setIntegerForKey("lifetemp",0);
        
        
        
		// 显示击杀奖励 规定杀死一个怪经历1个金币
		CCLabelAtlas* killbound= CCLabelAtlas::create("0","numtips.png",25,31,'0');
		CC_BREAK_IF(!killbound);
		sprintf(temp,"%d",killtemp);
		killbound->setString(temp);
		killbound->setAnchorPoint(ccp(0,0));
		killbound->setPosition(ccp(440,218));
		this->addChild(killbound,1);
        
		// 显示生命值奖励 一点生命值奖励一个金币
		CCLabelAtlas* lifebound= CCLabelAtlas::create("0","numtips.png",25,31,'0');
		CC_BREAK_IF(!lifebound);
		sprintf(temp,"%d",lifetemp);
		lifebound->setString(temp);
		lifebound->setAnchorPoint(ccp(0,0));
		lifebound->setPosition(ccp(440,170));
		this->addChild(lifebound,1);
        
        
		// 显示关卡奖励 一个过一关奖励5个金币
		CCLabelAtlas* goldbound= CCLabelAtlas::create("0","numtips.png",25,31,'0');
		CC_BREAK_IF(!goldbound);
		sprintf(temp,"%d",lve*5);
		goldbound->setString(temp);
		goldbound->setAnchorPoint(ccp(0,0));
		goldbound->setPosition(ccp(440,132));
		this->addChild(goldbound,1);
        
        
		// 显示显示总奖励金币
		CCLabelAtlas* total= CCLabelAtlas::create("0","numtips.png",25,31,'0');
		CC_BREAK_IF(!total);
		int totalnum=lve*5+lifetemp+killtemp;
		sprintf(temp,"%d",totalnum);
		total->setString(temp);
		total->setAnchorPoint(ccp(0,0));
		total->setPosition(ccp(415,80));
		this->addChild(total,1);
        
		// 加上总金币
		int goldnum=CCUserDefault::sharedUserDefault()->getIntegerForKey("goldNum",0);
		CCUserDefault::sharedUserDefault()->setIntegerForKey("goldNum",totalnum+goldnum);
        
		// 创建当前提示信息
        
		CCSprite* tip=CCSprite::createWithTexture(CCTextureCache::sharedTextureCache()->textureForKey("statstip.png"));
		CC_BREAK_IF(!tip);
		tip->setPosition(ccp(this->getContentSize().width/2,30));
		this->addChild(tip,1);
		tip->runAction(CCRepeatForever::create(CCBlink::create(1,1)));
		
        
        isRet=true;
	} while (0);
	return isRet;
}
Beispiel #8
0
bool GameScene::init(){
	bool bRet = false;
	do{
		CC_BREAK_IF(!CCLayer::init());
		setTouchEnabled(true);

		initBgItems(GameData::getLevel());

		//scrollBg1 = CCSprite::createWithTexture(scrollBg->getTexture());

		overText = CCLabelTTF::create("Game OVer!!!\nTouch screen to replay,Let's go","黑体",30);
		overText->setColor(ccc3(255,0,0));
		overText->setPosition(ccp(425,240));
		overText->setVisible(false);

		//CC_BREAK_IF(!scrollBg1);

		addChild(overText,1);
		//addChild(scrollBg1);
		//scrollBg1->setAnchorPoint(ccp(0,0));

		//scrollBg1->setPosition(ccp(scrollBg->getContentSize().width,0));
		//初始化地图
		map = new Map(1,this);
		//生成主角
		hero = new Role(this);

		CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("game.plist","game.png");
		CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("prop_effect.plist","prop_effect.png");
		initProps(200);

		CCSprite* scorePeach = CCSprite::createWithSpriteFrameName("score_peach.png");
		SETANCHPOS(scorePeach,600,420,0,0);
		addChild(scorePeach,10);


		CCSprite* distance = CCSprite::createWithSpriteFrameName("distance.png");
		SETANCHPOS(distance,0,430,0,0);
		addChild(distance,10);

		CCSprite* best = CCSprite::createWithSpriteFrameName("best.png");
		SETANCHPOS(best,20,390,0,0);
		addChild(best,10);

		scoreValue = CCLabelAtlas::create("0","num/num_green.png",28,40,'0');
		SETANCHPOS(scoreValue,680,420,0,0);
		addChild(scoreValue,10);

		distanceValue = CCLabelAtlas::create("0","num/num_yellow.png",28,40,'0');
		SETANCHPOS(distanceValue,170,430,0,0);
		addChild(distanceValue,10);

		char b[20];
		sprintf(b,"%d",GameData::getBest());
		bestValue = CCLabelAtlas::create(b,"num/num_red.png",28,40,'0');
		SETANCHPOS(bestValue,140,390,0,0);
		addChild(bestValue,10);

		progressBg = CCSprite::createWithSpriteFrameName("progress.png");
		SETANCHPOS(progressBg,200,0,0,0);
		addChild(progressBg,14);

		progressLeaf = CCSprite::createWithSpriteFrameName("thumb_leaf.png");
		SETANCHPOS(progressLeaf,200,0,0,0);
		addChild(progressLeaf,14);

		CCMenu* menu = CCMenu::create();
		SETANCHPOS(menu,20,0,0,0);
		menu->setTag(99);
		addChild(menu,12);

		CCMenuItemSprite* pause = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("pause.png"),
			CCSprite::createWithSpriteFrameName("pause.png"),this,menu_selector(GameScene::btnCallback));
		SETANCHPOS(pause,0,0,0,0);
		pause->setTag(1);
		menu->addChild(pause);


		schedule(schedule_selector(GameScene::bgMove));
		bRet = true;
	}while(0);
	return bRet;
}
bool CCComRender::serialize(void* r)
{
    bool bRet = false;
    do 
    {
        CC_BREAK_IF(r == NULL);
		SerData *pSerData = (SerData *)(r);
        const rapidjson::Value *v = pSerData->prData;
		stExpCocoNode *pCocoNode = pSerData->pCocoNode;
		CocoLoader *pCocoLoader = pSerData->pCocoLoader;
		const char *pClassName = NULL;
		const char *pComName = NULL;
		const char *pFile = NULL;
		const char *pPlist = NULL;
		std::string strFilePath;
		std::string strPlistPath;
		int nResType = 0;
		if (v != NULL)
		{
			pClassName = DICTOOL->getStringValue_json(*v, "classname");
			CC_BREAK_IF(pClassName == NULL);
			pComName = DICTOOL->getStringValue_json(*v, "name");
			const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
			CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
			pFile = DICTOOL->getStringValue_json(fileData, "path");
			pPlist = DICTOOL->getStringValue_json(fileData, "plistFile");
			CC_BREAK_IF(pFile == NULL && pPlist == NULL);
			nResType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
		}
		else if(pCocoNode != NULL)
		{
			pClassName = pCocoNode[1].GetValue(pCocoLoader);
			CC_BREAK_IF(pClassName == NULL);
			pComName = pCocoNode[2].GetValue(pCocoLoader);
			stExpCocoNode *pfileData = pCocoNode[4].GetChildArray(pCocoLoader);
			CC_BREAK_IF(!pfileData);
			pFile = pfileData[0].GetValue(pCocoLoader); 
			pPlist = pfileData[1].GetValue(pCocoLoader); 
			CC_BREAK_IF(pFile == NULL && pPlist == NULL);
			nResType = atoi(pfileData[2].GetValue(pCocoLoader));
		}  
		if (pComName != NULL)
		{
			setName(pComName);
		}
		else
		{
			setName(pClassName);
		}

		if (pFile != NULL)
		{
			strFilePath.assign(cocos2d::CCFileUtils::sharedFileUtils()->fullPathForFilename(pFile));
		}
		if (pPlist != NULL)
		{
			strPlistPath.assign(cocos2d::CCFileUtils::sharedFileUtils()->fullPathForFilename(pPlist));
		}
		if (nResType == 0)
		{
			if (strcmp(pClassName, "CCSprite") == 0 && (strFilePath.find(".png") != strFilePath.npos || strFilePath.find(".pvr.ccz") != strFilePath.npos))
			{
				m_pRender = CCSprite::create(strFilePath.c_str());
				m_pRender->retain();

                bRet = true;
			}
			else if(strcmp(pClassName, "CCTMXTiledMap") == 0 && strFilePath.find(".tmx") != strFilePath.npos)
			{
				m_pRender = CCTMXTiledMap::create(strFilePath.c_str());
				m_pRender->retain();

                bRet = true;
			}
			else if(strcmp(pClassName, "CCParticleSystemQuad") == 0 && strFilePath.find(".plist") != strFilePath.npos)
			{
				m_pRender = CCParticleSystemQuad::create(strFilePath.c_str());
				m_pRender->setPosition(ccp(0.0f, 0.0f));
				m_pRender->retain();

                bRet = true;
			}
			else if(strcmp(pClassName, "CCArmature") == 0)
			{
				std::string file_extension = strFilePath;
				size_t pos = strFilePath.find_last_of('.');
				if (pos != std::string::npos)
				{
					file_extension = strFilePath.substr(pos, strFilePath.length());
					std::transform(file_extension.begin(),file_extension.end(), file_extension.begin(), (int(*)(int))toupper);
				}
				if (file_extension == ".JSON" || file_extension == ".EXPORTJSON")
				{
					rapidjson::Document doc;
					if(!readJson(strFilePath.c_str(), doc))
					{
						CCLog("read json file[%s] error!\n", strFilePath.c_str());
						continue;
					}
					const rapidjson::Value &subData = DICTOOL->getDictionaryFromArray_json(doc, "armature_data", 0);
					const char *name = DICTOOL->getStringValue_json(subData, "name");
					CCArmatureDataManager::sharedArmatureDataManager()->addArmatureFileInfo(strFilePath.c_str());
					CCArmature *pAr = CCArmature::create(name);
					m_pRender = pAr;
					m_pRender->retain();
					const char *actionName = NULL;
					if (pCocoNode != NULL)
					{
						actionName = pCocoNode[6].GetValue(pCocoLoader);//DICTOOL->getStringValue_json(*v, "selectedactionname");
					}
					else
					{
						actionName = DICTOOL->getStringValue_json(*v, "selectedactionname");
					}
					if (actionName != NULL && pAr->getAnimation() != NULL)
					{
						pAr->getAnimation()->play(actionName);
					}
                    bRet = true;
				}
				else if (file_extension == ".CSB")
				{
					unsigned long size = 0;
					unsigned char *pBytes = NULL;
					std::string binaryFilePath = CCFileUtils::sharedFileUtils()->fullPathForFilename(strFilePath.c_str());
					pBytes = cocos2d::CCFileUtils::sharedFileUtils()->getFileData(binaryFilePath.c_str(), "rb", &size);
					CC_BREAK_IF(pBytes == NULL || strcmp((char*)pBytes, "") == 0);
					CocoLoader tCocoLoader;
					if (tCocoLoader.ReadCocoBinBuff((char*)pBytes))
					{
						stExpCocoNode *tpRootCocoNode = tCocoLoader.GetRootCocoNode();
						rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
						if (rapidjson::kObjectType  == tType)
						{
                            int count = tpRootCocoNode->GetChildNum();
                            stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray(&tCocoLoader);
                            for (int i = 0; i < count; ++i)
                            {
                                std::string key = tpChildArray[i].GetName(&tCocoLoader);
                                const char *str = tpChildArray[i].GetValue(&tCocoLoader);
                                if (key.compare("armature_data") == 0)
                                {
                                    int length = tpChildArray[i].GetChildNum();
                                    stExpCocoNode *armature_dataArray = tpChildArray[i].GetChildArray(&tCocoLoader);
                                    if (length < 1)
                                    {
                                        continue;
                                    }

                                    length = armature_dataArray[0].GetChildNum();
                                    stExpCocoNode *armature_data = armature_dataArray[0].GetChildArray(&tCocoLoader);
                                    for (int i = 0; i < length; ++i)
                                    {
                                        std::string key = armature_data[i].GetName(&tCocoLoader);
                                        const char *str = armature_data[i].GetValue(&tCocoLoader);
                                        if (key.compare("name") == 0)
                                        {
                                            if (str != NULL)
                                            {
                                                CCArmatureDataManager::sharedArmatureDataManager()->addArmatureFileInfo(strFilePath.c_str());
                                                CCArmature *pAr = CCArmature::create(str);
                                                m_pRender = pAr;
                                                m_pRender->retain();
                                                const char *actionName = NULL;
                                                if (pCocoNode != NULL)
                                                {
                                                    actionName = pCocoNode[6].GetValue(&tCocoLoader);//DICTOOL->getStringValue_json(*v, "selectedactionname");
                                                }
                                                else
                                                {
                                                    actionName = DICTOOL->getStringValue_json(*v, "selectedactionname");
                                                }
                                                if (actionName != NULL && pAr->getAnimation() != NULL)
                                                {
                                                    pAr->getAnimation()->play(actionName);
                                                }
                                                bRet = true;
                                            }
                                        }
                                    }
                                }
                            }
						}
					}
                    else
                    {
                        continue;
                    }
				}
                else
                {
                    continue;
                }
			}
			else if(strcmp(pClassName, "GUIComponent") == 0)
			{
				std::string file_extension = strFilePath;
				size_t pos = strFilePath.find_last_of('.');
				if (pos != std::string::npos)
				{
					file_extension = strFilePath.substr(pos, strFilePath.length());
					std::transform(file_extension.begin(),file_extension.end(), file_extension.begin(), (int(*)(int))toupper);
				}
				if (file_extension == ".JSON" || file_extension == ".EXPORTJSON")
				{
					cocos2d::ui::TouchGroup* tg = cocos2d::ui::TouchGroup::create();
					cocos2d::ui::Widget* widget = cocos2d::extension::GUIReader::shareReader()->widgetFromJsonFile(strFilePath.c_str());
					tg->addWidget(widget);
					m_pRender = tg;
					m_pRender->retain();

                    bRet = true;
				}
				else if (file_extension == ".CSB")
				{
                    cocos2d::ui::TouchGroup* tg = cocos2d::ui::TouchGroup::create();
                    cocos2d::ui::Widget* widget = cocos2d::extension::GUIReader::shareReader()->widgetFromBinaryFile(strFilePath.c_str());
                    tg->addWidget(widget);
                    m_pRender = tg;
                    m_pRender->retain();

                    bRet = true;
				}
			}
			else
			{
				CC_BREAK_IF(true);
			}
		}
		else if (nResType == 1)
		{
			if (strcmp(pClassName, "CCSprite") == 0)
			{
				std::string strPngFile = strPlistPath;
				std::string::size_type pos = strPngFile.find(".plist");
				if (pos  == strPngFile.npos)
				{
					continue;
				}
				strPngFile.replace(pos, strPngFile.length(), ".png");
				CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(strPlistPath.c_str(), strPngFile.c_str());
				m_pRender = CCSprite::createWithSpriteFrameName(strFilePath.c_str());
				m_pRender->retain();

                bRet = true;
			}
			else
			{
				CC_BREAK_IF(true);
			}
		}
		else
		{
			CC_BREAK_IF(true);
		}
    } while (0);

    return bRet;
}
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;
}
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;
}
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;
}
Beispiel #14
0
bool ComAudio::serialize(void* r)
{
    bool ret = false;
    do
    {
        CC_BREAK_IF(r == nullptr);
        SerData *serData = (SerData *)(r);
        const rapidjson::Value *v = serData->_rData;
        stExpCocoNode *cocoNode = serData->_cocoNode;
        CocoLoader *cocoLoader = serData->_cocoLoader;
        const char *className = nullptr;
        const char *comName = nullptr;
        const char *file = nullptr;
        std::string filePath;
        int resType = 0;
        bool loop = false;
        if (v != nullptr)
        {
            className = DICTOOL->getStringValue_json(*v, "classname");
            CC_BREAK_IF(className == nullptr);
            comName = DICTOOL->getStringValue_json(*v, "name");
            const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
            CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
            file = DICTOOL->getStringValue_json(fileData, "path");
            CC_BREAK_IF(file == nullptr);
            resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
            CC_BREAK_IF(resType != 0);
            loop = DICTOOL->getIntValue_json(*v, "loop") != 0? true:false;
        }
        else if (cocoNode != nullptr)
        {
            className = cocoNode[1].GetValue(cocoLoader);
            CC_BREAK_IF(className == nullptr);
            comName = cocoNode[2].GetValue(cocoLoader);
            stExpCocoNode *pfileData = cocoNode[4].GetChildArray(cocoLoader);
            CC_BREAK_IF(!pfileData);
            file = pfileData[0].GetValue(cocoLoader);
            CC_BREAK_IF(file == nullptr);
            resType = atoi(pfileData[2].GetValue(cocoLoader));
            CC_BREAK_IF(resType != 0);
            loop = atoi(cocoNode[5].GetValue(cocoLoader)) != 0? true:false;
            ret = true;
        }
        if (comName != nullptr)
        {
            setName(comName);
        }
        else
        {
            setName(className);
        }
        if (file != nullptr)
        {
            if (strcmp(file, "") == 0)
            {
                continue;
            }
            filePath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(file));
        }
        if (strcmp(className, "CCBackgroundAudio") == 0)
        {
            preloadBackgroundMusic(filePath.c_str());
            setLoop(loop);
            playBackgroundMusic(filePath.c_str(), loop);
        }
        else if(strcmp(className, COMPONENT_NAME.c_str()) == 0)
        {
            preloadEffect(filePath.c_str());
        }
        else
        {
            CC_BREAK_IF(true);
        }
        ret = true;
    }while (0);
    return ret;
}
Beispiel #15
0
bool CARenderImage::initWithWidthAndHeight(int w, int h, CAImage::PixelFormat eFormat, GLuint uDepthStencilFormat)
{
    CCAssert(eFormat != CAImage::PixelFormat_A8, "only RGB and RGBA formats are valid for a render texture");

    bool bRet = false;
    unsigned char *data = NULL;
    do 
    {
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_nOldFBO);

        // textures must be power of two squared
        unsigned int powW = 0;
        unsigned int powH = 0;

        {
            powW = (unsigned int)w;
            powH = (unsigned int)h;
        }

        data = (unsigned char *)malloc((int)(powW * powH * 4));
        CC_BREAK_IF(! data);

        memset(data, 0, (int)(powW * powH * 4));
        m_ePixelFormat = eFormat;
        m_uPixelsWide = powW;
        m_uPixelsHigh = powH;
        
        glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
        glGenTextures(1, &m_uName);
        ccGLBindTexture2D(m_uName);
        
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_uPixelsWide, m_uPixelsHigh, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        
        GLint oldRBO;
        glGetIntegerv(GL_RENDERBUFFER_BINDING, &oldRBO);
        
        // generate FBO
        glGenFramebuffers(1, &m_uFBO);
        glBindFramebuffer(GL_FRAMEBUFFER, m_uFBO);

        // associate Image with FBO
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_uName, 0);

        if (uDepthStencilFormat != 0)
        {
            //create and attach depth buffer
            glGenRenderbuffers(1, &m_uDepthRenderBufffer);
            glBindRenderbuffer(GL_RENDERBUFFER, m_uDepthRenderBufffer);
            glRenderbufferStorage(GL_RENDERBUFFER, uDepthStencilFormat, (GLsizei)powW, (GLsizei)powH);
            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_uDepthRenderBufffer);

            // if depth format is the one with stencil part, bind same render buffer as stencil attachment
            if (uDepthStencilFormat == GL_DEPTH24_STENCIL8)
            {
                glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_uDepthRenderBufffer);
            }
        }
//        // check if it worked (probably worth doing :) )
        CCAssert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Could not attach Image to framebuffer");

        ccGLBindTexture2D( m_uName );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

        CAImageView* imageView = CAImageView::createWithFrame(CCRect(0, 0, m_uPixelsWide, m_uPixelsHigh));
        ccBlendFunc tBlendFunc = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA };
        imageView->setBlendFunc(tBlendFunc);
        this->addSubview(imageView);
        this->setImageView(imageView);
        
        glBindRenderbuffer(GL_RENDERBUFFER, oldRBO);
        glBindFramebuffer(GL_FRAMEBUFFER, m_nOldFBO);
        
        // Diabled by default.
        m_bAutoDraw = false;

        bRet = true;
    } while (0);
    
    CC_SAFE_FREE(data);
    
    return bRet;
}
bool CCParticleSystem::initWithDictionary(CCDictionary<std::string, CCObject*> *dictionary)
{
	bool bRet = false;
	unsigned char *buffer = NULL;
	unsigned char *deflated = NULL;
	CCImage *image = NULL;
	do 
	{
		int maxParticles = atoi(valueForKey("maxParticles", dictionary));
		// self, not super
		if(this->initWithTotalParticles(maxParticles))
		{
			// angle
			m_fAngle = (float)atof(valueForKey("angle", dictionary));
			m_fAngleVar = (float)atof(valueForKey("angleVariance", dictionary));

			// duration
			m_fDuration = (float)atof(valueForKey("duration", dictionary));

			// blend function 
			m_tBlendFunc.src = atoi(valueForKey("blendFuncSource", dictionary));
			m_tBlendFunc.dst = atoi(valueForKey("blendFuncDestination", dictionary));

			// color
			m_tStartColor.r = (float)atof(valueForKey("startColorRed", dictionary));
			m_tStartColor.g = (float)atof(valueForKey("startColorGreen", dictionary));
			m_tStartColor.b = (float)atof(valueForKey("startColorBlue", dictionary));
			m_tStartColor.a = (float)atof(valueForKey("startColorAlpha", dictionary));

			m_tStartColorVar.r = (float)atof(valueForKey("startColorVarianceRed", dictionary));
			m_tStartColorVar.g = (float)atof(valueForKey("startColorVarianceGreen", dictionary));
			m_tStartColorVar.b = (float)atof(valueForKey("startColorVarianceBlue", dictionary));
			m_tStartColorVar.a = (float)atof(valueForKey("startColorVarianceAlpha", dictionary));

			m_tEndColor.r = (float)atof(valueForKey("finishColorRed", dictionary));
			m_tEndColor.g = (float)atof(valueForKey("finishColorGreen", dictionary));
			m_tEndColor.b = (float)atof(valueForKey("finishColorBlue", dictionary));
			m_tEndColor.a = (float)atof(valueForKey("finishColorAlpha", dictionary));

			m_tEndColorVar.r = (float)atof(valueForKey("finishColorVarianceRed", dictionary));
			m_tEndColorVar.g = (float)atof(valueForKey("finishColorVarianceGreen", dictionary));
			m_tEndColorVar.b = (float)atof(valueForKey("finishColorVarianceBlue", dictionary));
			m_tEndColorVar.a = (float)atof(valueForKey("finishColorVarianceAlpha", dictionary));

			// particle size
			m_fStartSize = (float)atof(valueForKey("startParticleSize", dictionary));
			m_fStartSizeVar = (float)atof(valueForKey("startParticleSizeVariance", dictionary));
			m_fEndSize = (float)atof(valueForKey("finishParticleSize", dictionary));
			m_fEndSizeVar = (float)atof(valueForKey("finishParticleSizeVariance", dictionary));

			// position
            float x = (float)atof(valueForKey("sourcePositionx", dictionary));
            float y = (float)atof(valueForKey("sourcePositiony", dictionary));
            this->setPosition( ccp(x,y) );			
            m_tPosVar.x = (float)atof(valueForKey("sourcePositionVariancex", dictionary));
			m_tPosVar.y = (float)atof(valueForKey("sourcePositionVariancey", dictionary));

			// Spinning
			m_fStartSpin = (float)atof(valueForKey("rotationStart", dictionary));
			m_fStartSpinVar = (float)atof(valueForKey("rotationStartVariance", dictionary));
			m_fEndSpin= (float)atof(valueForKey("rotationEnd", dictionary));
			m_fEndSpinVar= (float)atof(valueForKey("rotationEndVariance", dictionary));

			m_nEmitterMode = atoi(valueForKey("emitterType", dictionary));

			// Mode A: Gravity + tangential accel + radial accel
			if( m_nEmitterMode == kCCParticleModeGravity ) 
			{
				// gravity
				modeA.gravity.x = (float)atof(valueForKey("gravityx", dictionary));
				modeA.gravity.y = (float)atof(valueForKey("gravityy", dictionary));

				// speed
				modeA.speed = (float)atof(valueForKey("speed", dictionary));
				modeA.speedVar = (float)atof(valueForKey("speedVariance", dictionary));

                const char * pszTmp = NULL;
				// radial acceleration
                pszTmp = valueForKey("radialAcceleration", dictionary);
                modeA.radialAccel = (pszTmp) ? (float)atof(pszTmp) : 0;

                pszTmp = valueForKey("radialAccelVariance", dictionary);
				modeA.radialAccelVar = (pszTmp) ? (float)atof(pszTmp) : 0;

				// tangential acceleration
                pszTmp = valueForKey("tangentialAcceleration", dictionary);
				modeA.tangentialAccel = (pszTmp) ? (float)atof(pszTmp) : 0;

                pszTmp = valueForKey("tangentialAccelVariance", dictionary);
				modeA.tangentialAccelVar = (pszTmp) ? (float)atof(pszTmp) : 0;
			}

			// or Mode B: radius movement
			else if( m_nEmitterMode == kCCParticleModeRadius ) 
			{
				modeB.startRadius = (float)atof(valueForKey("maxRadius", dictionary));
				modeB.startRadiusVar = (float)atof(valueForKey("maxRadiusVariance", dictionary));
				modeB.endRadius = (float)atof(valueForKey("minRadius", dictionary));
				modeB.endRadiusVar = 0;
				modeB.rotatePerSecond = (float)atof(valueForKey("rotatePerSecond", dictionary));
				modeB.rotatePerSecondVar = (float)atof(valueForKey("rotatePerSecondVariance", dictionary));

			} else {
				CCAssert( false, "Invalid emitterType in config file");
				CC_BREAK_IF(true);
			}

			// life span
			m_fLife = (float)atof(valueForKey("particleLifespan", dictionary));
			m_fLifeVar = (float)atof(valueForKey("particleLifespanVariance", dictionary));

			// emission Rate
			m_fEmissionRate = m_uTotalParticles / m_fLife;

			// texture		
			// Try to get the texture from the cache
			char *textureName = (char *)valueForKey("textureFileName", dictionary);
            std::string fullpath = CCFileUtils::fullPathFromRelativeFile(textureName, m_sPlistFile.c_str());

			CCTexture2D *tex = NULL;

            if (strlen(textureName) > 0)
            {
                // set not pop-up message box when load image failed
                bool bNotify = CCFileUtils::getIsPopupNotify();
                CCFileUtils::setIsPopupNotify(false);
                tex = CCTextureCache::sharedTextureCache()->addImage(fullpath.c_str());

                // reset the value of UIImage notify
                CCFileUtils::setIsPopupNotify(bNotify);
            }

			if (tex)
			{
				this->m_pTexture = tex;
			}
			else
			{						
                char *textureData = (char*)valueForKey("textureImageData", dictionary);
				CCAssert(textureData, "");

				int dataLen = strlen(textureData);
				if(dataLen != 0)
				{
					// if it fails, try to get it from the base64-gzipped data	
					int decodeLen = base64Decode((unsigned char*)textureData, (unsigned int)dataLen, &buffer);
					CCAssert( buffer != NULL, "CCParticleSystem: error decoding textureImageData");
					CC_BREAK_IF(!buffer);

						int deflatedLen = ZipUtils::ccInflateMemory(buffer, decodeLen, &deflated);
						CCAssert( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData");
						CC_BREAK_IF(!deflated);
						
						image = new CCImage();
						bool isOK = image->initWithImageData(deflated, deflatedLen);
						CCAssert(isOK, "CCParticleSystem: error init image with Data");
						CC_BREAK_IF(!isOK);
						
						m_pTexture = CCTextureCache::sharedTextureCache()->addUIImage(image, fullpath.c_str());
				}
			}
			CCAssert( this->m_pTexture != NULL, "CCParticleSystem: error loading the texture");
			
			CC_BREAK_IF(!m_pTexture);
			this->m_pTexture->retain();
			bRet = true;
		}
	} while (0);
	CC_SAFE_DELETE_ARRAY(buffer);
    CC_SAFE_DELETE_ARRAY(deflated);
	CC_SAFE_DELETE(image);
	return bRet;
}
Beispiel #17
0
bool AppDelegate::initInstance() {
	bool bRet = false;
	do {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

		// Initialize OpenGLView instance, that release by CCDirector when application terminate.
		// The HelloWorld is designed as HVGA.
		CCEGLView * pMainWnd = new CCEGLView();
		CC_BREAK_IF(! pMainWnd
				|| ! pMainWnd->Create(TEXT("cocos2d: Hello World"), 480, 320));

#endif  // CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

		// OpenGLView initialized in testsAppDelegate.mm on ios platform, nothing need to do here.

#endif  // CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

		// OpenGLView initialized in HelloWorld/android/jni/helloworld/main.cpp
		// the default setting is to create a fullscreen view
		// if you want to use auto-scale, please enable view->create(320,480) in main.cpp
		// if the resources under '/sdcard" or other writeable path, set it.
		// warning: the audio source should in assets/
		// cocos2d::CCFileUtils::setResourcePath("/sdcard");

#endif  // CC_PLATFORM_ANDROID
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)

		// Initialize OpenGLView instance, that release by CCDirector when application terminate.
		// The HelloWorld is designed as HVGA.
		CCEGLView* pMainWnd = new CCEGLView(this);
		CC_BREAK_IF(! pMainWnd || ! pMainWnd->Create(320,480, WM_WINDOW_ROTATE_MODE_CW));

#ifndef _TRANZDA_VM_  
		// on wophone emulator, we copy resources files to Work7/NEWPLUS/TDA_DATA/Data/ folder instead of zip file
		cocos2d::CCFileUtils::setResource("HelloWorld.zip");
#endif

#endif  // CC_PLATFORM_WOPHONE
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
		// MaxAksenov said it's NOT a very elegant solution. I agree, haha
		CCDirector::sharedDirector()->setDeviceOrientation(kCCDeviceOrientationLandscapeLeft);
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)

		// Initialize OpenGLView instance, that release by CCDirector when application terminate.
		// The HelloWorld is designed as HVGA.
		CCEGLView * pMainWnd = new CCEGLView();
		CC_BREAK_IF(! pMainWnd
				|| ! pMainWnd->Create("cocos2d: Hello World", 480, 320 ,480, 320));

		CCFileUtils::setResourcePath("../Resource/");

#endif  // CC_PLATFORM_LINUX

#if (CC_TARGET_PLATFORM == CC_PLATFORM_BADA)

		CCEGLView * pMainWnd = new CCEGLView();
		CC_BREAK_IF(! pMainWnd|| ! pMainWnd->Create(this, 480, 320));
		pMainWnd->setDeviceOrientation(Osp::Ui::ORIENTATION_LANDSCAPE);
		CCFileUtils::setResourcePath("/Res/");

#endif  // CC_PLATFORM_BADA

#if (CC_TARGET_PLATFORM == CC_PLATFORM_QNX)
		CCEGLView * pMainWnd = new CCEGLView();
		CC_BREAK_IF(! pMainWnd|| ! pMainWnd->Create(480, 320));
		CCFileUtils::setResourcePath("./app/native/Resource");
#endif // CC_PLATFORM_QNX

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WEBOS)
		
				// Initialize OpenGLView instance, that release by CCDirector when application terminate.
				// The HelloWorld is designed as HVGA.
				CCEGLView * pMainWnd = new CCEGLView();
				//Palm Touchpad resolution	
				CC_BREAK_IF(! pMainWnd
						|| ! pMainWnd->Create("cocos2d: Hello World", 1024, 768));
                // Palm Pre 3 resolution
				//CC_BREAK_IF(! pMainWnd
				//		|| ! pMainWnd->Create("cocos2d: Hello World", 480,800));	
				cocos2d::CCFileUtils::setResourcePath("./Res/");
	//			cocos2d::CCFileUtils::fullPathFromRelativePath("");
		
#endif  // CC_PLATFORM_WEBOS


		bRet = true;
	} while (0);
	return bRet;
}
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;
	unsigned char * pImageData = 0;

	do{
		CC_BREAK_IF(! pText);  

		//D2DWraper& wraper = sharedD2DWraper();
		DXTextPainter^ painter = DirectXRender::SharedDXRender()->m_textPainter;
		std::wstring wStrFontName = CCUtf8ToUnicode(pFontName);
		bool isSuccess = painter->SetFont(ref new Platform::String(wStrFontName.c_str()), nSize);
		if (! isSuccess)
        {
            CCLog("Can't found font(%s), use system default", pFontName);
        }

		
		Windows::Foundation::Size size((float)nWidth, (float)nHeight);

		TextAlignment alignmet = TextAlignment::TextAlignmentCenter;
		DWORD dwHoriFlag = eAlignMask & 0x0f;
		//set text alignment
		switch (dwHoriFlag)
		{
		case 1: // left
				alignmet = TextAlignment::TextAlignmentLeft;
			break;
		case 2: // right
			alignmet = TextAlignment::TextAlignmentRight;
			break;
		case 3: // center
			alignmet = TextAlignment::TextAlignmentCenter;
			break;
		}

		Platform::Array<byte>^ pixelData;
		std::wstring wStrText = CCUtf8ToUnicode(pText);
		pixelData = painter->DrawTextToImage(ref new Platform::String(wStrText.c_str()), &size, alignmet);
		if(pixelData == nullptr)
		{
			break;
		}

		pImageData = new unsigned char[pixelData->Length];
		memcpy(pImageData,pixelData->Data,pixelData->Length);

		CC_BREAK_IF(! pImageData);

		m_nWidth    = (short)size.Width;
		m_nHeight   = (short)size.Height;
		m_bHasAlpha = true;
		m_bPreMulti = false;
		m_pData     = pImageData;
		pImageData  = 0;
		m_nBitsPerComponent = 8;

		bRet = true;
	}while(0);

	return bRet;
}
Beispiel #19
0
/*
 * 处理 web 服务器响应 get 请求回应数据
 */
void LoginLayer::handleWSResponseData(const char *szData, const unsigned int dataSize, char* szTag) {
    CCAssert(szData && dataSize > 0 && szTag, "invalid data");
    
    bool isSuccess = false;
    if (!strcmp(szTag, HTTP_REQUEST_LOGIN_TAG)) /*登录请求*/ {
        isSuccess = ProcessData::processLoginResponseFromServer(szData, dataSize);
        if (isSuccess) {
            // 登陆成功,请求玩家武将信息
            NetConnection* pNetConnection = NetConnection::getInstance();
            
            char szPostBuffer[MAX_POSTTO_SERVER_BUFFER_SIZE];
            memset(szPostBuffer, '\0', MAX_POSTTO_SERVER_BUFFER_SIZE);
            
            sprintf(szPostBuffer, "c=hero&a=hero_list&uid=%s", GamePlayer::getInstance()->getUid().c_str());
            char szTag[] = HTTP_REQUEST_GETHERO_TAG;
            pNetConnection->commitPostRequestData(szPostBuffer, szTag);
        }
    } else if (!strcmp(szTag, HTTP_REQUEST_GETHERO_TAG)) /*武将数据*/ {
        NetConnection* pNetConnection = NetConnection::getInstance();
        do {
            CC_BREAK_IF(!ProcessData::processHerosDataFromServer(szData, dataSize));
            // 还有 “未决” 请求
            CC_BREAK_IF(pNetConnection->isPending());
            
            // 武将管理
            HeroManager* pHeroManager = HeroManager::getInstance();
            // 恢复战队位置
            pHeroManager->restoreBattleTeamPosIndex();
            
            if (m_pGameState->hasEndlessFight()) /* 有未完成战斗 */ {
                Battle* pBattle = Battle::getInstance();
                
                // 恢复副本id
                m_pGameState->setCopyId(m_pGameState->getEndlessFightCopyId());
                // 恢复关卡id
                m_pGameState->setLevId(m_pGameState->getEndlessFightLevelId());
                // 恢复战斗波数
                pBattle->setRoundIndex(m_pGameState->getEndlessFightRoundIndex() - 1);
                
                // 往战场添加本方上阵武将
                unsigned int countOfGotoBattleHeros = pHeroManager->getGoIntoBattleHerosOfPlayerCount();
                for (unsigned int index = 0; index < countOfGotoBattleHeros; index++) {
                    HeroOfPlayerItem* pGotoBattleHeroItem = pHeroManager->getGoIntoBattleHeroDataByIndex(index);
                    CCAssert(pGotoBattleHeroItem, "invalid data");
                    unsigned int posIndexInBattle = m_pGameState->getUfTeamPos(pGotoBattleHeroItem->getUniId());
                    CCAssert(posIndexInBattle > 0, "invalid posIndexInBattle");
                    pGotoBattleHeroItem->setPosInBattle(posIndexInBattle);
                    pBattle->appendInBattleHero(pGotoBattleHeroItem);
                } /*for*/
                pHeroManager->saveBattleTeamPosIndex();
                
                // 提交战斗请求
                pBattle->commitPveFightRequest();
            } else {
                pNetConnection->setHandleNetDataDelegate(NULL);
                /* 设置login调用了主场景 */
                m_pGameState->setTagWhoCallMainScene(1);
                CCDirector::sharedDirector()->replaceScene(MainScene::create());
                CCNotificationCenter::sharedNotificationCenter()->postNotification(ON_MESSAGE_SHUTDOWN_LOADING);
            }
        } while (0);
    } else if (!strcmp(szTag, HTTP_REQUEST_FIGHT_PVE_TAG)) /*战斗请求*/{
        NetConnection* pNetConnection = NetConnection::getInstance();
        bool isSuccess = ProcessData::parseBufferFromSvr(szData, dataSize, szTag);
        if (isSuccess) {
            pNetConnection->setHandleNetDataDelegate(NULL);
            CCDirector::sharedDirector()->replaceScene(BattleScene::create());
        }
    }
}
/* get buffer as UIImage */
bool CCRenderTexture::getUIImageFromBuffer(CCImage *pImage, int x, int y, int nWidth, int nHeight)
{
	if (NULL == pImage || NULL == m_pTexture)
	{
		return false;
	}

	const CCSize& s = m_pTexture->getContentSizeInPixels();
	int tx = (int)s.width;
	int ty = (int)s.height;

	if (x < 0 || x >= tx || y < 0 || y >= ty)
	{
		return false;
	}

	if (nWidth < 0 
		|| nHeight < 0
		|| (0 == nWidth && 0 != nHeight)
		|| (0 == nHeight && 0 != nWidth))
	{
		return false;
	}
	
	// to get the image size to save
	//		if the saving image domain exeeds the buffer texture domain,
	//		it should be cut
	int nSavedBufferWidth = nWidth;
	int nSavedBufferHeight = nHeight;
	if (0 == nWidth)
	{
		nSavedBufferWidth = tx;
	}
	if (0 == nHeight)
	{
		nSavedBufferHeight = ty;
	}
	nSavedBufferWidth = x + nSavedBufferWidth > tx ? (tx - x): nSavedBufferWidth;
	nSavedBufferHeight = y + nSavedBufferHeight > ty ? (ty - y): nSavedBufferHeight;

	GLubyte *pBuffer = NULL;
	GLubyte *pTempData = NULL;
	bool bRet = false;

	do
	{
		CCAssert(m_ePixelFormat == kCCTexture2DPixelFormat_RGBA8888, "only RGBA8888 can be saved as image");

		CC_BREAK_IF(! (pBuffer = new GLubyte[nSavedBufferWidth * nSavedBufferHeight * 4]));

		// On some machines, like Samsung i9000, Motorola Defy,
		// the dimension need to be a power of 2
		int nReadBufferWidth = 0;
		int nReadBufferHeight = 0;
		int nMaxTextureSize = 0;
		glGetIntegerv(GL_MAX_TEXTURE_SIZE, &nMaxTextureSize);

		nReadBufferWidth = ccNextPOT(tx);
		nReadBufferHeight = ccNextPOT(ty);

		CC_BREAK_IF(0 == nReadBufferWidth || 0 == nReadBufferHeight);
		CC_BREAK_IF(nReadBufferWidth > nMaxTextureSize || nReadBufferHeight > nMaxTextureSize);

		CC_BREAK_IF(! (pTempData = new GLubyte[nReadBufferWidth * nReadBufferHeight * 4]));

		this->begin();
		glPixelStorei(GL_PACK_ALIGNMENT, 1);
		glReadPixels(0,0,nReadBufferWidth,nReadBufferHeight,GL_RGBA,GL_UNSIGNED_BYTE, pTempData);
		this->end(false);

		// to get the actual texture data 
		// #640 the image read from rendertexture is upseted
		for (int i = 0; i < nSavedBufferHeight; ++i)
		{
			memcpy(&pBuffer[i * nSavedBufferWidth * 4], 
				&pTempData[(y + nSavedBufferHeight - i - 1) * nReadBufferWidth * 4 + x * 4], 
				nSavedBufferWidth * 4);
		}

		bRet = pImage->initWithImageData(pBuffer, nSavedBufferWidth * nSavedBufferHeight * 4, CCImage::kFmtRawData, nSavedBufferWidth, nSavedBufferHeight, 8);
	} while (0);

	CC_SAFE_DELETE_ARRAY(pBuffer);
	CC_SAFE_DELETE_ARRAY(pTempData);

	return bRet;
}
bool CCEGLView::Create(LPCTSTR pTitle, int w, int h)
{
	bool bRet = false;
	do 
	{
		CC_BREAK_IF(m_hWnd);

		HINSTANCE hInstance = GetModuleHandle( NULL );
		WNDCLASS  wc;		// Windows Class Structure

		// Redraw On Size, And Own DC For Window.
		wc.style          = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;  
		wc.lpfnWndProc    = _WindowProc;					// WndProc Handles Messages
		wc.cbClsExtra     = 0;                              // No Extra Window Data
		wc.cbWndExtra     = 0;								// No Extra Window Data
		wc.hInstance      = hInstance;						// Set The Instance
		wc.hIcon          = LoadIcon( NULL, IDI_WINLOGO );	// Load The Default Icon
		wc.hCursor        = LoadCursor( NULL, IDC_ARROW );	// Load The Arrow Pointer
		wc.hbrBackground  = NULL;                           // No Background Required For GL
		wc.lpszMenuName   = NULL;                           // We Don't Want A Menu
		wc.lpszClassName  = kWindowClassName;               // Set The Class Name

		CC_BREAK_IF(! RegisterClass(&wc) && 1410 != GetLastError());		

		// center window position
		RECT rcDesktop;
		GetWindowRect(GetDesktopWindow(), &rcDesktop);

		// create window
		m_hWnd = CreateWindowEx(
			WS_EX_APPWINDOW | WS_EX_WINDOWEDGE,	// Extended Style For The Window
			kWindowClassName,									// Class Name
			pTitle,												// Window Title
			WS_CAPTION | WS_POPUPWINDOW | WS_MINIMIZEBOX,		// Defined Window Style
			0, 0,								                // Window Position
			0,                                                  // Window Width
			0,                                                  // Window Height
			NULL,												// No Parent Window
			NULL,												// No Menu
			hInstance,											// Instance
			NULL );

		CC_BREAK_IF(! m_hWnd);

        m_eInitOrientation = CCDirector::sharedDirector()->getDeviceOrientation();
        m_bOrientationInitVertical = (CCDeviceOrientationPortrait == m_eInitOrientation
            || kCCDeviceOrientationPortraitUpsideDown == m_eInitOrientation) ? true : false;
        m_tSizeInPoints.cx = w;
        m_tSizeInPoints.cy = h;
        resize(w, h);

		// init egl
		m_pEGL = CCEGL::create(this);

		if (! m_pEGL)
		{
			DestroyWindow(m_hWnd);
			m_hWnd = NULL;
			break;
		}

		s_pMainWindow = this;
		bRet = true;
	} while (0);

	return bRet;
}
bool CCRenderTexture::initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eFormat)
{
	// If the gles version is lower than GLES_VER_1_0, 
	// some extended gles functions can't be implemented, so return false directly.
	if (CCConfiguration::sharedConfiguration()->getGlesVersion() <= GLES_VER_1_0)
	{
		return false;
	}

    bool bRet = false;
    do 
    {
        w *= (int)CC_CONTENT_SCALE_FACTOR();
        h *= (int)CC_CONTENT_SCALE_FACTOR();

        glGetIntegerv(CC_GL_FRAMEBUFFER_BINDING, &m_nOldFBO);

        // textures must be power of two squared
        unsigned int powW = ccNextPOT(w);
        unsigned int powH = ccNextPOT(h);

        void *data = malloc((int)(powW * powH * 4));
        CC_BREAK_IF(! data);

        memset(data, 0, (int)(powW * powH * 4));
        m_ePixelFormat = eFormat;

        m_pTexture = new CCTexture2D();
        CC_BREAK_IF(! m_pTexture);

        m_pTexture->initWithData(data, (CCTexture2DPixelFormat)m_ePixelFormat, powW, powH, CCSizeMake((float)w, (float)h));
        free( data );

        // generate FBO
        ccglGenFramebuffers(1, &m_uFBO);
        ccglBindFramebuffer(CC_GL_FRAMEBUFFER, m_uFBO);

        // associate texture with FBO
        ccglFramebufferTexture2D(CC_GL_FRAMEBUFFER, CC_GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pTexture->getName(), 0);

        // check if it worked (probably worth doing :) )
        GLuint status = ccglCheckFramebufferStatus(CC_GL_FRAMEBUFFER);
        if (status != CC_GL_FRAMEBUFFER_COMPLETE)
        {
            CCAssert(0, "Render Texture : Could not attach texture to framebuffer");
            CC_SAFE_DELETE(m_pTexture);
            break;
        }

        m_pTexture->setAliasTexParameters();

        m_pSprite = CCSprite::spriteWithTexture(m_pTexture);

        m_pTexture->release();
        m_pSprite->setScaleY(-1);
        this->addChild(m_pSprite);

        ccBlendFunc tBlendFunc = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA };
        m_pSprite->setBlendFunc(tBlendFunc);

        ccglBindFramebuffer(CC_GL_FRAMEBUFFER, m_nOldFBO);
        bRet = true;
    } while (0);
    return bRet;
    
}
Beispiel #23
0
    int drawText(const char * pszText, SIZE& tSize, CCImage::ETextAlign eAlign)
    {
        int nRet = 0;
        wchar_t * pwszBuffer = 0;
        do 
        {
            CC_BREAK_IF(! pszText);

            DWORD dwFmt = DT_WORDBREAK;
            DWORD dwHoriFlag = eAlign & 0x0f;
            DWORD dwVertFlag = (eAlign & 0xf0) >> 4;

            switch (dwHoriFlag)
            {
            case 1: // left
                dwFmt |= DT_LEFT;
                break;
            case 2: // right
                dwFmt |= DT_RIGHT;
                break;
            case 3: // center
                dwFmt |= DT_CENTER;
                break;
            }

            int nLen = strlen(pszText);
            // utf-8 to utf-16
            int nBufLen  = nLen + 1;
            pwszBuffer = new wchar_t[nBufLen];
            CC_BREAK_IF(! pwszBuffer);

            memset(pwszBuffer, 0, sizeof(wchar_t)*nBufLen);
            nLen = MultiByteToWideChar(CP_UTF8, 0, pszText, nLen, pwszBuffer, nBufLen);

            SIZE newSize = sizeWithText(pwszBuffer, nLen, dwFmt, tSize.cx);

            RECT rcText = {0};
            // if content width is 0, use text size as content size
            if (tSize.cx <= 0)
            {
                tSize = newSize;
                rcText.right  = newSize.cx;
                rcText.bottom = newSize.cy;
            }
            else
            {

                LONG offsetX = 0;
                LONG offsetY = 0;
                rcText.right = newSize.cx; // store the text width to rectangle

                // calculate text horizontal offset
                if (1 != dwHoriFlag          // and text isn't align to left
                    && newSize.cx < tSize.cx)   // and text's width less then content width,
                {                               // then need adjust offset of X.
                    offsetX = (2 == dwHoriFlag) ? tSize.cx - newSize.cx     // align to right
                        : (tSize.cx - newSize.cx) / 2;                      // align to center
                }

                // if content height is 0, use text height as content height
                // else if content height less than text height, use content height to draw text
                if (tSize.cy <= 0)
                {
                    tSize.cy = newSize.cy;
                    dwFmt   |= DT_NOCLIP;
                    rcText.bottom = newSize.cy; // store the text height to rectangle
                }
                else if (tSize.cy < newSize.cy)
                {
                    // content height larger than text height need, clip text to rect
                    rcText.bottom = tSize.cy;
                }
                else
                {
                    rcText.bottom = newSize.cy; // store the text height to rectangle

                    // content larger than text, need adjust vertical position
                    dwFmt |= DT_NOCLIP;

                    // calculate text vertical offset
                    offsetY = (2 == dwVertFlag) ? tSize.cy - newSize.cy     // align to bottom
                        : (3 == dwVertFlag) ? (tSize.cy - newSize.cy) / 2   // align to middle
                        : 0;                                                // align to top
                }

                if (offsetX || offsetY)
                {
                    OffsetRect(&rcText, offsetX, offsetY);
                }
            }

            CC_BREAK_IF(! prepareBitmap(tSize.cx, tSize.cy));

            // draw text
            HGDIOBJ hOldFont = SelectObject(m_hDC, m_hFont);
            HGDIOBJ hOldBmp  = SelectObject(m_hDC, m_hBmp);
            
            SetBkMode(m_hDC, TRANSPARENT);
            SetTextColor(m_hDC, RGB(255, 255, 255)); // white color

            // draw text
            nRet = DrawTextW(m_hDC, pwszBuffer, nLen, &rcText, dwFmt);
            //DrawTextA(m_hDC, pszText, nLen, &rcText, dwFmt);

            SelectObject(m_hDC, hOldBmp);
            SelectObject(m_hDC, hOldFont);
        } while (0);
        CC_SAFE_DELETE_ARRAY(pwszBuffer);
        return nRet;
    }
Beispiel #24
0
bool CCEGLView::Create() {
	bool bRet = false;
	do {
		CC_BREAK_IF(m_hWnd);

		HINSTANCE hInstance = GetModuleHandle( NULL);
		WNDCLASS wc;        // Windows Class Structure

		// Redraw On Size, And Own DC For Window.
		wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
		wc.lpfnWndProc = _WindowProc;                // WndProc Handles Messages
		wc.cbClsExtra = 0;                              // No Extra Window Data
		wc.cbWndExtra = 0;                               // No Extra Window Data
		wc.hInstance = hInstance;                        // Set The Instance
		wc.hIcon = LoadIcon( NULL, IDI_WINLOGO);    // Load The Default Icon
		wc.hCursor = LoadCursor( NULL, IDC_ARROW);    // Load The Arrow Pointer
		wc.hbrBackground = NULL;                // No Background Required For GL
		wc.lpszMenuName = m_menu;                         //
		wc.lpszClassName = kWindowClassName;               // Set The Class Name

		CC_BREAK_IF(! RegisterClass(&wc) && 1410 != GetLastError());

		// center window position
		RECT rcDesktop;
		GetWindowRect(GetDesktopWindow(), &rcDesktop);

		WCHAR wszBuf[50] = { 0 };
		MultiByteToWideChar(CP_UTF8, 0, m_szViewName, -1, wszBuf,
				sizeof(wszBuf));

//		 create window
		m_hWnd = CreateWindowEx(
		WS_EX_APPWINDOW | WS_EX_WINDOWEDGE,    // Extended Style For The Window
				kWindowClassName,                                  // Class Name
				wszBuf,                                          // Window Title
				WS_CAPTION | WS_POPUPWINDOW | WS_MINIMIZEBOX, // Defined Window Style
				0, 0,                                         // Window Position
				//TODO: Initializing width with a large value to avoid getting a wrong client area by 'GetClientRect' function.
				1000,// Window Width
				1000,                                           // Window Height
				NULL,                                        // No Parent Window
				NULL,                                                // No Menu
				hInstance,                                           // Instance
				NULL);

//		WNDCLASS wndclass = { 0 };
//		DWORD wStyle = 0;
//		RECT windowRect;
//		HINSTANCE hInstance = GetModuleHandle(NULL);
//
//		wndclass.style = CS_OWNDC;
//		wndclass.lpfnWndProc = (WNDPROC) _WindowProc;;
//		wndclass.hInstance = hInstance;
//		wndclass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
//		wndclass.lpszClassName = TEXT("opengles2.0");
//
//		if (!RegisterClass(&wndclass))
//			return FALSE;
//
//		wStyle = WS_VISIBLE | WS_POPUP | WS_BORDER | WS_SYSMENU | WS_CAPTION
//				| WS_SIZEBOX;
//
//		// Adjust the window rectangle so that the client area has
//		// the correct number of pixels
//		windowRect.left = 0;
//		windowRect.top = 0;
//		windowRect.right = 400;
//		windowRect.bottom = 400;
//
//		AdjustWindowRect(&windowRect, wStyle, FALSE);
//
//		m_hWnd = CreateWindow(
//				TEXT("opengles2.0"),
//				TEXT("TEST!"),
//				wStyle,
//				0,
//				0,
//				windowRect.right - windowRect.left,
//				windowRect.bottom - windowRect.top,
//				NULL,
//				NULL,
//				hInstance,
//				NULL);

		CC_BREAK_IF(!m_hWnd);

		ShowWindow(m_hWnd, TRUE);

		m_glDevice = new CCGLDevice(m_hWnd);

//		printf("m_glDevice = %d\n", m_glDevice);

		if (!m_glDevice->isReady()) {
			printf("DEVICE NOT READY\n");
			m_hWnd = NULL;
			return false;
		}

		s_pMainWindow = this;
		bRet = true;
	} while (0);

#if(_MSC_VER >= 1600)
	m_bSupportTouch = CheckTouchSupport();
	if(m_bSupportTouch)
	{
		m_bSupportTouch = (s_pfRegisterTouchWindowFunction(m_hWnd, 0) != 0);
	}
#endif /* #if(_MSC_VER >= 1600) */

	printf("RETURNING : %d", bRet);
	return bRet;
}
Beispiel #25
0
void GridCell::constructMonsterCellEX()
{
    do{
        CC_BREAK_IF(!m_property);
        CC_BREAK_IF(!m_property->mType==kElementType_Monster);

        CCString *attachValue=CCString::createWithFormat("%d",(int)m_property->mMonsterProperty.mDamage);
        if (m_AttackValueTTF == NULL) {
            m_AttackValueTTF = CCLabelTTF::create(attachValue->getCString(),"Marker Felt",14);
        } else {
            m_AttackValueTTF->setString(attachValue->getCString());
        }
        CC_BREAK_IF(!m_AttackValueTTF);
        m_AttackValueTTF->setAnchorPoint(ccp(0.5,0.5));
        m_AttackValueTTF->setContentSize(CCSizeMake(20, 15));
        m_AttackValueTTF->setColor(ccc3(0,255,0));
        m_AttackValueTTF->setPosition(ccp(m_elementGridImg->getPosition().x+m_elementGridImg->getContentSize().width,m_elementGridImg->getPosition().y+m_elementGridImg->getContentSize().height-m_AttackValueTTF->getContentSize().height));
        this->addChild(m_AttackValueTTF);

        CCString *defenceValue=CCString::createWithFormat("%d",(int)m_property->mMonsterProperty.mDefence);
        if (m_DefenceValueTTF == NULL) {
            m_DefenceValueTTF = CCLabelTTF::create(defenceValue->getCString(),"Marker Felt",14);
        } else {
            m_DefenceValueTTF->setString(defenceValue->getCString());
        }
        CC_BREAK_IF(!m_DefenceValueTTF);
        m_DefenceValueTTF->setAnchorPoint(ccp(0.5,0.5));
        m_DefenceValueTTF->setContentSize(CCSizeMake(20, 15));
        m_DefenceValueTTF->setColor(ccc3(0,255,0));
        m_DefenceValueTTF->setPosition(ccp(m_elementGridImg->getPosition().x+m_elementGridImg->getContentSize().width,m_elementGridImg->getPosition().y+m_elementGridImg->getContentSize().height-2*m_AttackValueTTF->getContentSize().height));
        this->addChild(m_DefenceValueTTF);

        CCString *lifeValue=CCString::createWithFormat("%d",(int)m_property->mMonsterProperty.mLife);
        if (m_LifeValueTTF == NULL) {
            m_LifeValueTTF = CCLabelTTF::create(lifeValue->getCString(),"Marker Felt",14);
        } else {
            m_LifeValueTTF->setString(lifeValue->getCString());
        }
        CC_BREAK_IF(!m_LifeValueTTF);
        m_LifeValueTTF->setAnchorPoint(ccp(0.5,0.5));
        m_LifeValueTTF->setContentSize(CCSizeMake(20, 15));
        m_LifeValueTTF->setColor(ccc3(255,0,0));
        m_LifeValueTTF->setPosition(ccp(m_elementGridImg->getPosition().x+m_elementGridImg->getContentSize().width,m_elementGridImg->getPosition().y+m_elementGridImg->getContentSize().height-3*m_AttackValueTTF->getContentSize().height));
        this->addChild(m_LifeValueTTF);
        
        if (m_countValueTTF==NULL) {
            m_countValueTTF = CCLabelTTF::create("","Marker Felt",24);
            CC_BREAK_IF(!m_countValueTTF);
            m_countValueTTF->retain();
            m_countValueTTF->setAnchorPoint(ccp(0,0.5));
            m_countValueTTF->setColor(ccc3(0,255,0));
            this->addChild(m_countValueTTF);
            
            if (m_property->mMonsterProperty.mType == kBustyType_Boss && (m_property->mMonsterProperty.mSkillType==kBossBustyType_Golden || m_property->mMonsterProperty.mSkillType==kBossBustyType_Kamikaze)) {
                m_countValueTTF->setVisible(true);
                CCString *countStr=CCString::createWithFormat("%d",m_property->mMonsterProperty.mValidRound);
                m_countValueTTF->setString(countStr->getCString());
            }else{
                m_countValueTTF->setVisible(false);
            }
            m_countValueTTF->setPosition(ccp((this->getContentSize().width-m_countValueTTF->getContentSize().width)/2,getContentSize().height+10));
        }
        
    }while(0);
}
Beispiel #26
0
Boolean CCEGLView::EventHandler(TApplication * pApp, EventType * pEvent)
{
    Boolean bHandled = FALSE;

    switch(pEvent->eType)
    {
    case EVENT_WinInit:
        CfgRegisterScreenSwitchNotify(GetWindowHwndId(), 0);
        bHandled = TRUE;
        break;

    case EVENT_WinPaint:
        if (CfgGetScreenStatus())
        {
            // draw 
            CCDirector::sharedDirector()->mainLoop();
        }
        bHandled = TRUE;
        break;

    case EVENT_PenDown:
        bHandled = OnPenDown(pEvent, 0);
        break;

    case EVENT_PenMove:
        bHandled = OnPenMove(pEvent);
        break;

    case EVENT_PenUp:
        bHandled = OnPenUp(pEvent, 0);
        break;

    case EVENT_MultiTouchDown:
        bHandled = OnPenDown(pEvent, pEvent->lParam3);
        break;

    case EVENT_MultiTouchUp:
        bHandled = OnPenUp(pEvent, pEvent->lParam3);
        break;

    case EVENT_KeyCommand:
        {
            if (pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_UP ||
                pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_LONG)
            {
                bHandled = CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeBackClicked);
            }
            else if (pEvent->sParam1 == SYS_KEY_SOFTKEY_LEFT_UP ||
                     pEvent->sParam1 == SYS_KEY_SOFTKEY_LEFT_LONG)
            {
                bHandled = CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeMenuClicked);
            }
        }
        break;

    case MESSAGE_SENSORS_DATA:
        {
            TG3SensorsDataType	data;

            if (Sys_GetMessageBody((MESSAGE_t *)pEvent, &data, sizeof(TG3SensorsDataType)) == sizeof(TG3SensorsDataType) &&
                TG3_SENSOR_TYPE_ACCELEROMETER == data.sensorMask)
            {
                // convert the data to iphone format
                CCAcceleration AccValue;
                AccValue.x = -(data.acceleration.x / TG3_GRAVITY_EARTH);
                AccValue.y = -(data.acceleration.y / TG3_GRAVITY_EARTH);
                AccValue.z = -(data.acceleration.z / TG3_GRAVITY_EARTH);
                AccValue.timestamp = (double) TimGetTicks() / 100;

                // call delegates' didAccelerate function
                CCAccelerometer::sharedAccelerometer()->didAccelerate(&AccValue);
                bHandled = TRUE;
            }
        }
        break;

    case EVENT_WinClose:
        CfgUnRegisterScreenSwitchNotify(GetWindowHwndId(), 0);
        // Stop the application since the main form has been closed
        pApp->SendStopEvent();
        break;

    case EVENT_ScreenSwitchNotify:
        {
            bool bInBack = CCApplication::sharedApplication()->isInBackground();

            // if the app have be in background,don't handle this message
            CC_BREAK_IF(bInBack);

            if (! pEvent->sParam1)  // turn off screen
            {
                // CCDirector::sharedDirector()->pause();
                CCApplication::sharedApplication()->applicationDidEnterBackground();
                CCApplication::sharedApplication()->StopMainLoop();
            }
            else
            {
                // CCDirector::sharedDirector()->resume();
                CCApplication::sharedApplication()->applicationWillEnterForeground();
                CCApplication::sharedApplication()->StartMainLoop();
            }
            break;
        }

    }
//     {
//         char szType[32];
//         sprintf(szType, "%d", pEvent->eType);
//         const char * pszType = szType;
//         switch (pEvent->eType)
//         {
//         case EVENT_ScreenSwitchNotify:
//             pszType = "EVENT_ScreenSwitchNotify";
//             break;
// 
//         case EVENT_GlesUpdateNotify:
//             pszType = "EVENT_GlesUpdateNotify";
//             break;
// 
//         case EVENT_WinPaint:
//             pszType = "EVENT_GlesUpdateNotify";
//             break;
//         }
//         if (pszType)
//         {
//             char szMsg[256];
//             sprintf(szMsg, "%d: %s: %d \r\n", TimGetTicks(), pszType, pEvent->sParam1);
// #if defined (_TRANZDA_VM_)
// #define LOG_FILE_NAME "d:/Work7/NEWPLUS/TDA_DATA/UserData/mesagelog.txt"
// #else
// #define LOG_FILE_NAME "/NEWPLUS/TDA_DATA/UserData/mesagelog.txt"
// #endif
//             FILE * pf = fopen(LOG_FILE_NAME, "a+");
//             fwrite(szMsg, 1, strlen(szMsg), pf);
//             fclose(pf);
//         }
//     }

    if (! bHandled)
    {
        return TWindow::EventHandler(pApp, pEvent);
    }
    return bHandled;
}
static Data getData(const std::string& filename, bool forString)
{
    if (filename.empty())
    {
        return Data::Null;
    }

    Data ret;
    unsigned char* buffer = nullptr;
    size_t size = 0;
    size_t readsize;
    const char* mode = nullptr;

    if (forString)
        mode = "rt";
    else
        mode = "rb";

    auto fileutils = FileUtils::getInstance();
    do
    {
        // Read the file from hardware
        std::string fullPath = fileutils->fullPathForFilename(filename);
        if (fullPath.empty()) {
            break;
        }
        FILE *fp = fopen(fileutils->getSuitableFOpen(fullPath).c_str(), mode);
        CC_BREAK_IF(!fp);
        fseek(fp,0,SEEK_END);
        size = ftell(fp);
        fseek(fp,0,SEEK_SET);

        if (forString)
        {
            buffer = (unsigned char*)malloc(sizeof(unsigned char) * (size + 1));
            buffer[size] = '\0';
        }
        else
        {
            buffer = (unsigned char*)malloc(sizeof(unsigned char) * size);
        }

        readsize = fread(buffer, sizeof(unsigned char), size, fp);
        fclose(fp);

        if (forString && readsize < size)
        {
            buffer[readsize] = '\0';
        }
    } while (0);

    if (nullptr == buffer || 0 == readsize)
    {
        CCLOG("Get data from file %s failed", filename.c_str());
        if (buffer)
            free(buffer);
    }
    else
    {
        ret.fastSet(buffer, readsize);
    }

    return ret;
}
Beispiel #28
0
	static CCXEGL * create(TWindow * pWindow)
	{
		CCXEGL * pEGL = new CCXEGL;
		Boolean bSuccess = FALSE;
		do 
		{
			CC_BREAK_IF(! pEGL);

			TUChar szError[] = {'E','R','R','O','R',0};
			TUChar szEglInitFailed[] = {'e','g','l','I','n','i','t','i','a','l','i','z','e',' ','f','a','i','l','e','d',0};
			TUChar szCreateContextFailed[] = {'e','g','l','C','r','e','a','t','e','C','o','n','t','e','x','t',' ','f','a','i','l','e','d',0};
			TUChar szEglCreateWindowSurfaceFailed[] = {'e','g','l','C','r','e','a','t','e','W','i','n','d','o','w','S','u','r','f','a','c','e',' ','f','a','i','l','e','d',0};
			TUChar szEglMakeCurrentFailed[] = {'e','g','l','M','a','k','e','C','u','r','r','e','n','t',' ','f','a','i','l','e','d',0};

			pEGL->m_eglNativeWindow = pWindow;

			EGLDisplay eglDisplay;
			CC_BREAK_IF(EGL_NO_DISPLAY == (eglDisplay = eglGetDisplay(pEGL->m_eglNativeDisplay)));

			EGLint nMajor, nMinor;
			EGLBoolean bEglRet;
			
			bEglRet = eglInitialize(eglDisplay, &nMajor, &nMinor);
			if ( EGL_FALSE == bEglRet || 1 != nMajor )
			{
				TApplication::GetCurrentApplication()->MessageBox(szEglInitFailed, szError, WMB_OK);
				break;
			}

			const EGLint aConfigAttribs[] =
			{
				EGL_LEVEL,				0,
				EGL_SURFACE_TYPE,		EGL_WINDOW_BIT,
				EGL_RENDERABLE_TYPE,	EGL_OPENGL_ES2_BIT,
				EGL_NATIVE_RENDERABLE,	EGL_FALSE,
				EGL_DEPTH_SIZE,			16,
				EGL_NONE,
			};
			EGLint iConfigs;
			EGLConfig eglConfig;
			CC_BREAK_IF( EGL_FALSE == eglChooseConfig(eglDisplay, aConfigAttribs, &eglConfig, 1, &iConfigs) ||
						  (iConfigs != 1) );

			EGLContext eglContext = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
			if (EGL_NO_CONTEXT == eglContext)
			{
				TApplication::GetCurrentApplication()->MessageBox(szCreateContextFailed, szError, WMB_OK);
				break;
			}

			EGLSurface eglSurface;
			eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, pEGL->m_eglNativeWindow, NULL);
			if (EGL_NO_SURFACE == eglSurface)
			{
				TApplication::GetCurrentApplication()->MessageBox(szEglCreateWindowSurfaceFailed, szError, WMB_OK);
				break;
			}

			bEglRet = eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
			if (EGL_FALSE == bEglRet)
			{
				TApplication::GetCurrentApplication()->MessageBox(szEglMakeCurrentFailed, szError, WMB_OK);
				break;
			}

			pEGL->m_eglDisplay = eglDisplay;
			pEGL->m_eglConfig  = eglConfig;
			pEGL->m_eglContext = eglContext;
			pEGL->m_eglSurface = eglSurface;
			bSuccess = TRUE;
		} while (0);

		if (! bSuccess)
		{
			CC_SAFE_DELETE(pEGL);   
		}

		return pEGL;
	}
bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat format, GLuint depthStencilFormat)
{
    CCASSERT(format != Texture2D::PixelFormat::A8, "only RGB and RGBA formats are valid for a render texture");

    bool ret = false;
    void *data = nullptr;
    do 
    {
        _fullRect = _rtTextureRect = Rect(0,0,w,h);
        //Size size = Director::getInstance()->getWinSizeInPixels();
        //_fullviewPort = Rect(0,0,size.width,size.height);
        w = (int)(w * CC_CONTENT_SCALE_FACTOR());
        h = (int)(h * CC_CONTENT_SCALE_FACTOR());
        _fullviewPort = Rect(0,0,w,h);
        
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);

        // textures must be power of two squared
        int powW = 0;
        int powH = 0;

        if (Configuration::getInstance()->supportsNPOT())
        {
            powW = w;
            powH = h;
        }
        else
        {
            powW = ccNextPOT(w);
            powH = ccNextPOT(h);
        }

        auto dataLen = powW * powH * 4;
        data = malloc(dataLen);
        CC_BREAK_IF(! data);

        memset(data, 0, dataLen);
        _pixelFormat = format;

        _texture = new Texture2D();
        if (_texture)
        {
            _texture->initWithData(data, dataLen, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
        }
        else
        {
            break;
        }
        GLint oldRBO;
        glGetIntegerv(GL_RENDERBUFFER_BINDING, &oldRBO);
        
        if (Configuration::getInstance()->checkForGLExtension("GL_QCOM"))
        {
            _textureCopy = new Texture2D();
            if (_textureCopy)
            {
                _textureCopy->initWithData(data, dataLen, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
            }
            else
            {
                break;
            }
        }

        // generate FBO
        glGenFramebuffers(1, &_FBO);
        glBindFramebuffer(GL_FRAMEBUFFER, _FBO);

        // associate texture with FBO
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);

        if (depthStencilFormat != 0)
        {
            //create and attach depth buffer
            glGenRenderbuffers(1, &_depthRenderBufffer);
            glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderBufffer);
            glRenderbufferStorage(GL_RENDERBUFFER, depthStencilFormat, (GLsizei)powW, (GLsizei)powH);
            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBufffer);

            // if depth format is the one with stencil part, bind same render buffer as stencil attachment
            if (depthStencilFormat == GL_DEPTH24_STENCIL8)
            {
                glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBufffer);
            }
        }

        // check if it worked (probably worth doing :) )
        CCASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");

        _texture->setAliasTexParameters();

        // retained
        setSprite(Sprite::createWithTexture(_texture));

        _texture->release();
        _sprite->setFlippedY(true);

        _sprite->setBlendFunc( BlendFunc::ALPHA_PREMULTIPLIED );

        glBindRenderbuffer(GL_RENDERBUFFER, oldRBO);
        glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
        
        // Diabled by default.
        _autoDraw = false;
        
        // add sprite for backward compatibility
        addChild(_sprite);
        
        ret = true;
    } while (0);
    
    CC_SAFE_FREE(data);
    
    return ret;
}
Beispiel #30
0
bool CCArmature::init(const char *name)
{
    bool bRet = false;
    do
    {
        removeAllChildren();

        CC_SAFE_DELETE(m_pAnimation);
        m_pAnimation = new CCArmatureAnimation();
        m_pAnimation->init(this);

        CC_SAFE_DELETE(m_pBoneDic);
        m_pBoneDic	= new CCDictionary();

        CC_SAFE_DELETE(m_pTopBoneList);
        m_pTopBoneList = new CCArray();
        m_pTopBoneList->init();

        CC_SAFE_DELETE(m_pTextureAtlasDic);
        m_pTextureAtlasDic = new CCDictionary();

        m_sBlendFunc.src = CC_BLEND_SRC;
        m_sBlendFunc.dst = CC_BLEND_DST;


        m_strName = name == NULL ? "" : name;

        CCArmatureDataManager *armatureDataManager = CCArmatureDataManager::sharedArmatureDataManager();

        if(m_strName.length() != 0)
        {
            m_strName = name;

            CCAnimationData *animationData = armatureDataManager->getAnimationData(name);
            CCAssert(animationData, "CCAnimationData not exist! ");

            m_pAnimation->setAnimationData(animationData);


            CCArmatureData *armatureData = armatureDataManager->getArmatureData(name);
            CCAssert(armatureData, "");

            m_pArmatureData = armatureData;


            CCDictElement *_element = NULL;
            CCDictionary *boneDataDic = &armatureData->boneDataDic;
            CCDICT_FOREACH(boneDataDic, _element)
            {
                CCBone *bone = createBone(_element->getStrKey());

                //! init bone's  CCTween to 1st movement's 1st frame
                do
                {

                    CCMovementData *movData = animationData->getMovement(animationData->movementNames.at(0).c_str());
                    CC_BREAK_IF(!movData);

                    CCMovementBoneData *movBoneData = movData->getMovementBoneData(bone->getName().c_str());
                    CC_BREAK_IF(!movBoneData || movBoneData->frameList.count() <= 0);

                    CCFrameData *frameData = movBoneData->getFrameData(0);
                    CC_BREAK_IF(!frameData);

                    bone->getTweenData()->copy(frameData);
                    bone->changeDisplayWithIndex(frameData->displayIndex, false);
                }
                while (0);
            }

            update(0);
            updateOffsetPoint();
        }