int CCardFieldDlg::load_card_right_json() { int i,idx; Json::Value root; Json::Reader reader; std::ifstream input; //input.open("e:\\works\\cardlib\\ykt.v3_1.dev\\bin\\lcsmanager\\cardright.json"); input.open((LPCTSTR)m_jsonfile); if(input.is_open()==false) { AfxMessageBox("´ò¿ªÅäÖÃÎļþ´íÎó"); return -1; } if(reader.parse(input,root)==false) { std::string msg = "¶ÁÈ¡ÅäÖÃÎļþ´íÎó : " + reader.getFormatedErrorMessages(); AfxMessageBox(msg.c_str()); return -1; } std::string encoding = root.get("encoding","GBK").asString(); Json::Value fields = root["cardfield"]; Json::Value::Members fldid = fields.getMemberNames(); m_cardfield.clear(); for(i = 0;i < fldid.size();++i) { idx = atoi(fldid[i].c_str()); std::string v = fields.get(fldid[i],"Unknown").asString(); m_cardfield.insert(CARD_FILED_MAP::value_type(idx,v)); } if(fldid.size() > m_string_len) m_string_len = fldid.size(); // std::sort(m_cardfield.begin(),m_cardfield.end()); init_check_box(); return 0; }
//virtual bool AnimationLogic::init( const JsonValueRef json ) { m_states.clear(); if( !json.isMember("states") || !json.isMember("events") ) return false; for( int i=0; i< json["events"].size(); i++) { m_events.push_back( json["events"][i].asString() ); } m_defaultState = json.get("default", "idle").asString(); Json::Value::Members states = json["states"].getMemberNames(); for(int i=0; i< states.size(); i++) { JsonValueRef stateObj = json["states"][states[i]]; Json::Value::Members events = stateObj.getMemberNames(); AnimState animState; animState.name = states[i]; CCLOG(" animState: %s", animState.name.c_str() ); for( int j=0; j< events.size(); j++) { std::string newState = stateObj[ events[j] ].asString(); animState.transitionTable[ events[j] ] = newState; CCLOG(" %s => %s", events[j].c_str(), newState.c_str() ); } m_states[ states[i] ] = animState; } return true; }
//Load skin bool Skin::load(const std::string& filename) { std::ifstream ifs(filename); std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); Json::Value root; Json::Reader reader; m_classes.clear(); if (!reader.parse(str, root)) { return false; } Json::Value::Members classes = root.getMemberNames(); for (uint32 i = 0; i < classes.size(); i++) { std::string name = classes[i]; Json::Value v = root[name]; Skin::SkinClass sc; bool addP = false; //We need to figure out if we're dealing with sub classes. Json::Value::Members subs = v.getMemberNames(); for (uint32 j = 0; j < subs.size(); j++) { if (subs[j] != "normal" && subs[j] != "hover" && subs[j] != "active" && subs[j] != "focus") { //Yup, this is a sub class. Skin::SkinClass sub; jsonToStates(v[subs[j]], sub); sc.m_subs.insert(ClassMapPair(subs[j], sub)); } else { addP = true; } } //There's a valid state in the root if (addP) { jsonToStates(v, sc); } sc.reset(); m_classes.insert(ClassMapPair(name, sc)); } m_loaded = filename; return true; }
void Configuration::SetupRegisteredUsers(MongooseServer& httpServer) { boost::mutex::scoped_lock lock(globalMutex_); httpServer.ClearUsers(); if (!configuration_.isMember("RegisteredUsers")) { return; } const Json::Value& users = configuration_["RegisteredUsers"]; if (users.type() != Json::objectValue) { LOG(ERROR) << "Badly formatted list of users"; throw OrthancException(ErrorCode_BadFileFormat); } Json::Value::Members usernames = users.getMemberNames(); for (size_t i = 0; i < usernames.size(); i++) { const std::string& username = usernames[i]; std::string password = users[username].asString(); httpServer.RegisterUser(username.c_str(), password.c_str()); } }
static void RegisterUserContentType() { if (configuration_.isMember("UserContentType")) { const Json::Value& parameter = configuration_["UserContentType"]; Json::Value::Members members = parameter.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { std::string info = "\"" + members[i] + "\" = " + parameter[members[i]].toStyledString(); LOG(INFO) << "Registering user-defined attachment type: " << info; if (!parameter[members[i]].asBool()) { LOG(ERROR) << "Not a number in this user-defined attachment type: " << info; throw OrthancException(ErrorCode_BadParameterType); } int contentType = parameter[members[i]].asInt(); try { RegisterUserContentType(contentType, members[i]); } catch (OrthancException&) { LOG(ERROR) << "Cannot register this user-defined attachment type: " << info; throw; } } } }
void QueryParser::buildTasks( const Json::Value &query, std::vector<std::shared_ptr<Task> > &tasks, task_map_t &task_map) const { Json::Value::Members members = query["operators"].getMemberNames(); std::string papiEventName = getPapiEventName(query); for (unsigned i = 0; i < members.size(); ++i) { Json::Value planOperationSpec = query["operators"][members[i]]; std::string typeName = planOperationSpec["type"].asString(); std::shared_ptr<PlanOperation> planOperation = QueryParser::instance().parse( typeName, planOperationSpec); planOperation->setEvent(papiEventName); setInputs(planOperation, planOperationSpec); if (auto para = std::dynamic_pointer_cast<ParallelizablePlanOperation>(planOperation)) { para->setPart(planOperationSpec["part"].asUInt()); para->setCount(planOperationSpec["count"].asUInt()); } else { if (planOperationSpec.isMember("part") || planOperationSpec.isMember("count")) { throw std::runtime_error("Trying to parallelize " + typeName + ", which is not a subclass of Parallelizable"); } } planOperation->setOperatorId(members[i]); if (planOperationSpec.isMember("core")) planOperation->setPreferredCore(planOperationSpec["core"].asInt()); // check for materialization strategy if (planOperationSpec.isMember("positions")) planOperation->setProducesPositions(!planOperationSpec["positions"].asBool()); tasks.push_back(planOperation); task_map[members[i]] = planOperation; } }
void readJson() { using namespace std; std::string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\",\"cpp1\":\"jxx\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}"; Json::Reader reader; Json::Value value; if (reader.parse(strValue, value)) { std::string out = value["name"].asString(); //std::cout << out << std::endl; const Json::Value arrayObj = value["array"]; for (int i=0; i<arrayObj.size(); i++) { const Json::Value::Members memberNames = arrayObj[i].getMemberNames(); for(int j=0; j<memberNames.size(); j++) { std::cout << memberNames[j] << std::endl; } } //for (unsigned int i = 0; i < arrayObj.size(); i++) //{ //if (!arrayObj[i].isMember("cpp")) // continue; //out = arrayObj[i].asString(); //std::cout << out; //if (i != (arrayObj.size() - 1)) // std::cout << std::endl; //std::cout << "1111" << std::endl; //} } }
bool KsCardMsg::parseJsonData(const std::string& rootname,Json::Value &root) { size_t i; Json::Value::Members mbs = root.getMemberNames(); ++parseLevel_; if(parseLevel_>2) return false; for(i = 0;i < mbs.size(); ++i) { Json::Value& clt = root[mbs[i]]; std::string fullname = rootname; if(rootname.length() > 0) fullname += "."; fullname += mbs[i]; if(clt.isArray() || clt.isObject()) { if(!parseJsonData(fullname,clt)) return false; } else { msg_field_.insert(PARA_MAP_TYPE::value_type(fullname,root.get(mbs[i],"").asString())); } } return true; }
int jsonParse(string _s) { // Let's parse it Json::Value root; Json::Reader reader; bool parsedSuccess = reader.parse(_s, root, false); if (not parsedSuccess) { // Report failures and their locations // in the document. cout << "Failed to parse JSON" << endl << reader.getFormatedErrorMessages() << endl; return 1; } Json::Value::Members mem = root.getMemberNames(); Json::Value child = root[mem[0]]; cout << "name: " << mem[0] << ", child: " << child.asString() << endl; for (int i = 1; i < mem.size(); ++i) { child = root[mem[i]]; cout << "name: " << mem[i] << endl; Json::Value::Members childMem = child.getMemberNames(); cout << "\t" << "type: " << child[childMem[0]].asString() << endl; cout << "\t" << "value: " << child[childMem[1]].asString() << endl; cout << "\t" << "typeGen: " << child[childMem[2]].asString() << endl; } return 1; }
void SimplifyTags(Json::Value& target, const Json::Value& source, DicomToJsonFormat format) { assert(source.isObject()); target = Json::objectValue; Json::Value::Members members = source.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { const Json::Value& v = source[members[i]]; const std::string& type = v["Type"].asString(); std::string name; switch (format) { case DicomToJsonFormat_Human: name = v["Name"].asString(); break; case DicomToJsonFormat_Short: name = members[i]; break; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } if (type == "String") { target[name] = v["Value"].asString(); } else if (type == "TooLong" || type == "Null") { target[name] = Json::nullValue; } else if (type == "Sequence") { const Json::Value& array = v["Value"]; assert(array.isArray()); Json::Value children = Json::arrayValue; for (Json::Value::ArrayIndex i = 0; i < array.size(); i++) { Json::Value c; SimplifyTags(c, array[i], format); children.append(c); } target[name] = children; } else { assert(0); } } }
void LevelsParser::parseEntity(const Json::Value& json, Entity* entity) { using namespace Json; Json::Value::Members members = json.getMemberNames(); for (int i = 0; i < members.size(); ++i) { String member = members[i]; shared_ptr<EntityParser> parser = EntityParser::parser(member); Json::Value data = json[parser->type().c_str()]; parser->parse(entity, data); } }
void readJsonDict() { std::string strValue = "{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}"; Json::Reader reader; Json::Value value; reader.parse(strValue, value); std::cout << "value.isObject=" << value.isObject() << std::endl; const Json::Value::Members memberNames = value.getMemberNames(); for(int i=0; i<memberNames.size(); i++) { std::cout << memberNames[i] << ":" << value[memberNames[i]] << std::endl; } }
void JsonManager::initFromFile( const std::string& fileName ) { Json::Value json = ReadFileToJson(fileName); if( json.isObject() ) { Json::Value::Members domains = json.getMemberNames(); for(int i=0; i< domains.size(); i++){ m_domains[ domains[i] ] = json[domains[i]]; CCLog("loaded json domain %s", domains[i].c_str() ); } } }
void DbgPrintValue( const Json::Value& value ) { const Json::Value::Members valueMembers = value.getMemberNames(); const UINT numMembers = valueMembers.size(); for( UINT i = 0; i < numMembers; i++ ) { const Json::Value& member = valueMembers[i]; const std::string s = member.toStyledString(); DBGOUT( "\t%s\n", s.c_str() ); //DBGOUT( "\t%s\n", member.c_str() ); } }
Json::Value& QueryTransformationEngine::transform(Json::Value& query) { Json::Value::Members operatorIds = query["operators"].getMemberNames(); Json::Value operatorConfiguration; for (size_t i = 0; i < operatorIds.size(); ++i) { operatorConfiguration = query["operators"][operatorIds[i]]; // check whether operator should be transformed; postpone transformation if dynamic transformation is required if (operatorConfiguration["dynamic"].asBool() == false && _factory.count(operatorConfiguration["type"].asString()) > 0) _factory[operatorConfiguration["type"].asString()]->transform(operatorConfiguration, operatorIds[i], query); // check whether operator needs to be parallelized if (requestsParallelization(operatorConfiguration)) applyParallelizationTo(operatorConfiguration, operatorIds[i], query); } // std::cout << query.toStyledString()<< std::endl; return query; }
////////////////////////////////////////////////////////////////////////// // addAllPackageCrossRefs void CsPackageImporter::addAllPackageCrossRefs( Json::Value& Root ) { std::lock_guard< std::recursive_mutex > Lock( BuildingLock_ ); BcAssert( BuildingBeginCount_ > 0 ); // If it's a string value, attempt to match it. if( Root.type() == Json::stringValue ) { std::cmatch Match; std::regex_match( Root.asCString(), Match, GRegex_ResourceReference ); // Try the weak match. // TODO: Merge into regex. if( Match.size() == 0 ) { std::regex_match( Root.asCString(), Match, GRegex_WeakResourceReference ); } if( Match.size() == 4 ) { BcU32 RefIndex = addPackageCrossRef( Root.asCString() ); // If we find it, replace string reference with a cross ref index. if( RefIndex != BcErrorCode ) { PSY_LOG("Adding crossref %u: %s\n", RefIndex, Root.asCString() ); Root = Json::Value( RefIndex ); } } } else if( Root.type() == Json::arrayValue ) { for( BcU32 Idx = 0; Idx < Root.size(); ++Idx ) { addAllPackageCrossRefs( Root[ Idx ] ); } } else if( Root.type() == Json::objectValue ) { Json::Value::Members MemberValues = Root.getMemberNames(); for( BcU32 Idx = 0; Idx < MemberValues.size(); ++Idx ) { addAllPackageCrossRefs( Root[ MemberValues[ Idx ] ] ); } } }
void FBDialogLookupNgw::httpSelectedFinished () { if (httpSelectedReply->error() == QNetworkReply::NoError) { if (!receivedJson.empty()) { Json::Reader json_reader; Json::Value json_root; if (json_reader.parse(receivedJson, json_root, false)) { Json::Value json_items = json_root["lookup_table"]["items"]; Json::Value::Members mems = json_items.getMemberNames(); selectedLookup.clear(); for (int i=0; i<mems.size(); i++) { QString strName = QString::fromUtf8(mems[i].data()); QString strValue = QString::fromUtf8(json_items[mems[i]] .asString().data()); selectedLookup.append(QPair<QString,QString>(strName,strValue)); } wLabelStatus->setText(tr("Connection successful")); httpSelectedReply->deleteLater(); this->accept(); return; // TODO: do we need return here? } else { wLabelStatus->setText(tr("Error reading JSON")); } } else { wLabelStatus->setText(tr("Error reading JSON")); } } else { wLabelStatus->setText(tr("Connection error")); } receivedJson = ""; httpSelectedReply->deleteLater(); }
int ThreadUsuario::onJoinGame(Json::Value& data, Json::Value& userData){ int ret = 0; Logger::log("["+this->myId+"] Evento Join game"); Value retMsj; retMsj["event"] = EVENT_JOIN_GAME; retMsj["msj"] = "Error"; retMsj["code"] = -1; if(this->partida){ retMsj["msj"] = "Ya estas conectado a una partida"; retMsj["code"] = 1; }else{ string id = data["id"].asString(); long id_n; stringstream ss(id); ss >> id_n; PartidaInterface* part = this->server->connectPartidas(id_n); if (part){ if (part->getEstado() != PARTIDA_ABIERTA){ retMsj["msj"] = "Partida no esta en estado abierta"; }else if (part->getUsuarios() >= part->getMaxUsuarios()){ retMsj["msj"] = "Partida llena"; }else{ Json::Value::Members keys = userData.getMemberNames(); Json::Value yo; for(int i=0; i < keys.size(); i++){ if(keys[i] != string("pass")) yo[keys[i]] = userData[keys[i]]; } this->partida = part; part->addUsuario(this, yo); retMsj["msj"] = "Coneccion correcta"; retMsj["code"] = 0; } } } if (this->write(retMsj)){ Logger::log("["+this->myId+"] Error escribiendo el mensaje de conexion" "de partida"); return 1; } return ret; }
void SimplifyTags(Json::Value& target, const Json::Value& source) { assert(source.isObject()); target = Json::objectValue; Json::Value::Members members = source.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { const Json::Value& v = source[members[i]]; const std::string& name = v["Name"].asString(); const std::string& type = v["Type"].asString(); if (type == "String") { target[name] = v["Value"].asString(); } else if (type == "TooLong" || type == "Null") { target[name] = Json::nullValue; } else if (type == "Sequence") { const Json::Value& array = v["Value"]; assert(array.isArray()); Json::Value children = Json::arrayValue; for (Json::Value::ArrayIndex i = 0; i < array.size(); i++) { Json::Value c; SimplifyTags(c, array[i]); children.append(c); } target[name] = children; } else { assert(0); } } }
static void AddFileToConfiguration(const boost::filesystem::path& path) { LOG(WARNING) << "Reading the configuration from: " << path; Json::Value config; { std::string content; Toolbox::ReadFile(content, path.string()); Json::Value tmp; Json::Reader reader; if (!reader.parse(content, tmp) || tmp.type() != Json::objectValue) { LOG(ERROR) << "The configuration file does not follow the JSON syntax: " << path; throw OrthancException(ErrorCode_BadJson); } Toolbox::CopyJsonWithoutComments(config, tmp); } if (configuration_.size() == 0) { configuration_ = config; } else { Json::Value::Members members = config.getMemberNames(); for (Json::Value::ArrayIndex i = 0; i < members.size(); i++) { if (configuration_.isMember(members[i])) { LOG(ERROR) << "The configuration section \"" << members[i] << "\" is defined in 2 different configuration files"; throw OrthancException(ErrorCode_BadFileFormat); } else { configuration_[members[i]] = config[members[i]]; } } } }
static void CreateDicom(RestApiPostCall& call) { // curl http://localhost:8042/tools/create-dicom -X POST -d '{"PatientName":"Hello^World"}' // curl http://localhost:8042/tools/create-dicom -X POST -d '{"PatientName":"Hello^World","PixelData":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gUGDDcB53FulQAAAElJREFUGNNtj0sSAEEEQ1+U+185s1CtmRkblQ9CZldsKHJDk6DLGLJa6chjh0ooQmpjXMM86zPwydGEj6Ed/UGykkEM8X+p3u8/8LcOJIWLGeMAAAAASUVORK5CYII="}' Json::Value replacements; if (call.ParseJsonRequest(replacements) && replacements.isObject()) { ParsedDicomFile dicom; Json::Value::Members members = replacements.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { const std::string& name = members[i]; std::string value = replacements[name].asString(); DicomTag tag = FromDcmtkBridge::ParseTag(name); if (tag == DICOM_TAG_PIXEL_DATA) { dicom.EmbedImage(value); } else { dicom.Replace(tag, value); } } DicomInstanceToStore toStore; toStore.SetParsedDicomFile(dicom); std::string id; StoreStatus status = OrthancRestApi::GetContext(call).Store(id, toStore); if (status == StoreStatus_Failure) { LOG(ERROR) << "Error while storing a manually-created instance"; return; } OrthancRestApi::GetApi(call).AnswerStoredInstance(call, id, status); } }
void PrefabEntityParser::parse(Entity* entity, const Json::Value& node) { String path = node.asString(); String fullPath = CCFileUtils::fullPathFromRelativePath(path.c_str()); String json = String::fromFile(fullPath); Json::Reader reader; Json::Value root; reader.parse(json.str(), root); Json::Value::Members members = root.getMemberNames(); for (int i = 0; i < members.size(); ++i) { shared_ptr<EntityParser> parser = EntityParser::parser(members[i]); Json::Value data = root[parser->type().c_str()]; parser->parse(entity, data); } entity->prefabOverride(); }
static void ParseReplacements(DicomModification& target, const Json::Value& replacements) { if (!replacements.isObject()) { throw OrthancException(ErrorCode_BadRequest); } Json::Value::Members members = replacements.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { const std::string& name = members[i]; std::string value = replacements[name].asString(); DicomTag tag = FromDcmtkBridge::ParseTag(name); target.Replace(tag, value); VLOG(1) << "Replace: " << name << " " << tag << " == " << value << std::endl; } }
void SpellDiagramNode::createModSlotMenu( RadialLayer* slotEquipMenu, CCPoint pos, int idx ) { m_slotEquipMenu->setCenterNode(createPentNode(MOD_COLOR, ccc4f(0,0,0,1))); m_slotEquipMenu->setPosition( pos ); addChild(m_slotEquipMenu); CCLabelTTF* label = CCLabelTTF::create("cancel", "Arial",20); m_slotEquipMenu->addItem(label, "slotMenuCancel"); Json::Value::Members modNames = m_spellParts_Mods.getMemberNames(); for( int i=0; i<modNames.size(); i++) { label = CCLabelTTF::create(modNames[i].c_str(), "Helvetica", 20.0f); Json::Value data; data["name"] = modNames[i]; data["idx"] = idx; m_slotEquipMenu->addItemWithJson(label, "slotMenuMod", data); } }
int ThreadUsuario::onNewGame(Json::Value& data, Json::Value& userData){ Value retMsj; int ret = 0; retMsj["event"] = EVENT_NEW_GAME; retMsj["msj"] = "Error"; retMsj["code"] = 1; if (this->partida){ retMsj["msj"] = "Ya estas conectado a una partida"; retMsj["code"] = 1; }else{ if (! data["nivel"].isNumeric()) { // TODO: Error } int nivel = data["nivel"].asInt(); if(nivel > userData["nivel"].asInt()){ retMsj["msj"] = "Tu nivel es bajo"; }else{ retMsj["msj"] = "Conectado satisfactoriamnte"; retMsj["code"] = 0; Json::Value::Members keys = userData.getMemberNames(); Json::Value yo; for(int i=0; i < keys.size(); i++){ if(keys[i] != string("pass")) yo[keys[i]] = userData[keys[i]]; } std::string nombre = data["nombre"].asString(); this->partida = this->server->newPartida(nivel, nombre); this->partida->addUsuario(this, yo); } } if (this->write(retMsj)){ Logger::log("["+this->myId+"] Error escribiendo el mensaje de nueva partida"); return 1; } return ret; }
static bool ReadKeys(std::set<std::string>& target, const char* parameter, bool onlyAlphanumeric) { boost::mutex::scoped_lock lock(globalMutex_); target.clear(); if (!configuration_.isMember(parameter)) { return true; } const Json::Value& modalities = configuration_[parameter]; if (modalities.type() != Json::objectValue) { LOG(ERROR) << "Bad format of the \"DicomModalities\" configuration section"; throw OrthancException(ErrorCode_BadFileFormat); } Json::Value::Members members = modalities.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { if (onlyAlphanumeric) { for (size_t j = 0; j < members[i].size(); j++) { if (!isalnum(members[i][j]) && members[i][j] != '-') { return false; } } } target.insert(members[i]); } return true; }
// Return list of values in object void JsonValue::methodGetMemberNames( tThreadData* pThreadData, qshort pParamCount ) { // Create return value EXTfldval fValReturn, fValMember, fValColName; // Create single column list EXTqlist *retList = new EXTqlist( listVlen ); getEXTFldValFromString(fValColName, "Member"); str255 colName; fValColName.getChar(colName, qtrue); retList->addCol(fftCharacter, dpFcharacter, 10000000, &colName); // Ensure that the Json::Value is an Object (since those are the only one's with member names) if ( !(jsonValue->isObject()) ) { fValReturn.setList(retList, qtrue, qfalse); ECOaddParam(pThreadData->mEci, &fValReturn); return; } Json::Value::Members memberNames = jsonValue->getMemberNames(); // Loop the member names to create the list std::string rowMember; for (qlong lineNumber = 0; lineNumber < static_cast<qlong>(memberNames.size()); lineNumber++) { retList->insertRow(0); //retList->setCurRow( lineNumber+1 ); retList->getColValRef(lineNumber+1, 1, fValMember, qtrue); // Retrieve member name and place it in the list rowMember = memberNames[lineNumber]; getEXTFldValFromString(fValMember, rowMember); } fValReturn.setList(retList, qtrue, qfalse); ECOaddParam(pThreadData->mEci, &fValReturn); return; }
static bool ParseFromJsonValue(const Json::Value& root, Message* pb) { std::string pb_type = pb->GetTypeName(); VLOG(20) << "Set info for type:" << pb_type; Json::Value::Members members = root.getMemberNames(); for (size_t i = 0; i < members.size(); ++i) { VLOG(21) << "Member:" << members[i]; const std::string& field_name = members[i]; Json::Value sub_node; sub_node = root.get(field_name, sub_node); if (sub_node.isNull()) { const FieldDescriptor* field = pb->GetDescriptor()->FindFieldByName(field_name); if (field && field->is_required()) { LOG(ERROR) << "Missing required field:" << field_name; return false; } } else { if (!SetValueForMessage(field_name, sub_node, pb)) { return false; } } } return true; }
bool AnimatedSprite::loadTrackFile(const std::string& file, const std::string& name, std::shared_ptr<Library> &lib) { std::ifstream sfile(file.c_str()); if (!sfile.is_open()) { Guy::printLog("Error loading %s anim file", file.c_str()); return false; } Json::Value root; Json::Reader reader; if (!reader.parse(sfile, root) ) { Guy::printLog("Failed to parse %s anim file, reason: %s", file.c_str(), reader.getFormatedErrorMessages().c_str()); return false; } Track track; track.frameCount = root.get("frameCount", "UTF-8" ).asUInt(); const Json::Value keyframes = root["keyFrames"]; for ( int index = 0; index < keyframes.size(); ++index ) { Keyframe key; const Json::Value keyframe = keyframes[index]; const Json::Value data = keyframe["data"]; key.frame = keyframe.get("frame", "UTF-8").asUInt(); key.filename = data.get("fileName", "UTF-8").asString(); Guy::TextureManager::instance().getTexture(key.filename); const Json::Value offset = data["offset"]; key.origin.x = -offset.get("x", "UTF-8").asDouble(); key.origin.y = -offset.get("y", "UTF-8").asDouble(); { const Json::Value rect = data["rect"]; const Json::Value bottomRight = rect["bottomRight"]; const Json::Value topLeft = rect["topLeft"]; key.rect.update(math::vec2i(bottomRight.get("x", "UTF-8").asInt(), bottomRight.get("y", "UTF-8").asInt())); key.rect.update(math::vec2i( topLeft.get("x", "UTF-8").asInt(), topLeft.get("y", "UTF-8").asInt())); } { const Json::Value custom = data["customProperties"]; Json::Value::Members members = custom.getMemberNames(); for(std::size_t i; i < members.size(); ++i) { if (members[i] == std::string("velx")) { key.acceleration.x = custom.get("velx", "UTF-8").asDouble(); key.useAsVelocity = true; } else if (members[i] == std::string("vely")) { key.acceleration.y = custom.get("vely", "UTF-8").asDouble(); key.useAsVelocity = true; } else if (members[i] == std::string("accx")) { key.acceleration.x = custom.get("accx", "UTF-8").asDouble(); key.useAsVelocity = false; } else if (members[i] == std::string("accy")) { key.acceleration.y = custom.get("accy", "UTF-8").asDouble(); key.useAsVelocity = false; } else if (members[i] == std::string("frix")) { key.friction.x = custom.get("frix", "UTF-8").asDouble(); } else if (members[i] == std::string("friy")) { key.friction.y = custom.get("friy", "UTF-8").asDouble(); } else if (members[i] == std::string("maxx")) { key.maxVel.x = custom.get("maxx", "UTF-8").asDouble(); } else if (members[i] == std::string("maxy")) { key.maxVel.y = custom.get("maxy", "UTF-8").asDouble(); } } } const Json::Value hitBoxes = data["hitBoxes"]; for ( int index = 0; index < hitBoxes.size(); ++index ) { const Json::Value hitBox = hitBoxes[index]; const Json::Value rect = hitBox["rect"]; const Json::Value bottomRight = rect["bottomRight"]; const Json::Value topLeft = rect["topLeft"]; math::bbox3i box; box.update(math::vec3i(bottomRight.get("x", "UTF-8").asInt(), bottomRight.get("y", "UTF-8").asInt(), -100)); box.update(math::vec3i( topLeft.get("x", "UTF-8").asInt(), topLeft.get("y", "UTF-8").asInt(), 100)); if (hitBox.get("group", "UTF-8").asString() == std::string("body")) { key.body.push_back(box); } if (hitBox.get("group", "UTF-8").asString() == std::string("damage")) { key.damage.push_back(box); } } track.keyframes.push_back(key); } lib->trackNames.insert(std::make_pair(name, lib->tracks.size())); lib->tracks.push_back(track); return true; }
////////////////////////////////////////////////////////////////////////// // internalImportObject BcBool CsCore::internalImportObject( const Json::Value& Object, CsResourceRef<>& Handle, CsDependancyList* pDependancyList, BcBool ForceImport ) { BcScopedLock< BcMutex > Lock( ContainerLock_ ); // If we pass in a string value, call into the importResource that takes a file name. // If we pass in an object value, load it from that. if( Object.type() == Json::stringValue ) { // We don't pass the dependancy list in if it's a file. return internalImportResource( Object.asString(), Handle, NULL, ForceImport ); } else if( Object.type() == Json::objectValue ) { Json::Value::Members Members = Object.getMemberNames(); if( Members.size() == 1 ) { const std::string& Type = Members[ 0 ]; const Json::Value& Resource = Object[ Type ]; // If the resource is a string, it's an alias - so we need to load the appropriate file. // If the resource is an object, then do appropriate loading. if( Resource.type() == Json::stringValue ) { return internalImportResource( Resource.asString(), Handle, pDependancyList, ForceImport ); } else if( Resource.type() == Json::objectValue ) { // Check the resource has a name, and it's a string. if( Resource.isMember( "name" ) && Resource[ "name" ].type() == Json::stringValue ) { // Import resource by string. const std::string& Name = Resource[ "name" ].asString(); // Check name is a valid length. // TODO: Check it only contains valid characters. if( Name.length() > 0 ) { // Create a file writer for resource (using full name!) CsFile* pFile = createFileWriter( getResourceFullName( Name, Type ) ); if( pFile != NULL ) { // Add name as first string. pFile->addString( Name.c_str() ); // Allocate resource. Handle = allocResource( Name, Type, pFile ); if( Handle.isValid() ) { // Import the resource immediately (blocking operation). if( Handle->import( Resource, *pDependancyList ) ) { BcBool Success = pFile->save(); BcAssertMsg( Success, "Failed to save out \"%s\"", getResourceFullName( Name, Type ).c_str() ); if( Success ) { // Now we need to request the resource, this will delete the imported // one and replace it with a valid loaded resource. internalRequestResource( Name, Type, Handle ); } } else { // Failed to import, so set handle to NULL to release it. Handle = NULL; } } else { delete pFile; BcPrintf( "CsCore: Can not allocate resource type %s.\n", Type.c_str() ); } } else { BcPrintf( "CsCore: Can not allocate file writer.\n" ); } } else { BcPrintf( "CsCore: Json object does not contain valid name.\n" ); } } else { BcPrintf( "CsCore: Json object does not contain name.\n" ); } } else { BcPrintf( "CsCore: Json object is neither an alias or valid resource.\n" ); } } else { BcPrintf( "CsCore: Json object contains more than 1 element.\n" ); } } else { BcPrintf( "CsCore: Invalid Json object.\n" ); } return Handle.isValid(); }