cocos2dx lua 热更新方案的实现

(Upgrade.h)

#include <stdio.h>

#include "cocos2d.h"

#include "framework/utils/Utils.h"

#include "framework/json/JSONObject.h"

USING_NS_CC;

#include "ide-support/SimpleConfigParser.h"

#include "extensions/cocos-ext.h"

USING_NS_CC_EXT;

using namespace std;

class Upgrade : public Layer, public AssetsManagerDelegateProtocol

{

public:

    static Scene* createScene();

    Upgrade();

    virtual void onEnter();

    virtual ~Upgrade();

    

    virtual bool init();

    void enterScene();

    void upgrade(); //检查版本更新

    

  //重写AssetsManagerDelegateProtocol中的三个虚函数

    virtual void onError(AssetsManager::ErrorCode errorCode); //错误信息

    virtual void onProgress(int percent); //更新下载进度

    virtual void onSuccess(); //下载成功

    CREATE_FUNC(Upgrade);

    

private:

    AssetsManager* getAssetManager();

    string DirectoryPathCache_Res;

    string DirectoryPathCache_Src;

    string DirectoryPathCache_Resources;

};

#include "framework/updater/Upgrade.h"

#include "SimpleAudioEngine.h"

#include "CCLuaEngine.h"

#include "lua_module_register.h"

#include "cocos2d.h"

#if (CC_TARGET_PLATFORM != CC_PLATFORM_LINUX)

#include "ide-support/CodeIDESupport.h"

#endif

#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)

#include "runtime/Runtime.h"

#include "ide-support/RuntimeLuaImpl.h"

#endif

(Upgrade.cpp)

USING_NS_CC;

USING_NS_CC_EXT;

using namespace CocosDenshion;

#define TEMP_PACKAGE_FILE_NAME "Scripts" //下载后保存的文件夹名

static const char * UpdaterConfig="res/UpdaterConfig.json";

static const char * KEY_PackageURL="PackageUrl";

static const char * KEY_VersionURL="VersionUrl";

Upgrade::Upgrade()

{

     std::vector<std::string> searchPaths;

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

    FileUtils::getInstance()->setPopupNotify(false);

    searchPaths.push_back("ccs-res/");

    searchPaths.push_back("ccs-res/res/");

    

   string path= StringUtils::format("%s%s",FileUtils::getInstance()->getWritablePath().c_str(),"debugruntime/");

    DirectoryPathCache_Resources=path;

    DirectoryPathCache_Res=StringUtils::format("%s/res/",path.c_str());

    DirectoryPathCache_Src=StringUtils::format("%s/src/",path.c_str());;

#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

    DirectoryPathCache_Res=FileUtils::getInstance()->fullPathForFilename("res");

    DirectoryPathCache_Resources=StringUtils::format("%s/", DirectoryPathCache_Res.substr(0, DirectoryPathCache_Res.find_last_of("/")).c_str());

    DirectoryPathCache_Src=FileUtils::getInstance()->fullPathForFilename("src");

#endif

     

     searchPaths.push_back(DirectoryPathCache_Src);

     searchPaths.push_back(DirectoryPathCache_Res);

  

    

     FileUtils::getInstance()->setSearchPaths(searchPaths);

}

Scene* Upgrade::createScene()

{

    auto scene = Scene::create();

    auto layer = Upgrade::create();

    scene->addChild(layer);

    return scene;

}

Upgrade::~Upgrade()

{

    AssetsManager* assetManager = getAssetManager();

    CC_SAFE_DELETE(assetManager);

    #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)

    // NOTE:Please don't remove this call if you want to debug with Cocos Code IDE

    RuntimeEngine::getInstance()->end();

    #endif

}

bool Upgrade::init()

{

    if (!CCLayer::init())

    {

        return false;

    }

    

    return true;

}

void Upgrade::onError(AssetsManager::ErrorCode errorCode)

