void EditorApplication::initialize(const std::string& configPath) { mEditorConfigPath = configPath; if(!readJson(configPath, mConfig)) { LOG(ERROR) << "Failed to read editor config file: \"" << configPath; QCoreApplication::exit(); } auto projectManagerConfig = mConfig.get<DataProxy>("projectManager"); if(!projectManagerConfig.second) { LOG(ERROR) << "No projectManager configs found in config file"; QCoreApplication::exit(); } if(!mProjectManager->initialize(projectManagerConfig.first)) { LOG(ERROR) << "Failed to initialize project manager"; QCoreApplication::exit(); } rootContext()->setContextProperty("editor", this); rootContext()->setContextProperty("projectManager", mProjectManager); emit(initializedEngine()); }
bool BleepoutConfig::loadJsonFile(std::string path) { JsonLoader loader; Json::Value obj; if (!loader.readFile(path, &obj)) return false; readJson(loader, obj); return true; }
int KeyValueStore::readInt(String key) { String json = readJson(); StaticJsonBuffer<300> jsonBuffer; JsonObject& root = jsonBuffer.parseObject(json); if (!root.success()) { Serial.println("parseObject() failed"); return 0; } return root.get<int>(key); }
cocos2d::CCNode* SceneReader::createNodeWithSceneFile(const char* pszFileName, AttachComponentType eAttachComponent /*= ATTACH_EMPTY_NODE*/) { rapidjson::Document jsonDict; do { CC_BREAK_IF(!readJson(pszFileName, jsonDict)); _eAttachComponent = eAttachComponent; _pNode = createObject(jsonDict, NULL, eAttachComponent); TriggerMng::getInstance()->parse(jsonDict); } while (0); return _pNode; }
cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName) { rapidjson::Document jsonDict; do { CC_BREAK_IF(!readJson(fileName, jsonDict)); _node = createObject(jsonDict, nullptr); TriggerMng::getInstance()->parse(jsonDict); } while (0); return _node; }
cocos2d::CCNode* SceneReader::createNodeWithSceneFile(const char* pszFileName) { cocos2d::CCNode *pNode = NULL; rapidjson::Document jsonDict; do { CC_BREAK_IF(!readJson(pszFileName, jsonDict)); pNode = createObject(jsonDict, NULL); } while (0); return pNode; }
cocos2d::CCNode* SceneReader::createNodeWithSceneFile(const char* pszFileName) { rapidjson::Document jsonDict; do { CC_BREAK_IF(!readJson(pszFileName, jsonDict)); _pNode = createObject(jsonDict, NULL); TriggerMng::getInstance()->parse(jsonDict); } while (0); return _pNode; }
bool ProjectManager::loadProject(QString projectFilePath, DataProxy& configs) { if(!readJson(projectFilePath.toStdString(), configs)) { return false; } QFileInfo projectFileInfo(projectFilePath); mCurrentProjectFolder = projectFileInfo.absolutePath(); QDir::setCurrent(mCurrentProjectFolder); return true; }
// Output JSON to Serial void KeyValueStore::output() { migrate(); String json = readJson(); StaticJsonBuffer<300> jsonBuffer; JsonObject& root = jsonBuffer.parseObject(json); if (!root.success()) { Serial.println("parseObject() failed"); return; } root.prettyPrintTo(Serial); Serial.println(); }
cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/) { _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; }
bool KeyValueStore::write(String key, int value) { String json = readJson(); StaticJsonBuffer<300> jsonBuffer; JsonObject& root = jsonBuffer.parseObject(json); if (!root.success()) { Serial.println("parseObject() failed"); return false; } root.set(key, value); File file = SPIFFS.open(FILENAME_JSON, "w"); root.printTo(file); file.close(); return true; }
Value read(const Bytes &vec, const String &key) { auto ff = detectDataFormat(vec); switch (ff) { case DataFormat::Cbor: return readCbor(vec); break; case DataFormat::Json: return readJson(CharReaderBase((char *)vec.data(), vec.size())); break; default: break; } return Value(); }
extern "C" int main (int argc, char* argv[]) { const std::string path = "contrib/box2deditor/caveexpress.json"; File file(SDL_RWFromFile(path.c_str(), "rb"), path); char *buffer; const int fileLen = file.read((void **) &buffer); const ScopedArrayPtr<char> p(buffer); std::cout.precision(3); if (!buffer || fileLen <= 0) { std::cerr << "Could not read the json file" << std::endl; return EXIT_FAILURE; } if (argc > 1) { for (int i = 1; i < argc; ++i) { if ((!strcmp(argv[i], "-s") || !strcmp(argv[i], "--scale")) && argc >= i + 1) { scale = atof(argv[++i]); //std::cerr << "use a scale factor of " << scale << std::endl; } else if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { usage(); return EXIT_FAILURE; } else if ((!strcmp(argv[i], "--name") || !strcmp(argv[i], "-n")) && argc >= i + 1) { onlyName = argv[++i]; } else { std::cerr << "unknown command given: " << argv[i] << std::endl; usage(); return EXIT_FAILURE; } } } const std::string str(buffer, fileLen); std::cout << "sprites = {" << std::endl; const bool ret = readJson(str); std::cout << "}" << std::endl; if (!ret) return EXIT_FAILURE; return EXIT_SUCCESS; }
CCNode* SceneReader::createObject(const rapidjson::Value &root, cocos2d::CCNode* parent) { const char *className = DICTOOL->getStringValue_json(root, "classname"); //inputFiles->getItemStringValue("classname"); if(strcmp(className, "CCNode") == 0) { CCNode* gb = NULL; if(NULL == parent) { gb = CCNode::create(); } else { gb = CCNode::create(); parent->addChild(gb); } setPropertyFromJsonDict(root, gb); int count = DICTOOL->getArrayCount_json(root, "components"); for (int i = 0; i < count; i++) { const rapidjson::Value &subDict = DICTOOL->getSubDictionary_json(root, "components", i); if (!DICTOOL->checkObjectExist_json(subDict)) { break; } const char *comName = DICTOOL->getStringValue_json(subDict, "classname"); const char *pComName = DICTOOL->getStringValue_json(subDict, "name"); const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(subDict, "fileData"); std::string pPath; std::string pPlistFile; int nResType = 0; //if (fileData != NULL) if (DICTOOL->checkObjectExist_json(fileData)) { const char *file = DICTOOL->getStringValue_json(fileData, "path"); nResType = DICTOOL->getIntValue_json(fileData, "resourceType", - 1); const char *plistFile = DICTOOL->getStringValue_json(fileData, "plistFile"); if (file != NULL) { pPath.append(cocos2d::CCFileUtils::sharedFileUtils()->fullPathForFilename(file)); } if (plistFile != NULL) { pPlistFile.append(cocos2d::CCFileUtils::sharedFileUtils()->fullPathForFilename(plistFile)); } } if (comName != NULL && strcmp(comName, "CCSprite") == 0) { cocos2d::CCSprite *pSprite = NULL; if (nResType == 0) { if (pPath.find(".png") == pPath.npos) { continue; } pSprite = CCSprite::create(pPath.c_str()); } else if (nResType == 1) { std::string pngFile = pPlistFile; std::string::size_type pos = pngFile.find(".plist"); if (pos == pPath.npos) { continue; } pngFile.replace(pos, pngFile.length(), ".png"); CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(pPlistFile.c_str(), pngFile.c_str()); pSprite = CCSprite::createWithSpriteFrameName(pPath.c_str()); } else { continue; } CCComRender *pRender = CCComRender::create(pSprite, "CCSprite"); if (pComName != NULL) { pRender->setName(pComName); } gb->addComponent(pRender); if (_pListener && _pfnSelector) { (_pListener->*_pfnSelector)(pSprite, (void*)(&subDict)); } } else if(comName != NULL && strcmp(comName, "CCTMXTiledMap") == 0) { cocos2d::CCTMXTiledMap *pTmx = NULL; if (nResType == 0) { if (pPath.find(".tmx") == pPath.npos) { continue; } pTmx = CCTMXTiledMap::create(pPath.c_str()); } else { continue; } CCComRender *pRender = CCComRender::create(pTmx, "CCTMXTiledMap"); if (pComName != NULL) { pRender->setName(pComName); } gb->addComponent(pRender); if (_pListener && _pfnSelector) { (_pListener->*_pfnSelector)(pTmx, (void*)(&subDict)); } } else if(comName != NULL && strcmp(comName, "CCParticleSystemQuad") == 0) { std::string::size_type pos = pPath.find(".plist"); if (pos == pPath.npos) { continue; } cocos2d::CCParticleSystemQuad *pParticle = NULL; if (nResType == 0) { pParticle = CCParticleSystemQuad::create(pPath.c_str()); } else { CCLog("unknown resourcetype on CCParticleSystemQuad!"); } pParticle->setPosition(0, 0); CCComRender *pRender = CCComRender::create(pParticle, "CCParticleSystemQuad"); if (pComName != NULL) { pRender->setName(pComName); } gb->addComponent(pRender); if (_pListener && _pfnSelector) { (_pListener->*_pfnSelector)(pParticle, (void*)(&subDict)); } } else if(comName != NULL && strcmp(comName, "CCArmature") == 0) { if (nResType != 0) { continue; } std::string reDir = pPath; std::string file_path = ""; size_t pos = reDir.find_last_of('/'); if (pos != std::string::npos) { file_path = reDir.substr(0, pos+1); } rapidjson::Document jsonDict; if(!readJson(pPath.c_str(), jsonDict)) { CCLog("read json file[%s] error!\n", pPath.c_str()); continue; } int childrenCount = DICTOOL->getArrayCount_json(jsonDict, "armature_data"); const rapidjson::Value &subData = DICTOOL->getDictionaryFromArray_json(jsonDict, "armature_data", 0); const char *name = DICTOOL->getStringValue_json(subData, "name"); childrenCount = DICTOOL->getArrayCount_json(jsonDict, "config_file_path"); for (int i = 0; i < childrenCount; ++i) { const char* plist = DICTOOL->getStringValueFromArray_json(jsonDict, "config_file_path", i); if (plist == NULL) { continue; } std::string plistpath; plistpath += file_path; plistpath.append(plist); cocos2d::CCDictionary *root = CCDictionary::createWithContentsOfFile(plistpath.c_str()); CCDictionary* metadata = DICTOOL->getSubDictionary(root, "metadata"); const char* textureFileName = DICTOOL->getStringValue(metadata, "textureFileName"); std::string textupath; textupath += file_path; textupath.append(textureFileName); CCArmatureDataManager::sharedArmatureDataManager()->addArmatureFileInfo(textupath.c_str(), plistpath.c_str(), pPath.c_str()); } CCArmature *pAr = CCArmature::create(name); CCComRender *pRender = CCComRender::create(pAr, "CCArmature"); if (pComName != NULL) { pRender->setName(pComName); } gb->addComponent(pRender); const char *actionName = DICTOOL->getStringValue_json(subDict, "selectedactionname"); if (actionName != NULL && pAr->getAnimation() != NULL) { pAr->getAnimation()->play(actionName); } if (_pListener && _pfnSelector) { (_pListener->*_pfnSelector)(pAr, (void*)(&subDict)); } } else if(comName != NULL && strcmp(comName, "CCComAudio") == 0) { CCComAudio *pAudio = NULL; if (nResType == 0) { pAudio = CCComAudio::create(); } else { continue; } pAudio->preloadEffect(pPath.c_str()); gb->addComponent(pAudio); if (_pListener && _pfnSelector) { (_pListener->*_pfnSelector)(pAudio, (void*)(&subDict)); } } else if(comName != NULL && strcmp(comName, "CCComAttribute") == 0) { CCComAttribute *pAttribute = NULL; if (nResType == 0) { pAttribute = CCComAttribute::create(); unsigned long size = 0; const char* pData = 0; pData = (char*)(cocos2d::CCFileUtils::sharedFileUtils()->getFileData(pPath.c_str(), "r", &size)); if(pData != NULL && strcmp(pData, "") != 0) { pAttribute->parse(pData); } } else { CCLog("unknown resourcetype on CCComAttribute!"); continue; } gb->addComponent(pAttribute); if (_pListener && _pfnSelector) { (_pListener->*_pfnSelector)(pAttribute, (void*)(&subDict)); } } else if (comName != NULL && strcmp(comName, "CCBackgroundAudio") == 0) { CCComAudio *pAudio = NULL; if (nResType == 0) { pAudio = CCComAudio::create(); } else { continue; } #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) // no MP3 support for CC_PLATFORM_WP8 std::string::size_type pos = pPath.find(".mp3"); if (pos == pPath.npos) { continue; } pPath.replace(pos, pPath.length(), ".wav"); #endif pAudio->preloadBackgroundMusic(pPath.c_str()); pAudio->setFile(pPath.c_str()); bool bLoop = (bool)(DICTOOL->getIntValue_json(subDict, "loop")); pAudio->setLoop(bLoop); gb->addComponent(pAudio); if (_pListener && _pfnSelector) { (_pListener->*_pfnSelector)(pAudio, (void*)(&subDict)); } pAudio->playBackgroundMusic(pPath.c_str(), bLoop); } else if(comName != NULL && strcmp(comName, "GUIComponent") == 0) { cocos2d::extension::UILayer *pLayer = cocos2d::extension::UILayer::create(); pLayer->scheduleUpdate(); UIWidget* widget = cocos2d::extension::GUIReader::shareReader()->widgetFromJsonFile(pPath.c_str()); pLayer->addWidget(widget); CCComRender *pRender = CCComRender::create(pLayer, "GUIComponent"); if (pComName != NULL) { pRender->setName(pComName); } gb->addComponent(pRender); if (_pListener && _pfnSelector) { (_pListener->*_pfnSelector)(pLayer, (void*)(&subDict)); } } } int length = DICTOOL->getArrayCount_json(root, "gameobjects"); for (int i = 0; i < length; ++i) { const rapidjson::Value &subDict = DICTOOL->getSubDictionary_json(root, "gameobjects", i); if (!DICTOOL->checkObjectExist_json(subDict)) { break; } createObject(subDict, gb); } return gb; } return NULL; }
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; 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(); CC_BREAK_IF(pClassName == NULL); pComName = pCocoNode[2].GetValue(); stExpCocoNode *pfileData = pCocoNode[4].GetChildArray(); CC_BREAK_IF(!pfileData); pFile = pfileData[0].GetValue(); pPlist = pfileData[1].GetValue(); CC_BREAK_IF(pFile == NULL && pPlist == NULL); nResType = atoi(pfileData[2].GetValue()); } 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();//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(); for (int i = 0; i < count; ++i) { std::string key = tpChildArray[i].GetName(&tCocoLoader); const char *str = tpChildArray[i].GetValue(); if (key.compare("armature_data") == 0) { int length = tpChildArray[i].GetChildNum(); stExpCocoNode *armature_dataArray = tpChildArray[i].GetChildArray(); if (length < 1) { continue; } length = armature_dataArray[0].GetChildNum(); stExpCocoNode *armature_data = armature_dataArray[0].GetChildArray(); for (int i = 0; i < length; ++i) { std::string key = armature_data[i].GetName(&tCocoLoader); const char *str = armature_data[i].GetValue(); 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();//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; }
int main(int argc, const char *argv[]) { Json::Value options; char usage[] = "Usage: main [jobNum] config1 [config2 ...]"; if (argc <= 1) { std::cerr << "Too few arguments" << std::endl; std::cerr << usage << std::endl; return 1; } else if ((std::string(argv[1]) == "-h") || (std::string(argv[1]) == "--help")) { std::cout << usage << std::endl; return 0; } unsigned int configStart = 1; int jobNum = -1; // try to interpret the first arg as a job number bool isJobNum = true; for (int i = 0; argv[1][i] != '\0'; i++) { if (!isdigit(argv[1][i])) { isJobNum = false; break; } } if (isJobNum) { jobNum = atoi(argv[1]); configStart++; } for (int i = configStart; i < argc; i++) { if (! readJson(argv[i],options)) { return 1; } } int numTrials = options.get("trials",1).asUInt(); int startTrial = 0; int origNumTrials = numTrials; unsigned int numTrialsPerJob = options.get("trialsPerJob",1).asUInt(); unsigned int maxNumStepsPerEpisode = options.get("maxNumStepsPerEpisode",10000).asUInt(); if (jobNum < 0) { jobNum = 0; } else { startTrial = jobNum * numTrialsPerJob; numTrials = min((int)numTrialsPerJob,numTrials-startTrial); } if (numTrials <= 0) { std::cerr << "ERROR: insufficient number of trials: " << numTrials << std::endl; std::cerr << "Calculated from: jobNum: " << jobNum << " numTrialsPerJob: " << numTrialsPerJob << " numTrials: " << origNumTrials << std::endl; std::cerr << "Start trial should be: " << startTrial << std::endl; return 1; } replaceOptsDir(options); if (jobNum == 0) saveConfig(options); replaceOptsJob(options,boost::lexical_cast<std::string>(jobNum)); unsigned int numEpisodes = options.get("numEpisodesPerTrial",1).asUInt(); bool displayDescriptionQ = options["verbosity"].get("description",true).asBool(); bool displaySummaryQ = options["verbosity"].get("summary",true).asBool(); bool displayObsQ = options["verbosity"].get("observation",true).asBool(); bool displayStepsPerEpisodeQ = options["verbosity"].get("stepsPerEpisode",true).asBool(); bool displayStepsPerTrialQ = options["verbosity"].get("stepsPerTrial",true).asBool(); std::string saveFilename = options["save"].get("results","").asString(); bool saveResultsQ = (saveFilename != ""); bool randomizeSeedQ = options.get("randomizeSeed",false).asBool(); // running for fixed lengths unsigned int numStepsPerEpisode = options.get("numStepsPerEpisode",0).asUInt(); bool runForFixedLength = (numStepsPerEpisode != 0); // get the output DT information unsigned int outputDTSteps = options["verbosity"].get("dtsteps",0).asUInt(); std::string outputDTFilename = options["verbosity"].get("dtfile","").asString(); bool outputDTCSVQ = (outputDTFilename != ""); boost::shared_ptr<OutputDT> outputDT; boost::shared_ptr<std::vector<Action::Type> > actions; Observation obs; double startTime = getTime(); std::vector<std::vector<unsigned int> > numSteps(numTrials,std::vector<unsigned int>(numEpisodes,0)); std::vector<std::vector<unsigned int> > numCaptures(numTrials,std::vector<unsigned int>(numEpisodes,0)); std::vector<std::vector<unsigned int> > *results = &numSteps; if (runForFixedLength) results = &numCaptures; std::cout << "Running for " << numTrials << " trials" << std::endl; unsigned int trialNum; unsigned int randomSeed; for (int trial = 0; trial < numTrials; trial++) { trialNum = trial + startTrial; if (randomizeSeedQ) randomSeed = getTime() * 1000000 + 1000 * getpid() + trialNum; // hopefully random enough else randomSeed = trialNum; //std::cout << "RANDOM SEED: " << randomSeed << std::endl; Json::Value trialOptions(options); replaceOptsTrial(trialOptions,trialNum); boost::shared_ptr<World> world = createWorldAgents(randomSeed,trialNum,trialOptions); boost::shared_ptr<const WorldModel> model = world->getModel(); std::cout << "Ad hoc agent ind: " << model->getAdhocInd() << std::endl; // INITIALIZATION if (trial == 0) { if (displayDescriptionQ) std::cout << world->generateDescription() << std::endl; if (outputDTCSVQ) { // set up the actions actions = boost::shared_ptr<std::vector<Action::Type> >(new std::vector<Action::Type>(model->getNumAgents())); // create models for the DT csv output if required std::vector<std::string> modelNames; //modelNames.push_back("GR"); //modelNames.push_back("TA"); //modelNames.push_back("GP"); //modelNames.push_back("PD"); outputDT = boost::shared_ptr<OutputDT>(new OutputDT(outputDTFilename,model->getDims(),model->getNumAgents()-1,modelNames,true,false,outputDTSteps)); } } if (outputDTCSVQ) { if (outputDT->hasCollectedSufficientData()) { std::cout << "WARNING: collected sufficient data, stopping with " << trial << " trials" << std::endl; numSteps.resize(trial); break; } } if (displayStepsPerTrialQ) std::cout << "trial " << std::setw(2) << trialNum << ": " << std::flush; for (unsigned int episode = 0; episode < numEpisodes; episode++) { world->randomizePositions(); world->restartAgents(); if (outputDTCSVQ) { // for the first step, add the observation, since it keeps a history of 1 world->generateObservation(obs); outputDT->saveStep(trial,numSteps[trial][episode],obs,*actions); } while (!model->isPreyCaptured()) { numSteps[trial][episode]++; // check end conditions if (runForFixedLength) { if (numSteps[trial][episode] > numStepsPerEpisode) break; } else { if (numSteps[trial][episode] > maxNumStepsPerEpisode) { std::cerr << "TRIAL " << trial << " EPISODE " << episode << " TOO LONG" << std::endl; break; } } if (displayObsQ) { world->generateObservation(obs); std::cout << obs << std::endl; } world->step(actions); if (outputDTCSVQ){ world->generateObservation(obs); // should follow world->step so that we can extract the observed actions of the previous step outputDT->saveStep(trial,numSteps[trial][episode],obs,*actions); } // if we want to run for a fixed length and the prey is captured, find a new position for the prey if (runForFixedLength && model->isPreyCaptured()) { //std::cout << "Prey is captured, generating new position" << std::endl; world->randomizePreyPosition(); numCaptures[trial][episode]++; } } // while the episode lasts if (displayObsQ) { world->generateObservation(obs); std::cout << obs << std::endl; } if (displayStepsPerEpisodeQ) std::cout << std::setw(3) << (*results)[trial][episode] << " " << std::flush; } if (displayStepsPerTrialQ) displayStepsPerTrial(displayStepsPerEpisodeQ,(*results)[trial]); } // end for trial double endTime = getTime(); // optionally display the summary if (displaySummaryQ) displaySummary(endTime-startTime,*results); // optionally save the results if (saveResultsQ) saveResults(saveFilename,startTrial,*results); // optionally finialize the saving of data for the DT if (outputDTCSVQ) outputDT->finalizeSave(randomSeed); return 0; }
bool CCComRender::serialize(void* r) { bool bRet = false; do { CC_BREAK_IF(r == NULL); rapidjson::Value *v = (rapidjson::Value *)r; const char *pClassName = DICTOOL->getStringValue_json(*v, "classname"); CC_BREAK_IF(pClassName == NULL); const char *pComName = DICTOOL->getStringValue_json(*v, "name"); if (pComName != NULL) { setName(pComName); } else { setName(pClassName); } const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData"); CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData)); const char *pFile = DICTOOL->getStringValue_json(fileData, "path"); const char *pPlist = DICTOOL->getStringValue_json(fileData, "plistFile"); CC_BREAK_IF(pFile == NULL && pPlist == NULL); std::string strFilePath; std::string strPlistPath; if (pFile != NULL) { strFilePath.assign(cocos2d::CCFileUtils::sharedFileUtils()->fullPathForFilename(pFile)); } if (pPlist != NULL) { strPlistPath.assign(cocos2d::CCFileUtils::sharedFileUtils()->fullPathForFilename(pPlist)); } int nResType = DICTOOL->getIntValue_json(fileData, "resourceType", -1); if (nResType == 0) { if (strcmp(pClassName, "CCSprite") == 0 && strFilePath.find(".png") != strFilePath.npos) { m_pRender = CCSprite::create(strFilePath.c_str()); } else if(strcmp(pClassName, "CCTMXTiledMap") == 0 && strFilePath.find(".tmx") != strFilePath.npos) { m_pRender = CCTMXTiledMap::create(strFilePath.c_str()); } 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)); } else if(strcmp(pClassName, "CCArmature") == 0) { std::string reDir = strFilePath; std::string file_path = ""; size_t pos = reDir.find_last_of('/'); if (pos != std::string::npos) { file_path = reDir.substr(0, pos+1); } 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; const char *actionName = DICTOOL->getStringValue_json(*v, "selectedactionname"); if (actionName != NULL && pAr->getAnimation() != NULL) { pAr->getAnimation()->play(actionName); } } else if(strcmp(pClassName, "GUIComponent") == 0) { cocos2d::gui::TouchGroup* tg = cocos2d::gui::TouchGroup::create(); cocos2d::gui::Widget* widget = cocos2d::extension::GUIReader::shareReader()->widgetFromJsonFile(strFilePath.c_str()); tg->addWidget(widget); m_pRender = tg; } 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()); } else { CC_BREAK_IF(true); } } else { CC_BREAK_IF(true); } bRet = true; } while (0); return bRet; }
Value read(const String &string, const String &key) { CharReaderBase r(string); return readJson(r); }
int main(int argc, char *argv[]) { std::string usage = "Usage: runClassifier [options] optionFile testFile numTrainingInstances"; parseCommandLineArgs(&argc,&argv,usage,3,3); std::string optionFile = argv[1]; std::string testFile = argv[2]; unsigned int numTrainingInstances = boost::lexical_cast<unsigned int>(argv[3]); Json::Value options; if (! readJson(optionFile,options)) return 1; ClassifierPtr classifier = createClassifier(options); std::ifstream testIn(testFile.c_str()); ArffReader testReader(testIn); for (unsigned int count = 0; count < numTrainingInstances; count++) { if (testReader.isDone()) { std::cerr << "ERROR: Insufficient training data" << std::endl; std::cerr << "Found " << count << " instances, expected " << numTrainingInstances << std::endl; exit(2); } InstancePtr instance = testReader.next(); classifier->addData(instance); } double trainingTime = 0.0; if (FLAGS_train) { double startTime = getTime(); classifier->train(false); trainingTime = getTime() - startTime; std::cout << "Training time: " << trainingTime << std::endl; } std::cout << "------------------------------------------" << std::endl; //std::cout << *classifier << std::endl; double correct = 0.0; int correctCount = 0; int count; for (count = 0; !testReader.isDone(); count++) { InstancePtr instance = testReader.next(); Classification c; classifier->classify(instance,c); //std::cout << *instance << std::endl; //std::cout << " "; //for (unsigned int i = 0; i < c.size(); i++) //std::cout << c[i] << " "; //std::cout << std::endl; // calculate the fraction correct correct += c[instance->label]; // calculate whether most probable was correct unsigned int maxInd = vectorMaxInd(c); if (maxInd == instance->label) correctCount++; } testIn.close(); std::cout << "------------------------------------------" << std::endl; std::cout << "Target Training Insts: " << numTrainingInstances << std::endl; std::cout << "Testing Insts: " << count << std::endl; std::cout << "Frac Correct: " << correct << "(" << correct / count << ")" << std::endl; std::cout << "Num Correct: " << correctCount << "(" << correctCount / (float)count << ")" << std::endl; std::cout << "Training time: " << trainingTime << std::endl; return 0; }
cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/) { std::string reDir = fileName; std::string file_extension = ""; size_t pos = reDir.find_last_of('.'); if (pos != std::string::npos) { file_extension = reDir.substr(pos, reDir.length()); std::transform(file_extension.begin(),file_extension.end(), file_extension.begin(), (int(*)(int))toupper); } if (file_extension == ".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(file_extension == ".CSB") { do { std::string binaryFilePath = CCFileUtils::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; }