{

    if (errorCode == AssetsManager::ErrorCode::NO_NEW_VERSION)

    {

        CCLOG("检查新版本: %s","当前已是最新版本");

    }

    else if (errorCode == AssetsManager::ErrorCode::NETWORK)

    {

        CCLOG("检查新版本: %s","更新失败 请检查网络状态");

    }

    else if (errorCode == AssetsManager::ErrorCode::CREATE_FILE)

    {

        CCLOG("检查新版本: %s","创建临时文件失败");

    }else if(errorCode == AssetsManager::ErrorCode::UNCOMPRESS){

        CCLOG("检查新版本: %s","更新包解压失败");

    }

}

void Upgrade::onProgress(int percent)

{

    if (percent < 0)

        return;

    CCLOG("下载进度: %d%%",percent);

}

void Upgrade::onEnter(){

      CCLOG("onEnter!");

      upgrade();

}

void Upgrade::onSuccess()

{

    CCLOG("下载完毕!");

    this->enterScene();

}

void Upgrade::enterScene(){

    #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)

        RuntimeEngine::getInstance()->addRuntime(RuntimeLuaImpl::create(), kRuntimeEngineLua);

        RuntimeEngine::getInstance()->start();

        CCLOG("iShow!");

    #else

        auto engine = LuaEngine::getInstance();

        ScriptEngineManager::getInstance()->setScriptEngine(engine);

        lua_module_register(engine->getLuaStack()->getLuaState());

        engine->getLuaStack()->setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA"));

        engine->executeScriptFile("src/main.lua");

    #endif

    

}

static void ConfigAndroidParameters(JSONObject * object){

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

    JSONObject * json=JSONObject::create();

    json->put("NETLOG_URL",object->getString("NETLOG_URL").c_str());

    Utils::ConfigParameters(json->toString());

#endif

}

AssetsManager* Upgrade::getAssetManager()

{

    static AssetsManager *assetManager = NULL;

    if (!assetManager)

    {

        static AssetsManager *assetManager = NULL;

        if (!assetManager)

        {

            string fileContent = "";

            #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

            

                string fullPathFile=StringUtils::format("%s%s%s",FileUtils::getInstance()->getWritablePath().c_str(),"debugruntime/",UpdaterConfig);

                CCLOG("文件路径:--------%s",fullPathFile.c_str());

                fileContent = FileUtils::getInstance()->getStringFromFile(fullPathFile);

            #elif(CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

           

                string fullPathFile=FileUtils::getInstance()->fullPathForFilename(UpdaterConfig);

                fileContent = FileUtils::getInstance()->getStringFromFile(fullPathFile);

                CCLOG("文件路径:--------%s",fullPathFile.c_str());

            #endif

            

            CCLOG("配置文件内容:%s",fileContent.c_str());

            

            JSONObject * object=JSONObject::create(fileContent.c_str());

            ConfigAndroidParameters(object);

            //获取更新包地址

            string packageUrl=object->getString(KEY_PackageURL);

            //获取版本号地址

            string versionUrl=object->getString(KEY_VersionURL);

            

            CCLOG("更新包地址:%s",packageUrl.c_str());

            CCLOG("获取版本号地址:%s",versionUrl.c_str());

            

            string storageDirectory=DirectoryPathCache_Resources;

            CCLOG("下载存储路径:%s",storageDirectory.c_str());

            assetManager = new AssetsManager(packageUrl.c_str(),versionUrl.c_str(), storageDirectory.c_str());

            assetManager->setDelegate(this);

            assetManager->setConnectionTimeout(8);

            CCLOG("当前版本号:%s",assetManager->getVersion().c_str());

            

            if (assetManager->checkUpdate()) {

                assetManager->update();

            }else{

                this->enterScene();

            }

        }

    }

    return assetManager;

}

void Upgrade::upgrade()

{

    getAssetManager();

    

}

#endif

(作者很懒,此处不做注释,后续修改)

原文地址:https://www.cnblogs.com/HemJohn/p/4850795.html