Exemple #1
0
void JsonWrapper::get(const char* name, bool dflt, bool& param) const {
  auto val = m_config.get(name, dflt);

  // Do some simple type conversions that folly used to do
  if (val.isBool()) {
    param = val.asBool();
    return;
  } else if (val.isInt()) {
    auto valInt = val.asInt();
    if (valInt == 0 || valInt == 1) {
      param = (val.asInt() != 0);
      return;
    }
  } else if (val.isString()) {
    auto str = val.asString();
    std::transform(str.begin(), str.end(), str.begin(),
                   [](auto c) { return ::tolower(c); });
    if (str == "0" || str == "false" || str == "off" || str == "no") {
      param = false;
      return;
    } else if (str == "1" || str == "true" || str == "on" || str == "yes") {
      param = true;
      return;
    }
  }
  throw std::runtime_error("Cannot convert JSON value to bool: " +
                           val.asString());
}
Exemple #2
0
void SEMHeader::reallyGetRecord(FFStream& ffs)
throw(std::exception, FFStreamError,
      gpstk::StringUtils::StringException)
{
    string line;

    SEMStream& strm = dynamic_cast<SEMStream&>(ffs);

    //Grab the first line
    strm.formattedGetLine(line);

    numRecords = (short) asInt(line.substr(0,2));
    Title = line.substr(3,24);

    //Grab the second line
    strm.formattedGetLine(line);
    week = (short) asInt(line.substr(0,4));
    Toa = asInt(line.substr(5,6));

    if (nearFullWeek > 0)
    {
        // In case a full week is provided.
        week %= 1024;
        week += (nearFullWeek / 1024) * 1024;
        short diff = nearFullWeek - week;
        if (diff > 512)
            week += 512;
        else if(diff < -512)
            week -= 512;
    }

    strm.header = *this;
    strm.headerRead = true;

} // end of reallyGetRecord()
Exemple #3
0
 void
 Time::operator=(const std::string& other)
 {
    if ( (other.size() < 12) || (other[2] != ':') || (other[6] != ':') )
    {
       Exception  err("Invalid time syntax: " + other);
       GPSTK_THROW(err);
    }
    year = asInt(other.substr(0, 2) );
    doy  = asInt(other.substr(3, 3) );
    sod  = asInt(other.substr(7, 5) );
 }
Exemple #4
0
MAPM DateUtils::convertDMY2Absolute(MAPM day, MAPM month, MAPM year)
{
  MAPM prevYear = year - 1;
  if(year.sign() < 0) ++prevYear;
  MAPM absolute = ( prevYear * 365 ) + prevYear.integer_divide(4) - prevYear.integer_divide(100) +
    prevYear.integer_divide(400);

  if(isLeapYear(year))
    absolute+=days_before_month_leap[asInt(month)-1];
  else
    absolute+=days_before_month[asInt(month)-1];
  absolute+= day;
  return absolute - 1;
}
Exemple #5
0
      /** This function sets the time for this header.
       * It looks at \a line to obtain the needed information.
       */
   CommonTime Rinex3ClockHeader::parseTime(const string& line) const
   {

      int year, month, day, hour, min;
      double sec;

      year  = asInt(   line.substr( 0, 4 ));
      month = asInt(   line.substr( 4, 3 ));
      day   = asInt(   line.substr( 7, 3 ));
      hour  = asInt(   line.substr(10, 3 ));
      min   = asInt(   line.substr(13, 3 ));
      sec   = asDouble(line.substr(16, 10));

      return CivilTime(year, month, day, hour, min, sec).convertToCommonTime();

   }  // End of method 'Rinex3ClockHeader::parseTime(const string& line)'
Exemple #6
0
  std::ostream& value(const ast::types::abstract::Value& value) {
    const boost::regex esc("\n");
    const std::string rep("\\\\n");

    type(value.type());
    stream << " ";
    switch(value) {
    case ast::types::Bool:
      stream << asBool(value).value;
      break;
    case ast::types::Float32:
      stream << asFloat(value).value;
      break;
    case ast::types::Int32:
      stream << asInt(value).value;
      break;
    case ast::types::String:
      stream << "\""
                << boost::regex_replace(asString(value).value, esc, rep,
                                        boost::match_default | boost::format_sed)
                << "\"";
      break;
    case ast::types::Void:
      stream << "()";
      break;
    default:
      stream << " ??";
    }
    return stream;
  }
Exemple #7
0
LargestInt Value::asLargestInt() const {
#if defined(JSON_NO_INT64)
  return asInt();
#else
  return asInt64();
#endif
}
Exemple #8
0
void TMXLayer::parseInternalProperties()
{
    // if cc_vertex=automatic, then tiles will be rendered using vertexz

    auto vertexz = getProperty("cc_vertexz");
    if (!vertexz.isNull())
    {
        std::string vertexZStr = vertexz.asString();
        // If "automatic" is on, then parse the "cc_alpha_func" too
        if (vertexZStr == "automatic")
        {
            _useAutomaticVertexZ = true;
            auto alphaFuncVal = getProperty("cc_alpha_func");
            float alphaFuncValue = alphaFuncVal.asFloat();
            setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST));

            GLint alphaValueLocation = glGetUniformLocation(getShaderProgram()->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);

            // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison
            
            // use shader program to set uniform
            getShaderProgram()->use();
            getShaderProgram()->setUniformLocationWith1f(alphaValueLocation, alphaFuncValue);
            CHECK_GL_ERROR_DEBUG();
        }
        else
        {
            _vertexZvalue = vertexz.asInt();
        }
    }
}
Exemple #9
0
std::string 
Value::asString() const
{
   switch ( type_ )
   {
   case nullValue:
      return "";
   case stringValue:
      return value_.string_ ? value_.string_ : "";
   case booleanValue:
      return value_.bool_ ? "true" : "false";
   case intValue:
   case uintValue:
	   {
		   std::stringstream ss;
		   ss << asInt();
		   return ss.str();
	   }
	   break;
   case realValue:
   case arrayValue:
   case objectValue:
      JSON_ASSERT_MESSAGE( false, "Type is not convertible to string" );
   default:
      JSON_ASSERT_UNREACHABLE;
   }
   return ""; // unreachable
}
int
XmlConfig::asInt(const std::string &key, int defval) const {
	try {
		return asInt(key);
	} catch (const std::exception &e) {
		return defval;
	}
}
//---------------------------------------------------------
int CSG_String::asInt(void) const
{
	int		Value	= 0;

	asInt(Value);

	return( Value );
}
Exemple #12
0
   void RinexClockData::reallyGetRecord(FFStream& ffs)
      throw(exception, FFStreamError, StringException)
   {
      // cast the stream to be an RinexClockStream
      RinexClockStream& strm = dynamic_cast<RinexClockStream&>(ffs);

      clear();

      string line;
      strm.formattedGetLine(line,true);      // true means 'expect possible EOF'
      stripTrailing(line);
      if(line.length() < 59) {
         FFStreamError e("Short line : " + line);
         GPSTK_THROW(e);
      }

      //cout << "Data Line: /" << line << "/" << endl;
      datatype = line.substr(0,2);
      site = line.substr(3,4);
      if(datatype == string("AS")) {
         strip(site);
         int prn(asInt(site.substr(1,2)));
         if(site[0] == 'G') sat = RinexSatID(prn,RinexSatID::systemGPS);
         else if(site[0] == 'R') sat = RinexSatID(prn,RinexSatID::systemGlonass);
         else {
            FFStreamError e("Invalid sat : /" + site + "/");
            GPSTK_THROW(e);
         }
         site = string();
      }

      time = CivilTime(asInt(line.substr( 8,4)),
                     asInt(line.substr(12,3)),
                     asInt(line.substr(15,3)),
                     asInt(line.substr(18,3)),
                     asInt(line.substr(21,3)),
                     asDouble(line.substr(24,10)),
                     TimeSystem::Any);

      int n(asInt(line.substr(34,3)));
      bias = asDouble(line.substr(40,19));
      if(n > 1 && line.length() >= 59) sig_bias = asDouble(line.substr(60,19));

      if(n > 2) {
         strm.formattedGetLine(line,true);
         stripTrailing(line);
         if(int(line.length()) < (n-2)*20-1) {
            FFStreamError e("Short line : " + line);
            GPSTK_THROW(e);
         }
         drift =     asDouble(line.substr( 0,19));
         if(n > 3) sig_drift = asDouble(line.substr(20,19));
         if(n > 4) accel     = asDouble(line.substr(40,19));
         if(n > 5) sig_accel = asDouble(line.substr(60,19));
      }

   }   // end reallyGetRecord()
int ConfigFile::getValueAsInt(const std::string name)
{
    first();
    do {
        if ((*this)[0] == name) {
            return asInt(1);
        }
    } while (next());
    // TODO: This should throw an error, otherwise there is no way to tell 
    // when we did not find the int
    return 0;
}
Exemple #14
0
//追加
void SqliteManager::addPicoJsonObject(const std::string &table_name, picojson::object &object)
{
    std::string cols = "";
    std::string values = "";

    picojson::object::iterator it = object.begin();
    while (it != object.end()) {
        cols.append('\''+(*it).first+'\'');
        cols.append(",");

        std::string value;
        if(object[it->first].is<double>()) {
            auto val = cocos2d::Value(object[it->first].get<double>());
            value = std::to_string(val.asInt());
        } else if(object[it->first].is<std::string>()) {
            value = object[it->first].get<std::string>();
        }

        values.append('\''+value+'\'');
        values.append(",");
        it++;
    }

    std::string create_at = "created_at";
    std::string updated_at = "updated_at";
    std::string now_time = "datetime('now', 'localtime')";

    //作成時間
    cols.append('\''+create_at+'\'');
    cols.append(",");
    values.append(now_time);
    values.append(",");

    //更新時間
    cols.append('\''+create_at+'\'');
    cols.append(",");
    values.append(now_time);
    values.append(",");

    cols.pop_back();
    values.pop_back();

    std::string sql = "INSERT INTO "+ table_name +" (" + cols + ") VALUES (" + values + ")";
    CCLOG("sql:%s", sql.c_str());

    _result = this->executeQuery(sql);
    if (_result != SQLITE_OK)
    {
        CCLOG("エラー%d:%s", _result, _error_msg);
    }

}
void ShapeCache::addShapeWithFileToSprite(std::string plist, cocos2d::Sprite *s){
    FileUtils *fu = FileUtils::getInstance();
    ValueMap root = fu->getValueMapFromFile(plist);
    
    auto bodies = root["bodies"].asValueMap();
    ValueMap fixtureDef;
    for (auto iter=bodies.begin(); iter!=bodies.end(); iter++) {
        fixtureDef = iter->second.asValueMap();
    }
    
    ValueMap item = fixtureDef["fixtures"].asValueVector()[0].asValueMap();
    s->setPhysicsBody(PhysicsBody::create());
    for (auto iter=item.begin(); iter!=item.end(); iter++) {
        std::string key = iter->first;
        auto type = iter->second;
        if (key == "polygons") {
            auto value = type.asValueVector();
            for (int i=0; i<value.size(); i++) {
                auto _item = value[i].asValueVector();
                Vec2 *vec = new Vec2[_item.size()];
                for (int j=0; j<_item.size(); j++) {
                    Point p = PointFromString(_item[j].asString().c_str());
                    vec[j] = Vec2(p.x, p.y);
                }
                s->getPhysicsBody()->addShape(PhysicsShapePolygon::create(vec, _item.size()));
            }
        }else if (key == "mass"){
            s->getPhysicsBody()->setMass(type.asInt());
        }else if (key == "friction"){
            auto shapes = s->getPhysicsBody()->getShapes();
            for (int i=0; i<shapes.size(); i++) {
                shapes.at(i)->setFriction(type.asInt());
            }
        }
        
    }
    
}
Exemple #16
0
void SoldierLyzc::animationEvent( Armature *armature, MovementEventType movementType, const string& movementID )
{
	if (movementType == LOOP_COMPLETE || movementType == COMPLETE)
	{
		auto va = Value(movementID.substr(movementID.length() - 2,2).c_str());
		_currentIndex = va.asInt();
		if (_currentIndex != _degreeIndex)
		{
			getHead()->getAnimation()->play(getMovement(_currentIndex,_degreeIndex));
		}
		else
		{
			setStatus(e_battle_status_attack);
		}
	}
}
Exemple #17
0
//更新
void SqliteManager::savePicoJsonObject(const std::string &table_name, picojson::object &object)
{
    std::string values = "";
    std::string update_id = "";

    picojson::object::iterator it = object.begin();
    while (it != object.end()) {
        values.append('\''+(*it).first+'\'');
        values.append("=");


        std::string value;
        if(object[it->first].is<double>()) {
            auto val = cocos2d::Value(object[it->first].get<double>());
            value = std::to_string(val.asInt());
        } else if(object[it->first].is<std::string>()) {
            value = object[it->first].get<std::string>();
        }

        if ((*it).first == "id") {
            update_id = value;
        }

        values.append('\''+value+'\'');
        values.append(",");
        it++;
    }
    std::string updated_at = "updated_at";
    std::string now_time = "datetime('now', 'localtime')";

    //更新時間
    values.append('\''+updated_at+'\'');
    values.append("=");
    values.append(now_time);

    std::string sql = "UPDATE "+ table_name +" SET " + values + " WHERE id = " + update_id;
    CCLOG("sql:%s", sql.c_str());

    _result = this->executeQuery(sql);
    if (_result != SQLITE_OK)
    {
        CCLOG("エラー%d:%s", _result, _error_msg);
    }

}
bool cVariant::cast( Type t )
{
	switch ( t )
	{
	case StringType:
		asString();
		break;
	case IntType:
		asInt();
		break;
	case DoubleType:
		asDouble();
		break;
	default:
		( *this ) = cVariant();
	}
	return canCast( t );
}
Exemple #19
0
std::size_t dynamic::hash() const {
  switch (type()) {
  case OBJECT:
  case ARRAY:
  case NULLT:
    throw TypeError("not null/object/array", type());
  case INT64:
    return std::hash<int64_t>()(asInt());
  case DOUBLE:
    return std::hash<double>()(asDouble());
  case BOOL:
    return std::hash<bool>()(asBool());
  case STRING:
    return std::hash<fbstring>()(asString());
  default:
    CHECK(0); abort();
  }
}
Exemple #20
0
//ストーリーの作成
void StoryManager::addStory(picojson::value pico_value)
{
    sqlite3_stmt* stmt;
    char* sql = "INSERT INTO `story` (`id`, `hash`, `title`, `text`, `length`, `type`, `number`, `max_number`, `created_at`, `updated_at`) VALUES(?,?,?,?,?,?,?,?,?,?)";
    const char *pzTest;
    sqlite3_prepare_v2(useDataBase, sql, std::strlen(sql), &stmt, &pzTest);
    sqlite3_reset(stmt);
    
    //取得
    picojson::object& record = pico_value.get<picojson::object>();
    auto id = Value(record["id"].get<std::string>());
    std::string hash = record["hash"].get<std::string>();
    std::string title = record["title"].get<std::string>();
    std::string text = record["text"].get<std::string>();
    std::string length = record["length"].get<std::string>();
    auto type = Value(record["type"].get<std::string>());
    auto number = Value(record["number"].get<std::string>());
    auto max_number = Value(record["max_number"].get<std::string>());
    auto created_at = Value(record["created_at"].get<std::string>());
    auto updated_at = Value(record["updated_at"].get<std::string>());
    
    CCLOG("id:%d", id.asInt());
    CCLOG("hash:%s", hash.c_str());
    
    sqlite3_bind_int(stmt, 1, id.asInt());
    sqlite3_bind_text(stmt, 2, hash.c_str(), std::strlen(hash.c_str()), 0);
    sqlite3_bind_text(stmt, 3, title.c_str(), std::strlen(title.c_str()), 0);
    sqlite3_bind_text(stmt, 4, text.c_str(), std::strlen(text.c_str()), 0);
    sqlite3_bind_text(stmt, 5, length.c_str(), std::strlen(length.c_str()), 0);
    sqlite3_bind_int(stmt, 6, type.asInt());
    sqlite3_bind_int(stmt, 7, number.asInt());
    sqlite3_bind_int(stmt, 8, max_number.asInt());
    sqlite3_bind_int(stmt, 9, created_at.asInt());
    sqlite3_bind_int(stmt, 10, updated_at.asInt());
    
    // stmtのSQLを実行
    sqlite3_step(stmt);
    sqlite3_finalize(stmt);
}
Exemple #21
0
    void AttributeWriter::addElement(NwkAddr nwkAddr, EndpointID endpointID, std::shared_ptr<zigbee::Cluster> cluster, Json::Value &&value,
                                     AttributeWriterResult &results) {
        auto jsonId = value["id"];
        if (!jsonId.isInt()) {
            return;
        }
        int id = jsonId.asInt();
        auto jsonType = value["type"];
        if (!jsonType.isString()) {
            return;
        }
        auto jsonData = value["data"];
        auto type = jsonType.asString();
        auto zigbeeDevice = singletons.getZigbeeDevice();
        auto attribute = cluster->getAttribute(id);
        auto &rawValue = attribute->getAttributeRawValue();
        if (type == "string") {
            if (!jsonData.isString()) {
                return;
            }
            rawValue(jsonData.asString());
        } else  if (type == "int" && jsonData.isInt64()){
            rawValue(jsonData.asInt64());
        } else  if (type == "raw" && jsonData.isArray()){
            std::vector<uint8_t > rawData;
            for (Json::Value::ArrayIndex i = 0; i < jsonData.size(); i++) {
                rawData.push_back(jsonData[i].asInt());
            }

            rawValue(rawData);
        } else {
            return;
        }
        zigbeeDevice->writeAttribute(nwkAddr, endpointID, cluster->getId(), id, rawValue.type, rawValue.rawData.size(), &rawValue.rawData[0]);
        results.add(id);
    }
Exemple #22
0
   void RinexNavData::getPRNEpoch(const string& currentLine)
      throw(StringException, FFStreamError)
   {
      try
      {
            // check for spaces in the right spots...
         for (int i = 2; i <= 17; i += 3)
            if (currentLine[i] != ' ')
               throw(FFStreamError("Badly formatted line"));

         PRNID = asInt(currentLine.substr(0,2));

         short yr = asInt(currentLine.substr(2,3));
         short mo = asInt(currentLine.substr(5,3));
         short day = asInt(currentLine.substr(8,3));
         short hr = asInt(currentLine.substr(11,3));
         short min = asInt(currentLine.substr(14,3));
         double sec = asDouble(currentLine.substr(17,5));

            // years 80-99 represent 1980-1999
         const int rolloverYear = 80;
         if (yr < rolloverYear)
            yr += 100;
         yr += 1900;

         // Real Rinex has epochs 'yy mm dd hr 59 60.0' surprisingly often....
         double ds=0;
         if(sec >= 60.) { ds=sec; sec=0.0; }
         time = CivilTime(yr,mo,day,hr,min,sec).convertToCommonTime();
         if(ds != 0) time += ds;

         Toc = (static_cast<GPSWeekSecond>(time)).sow;
         af0 = gpstk::StringUtils::for2doub(currentLine.substr(22,19));
         af1 = gpstk::StringUtils::for2doub(currentLine.substr(41,19));
         af2 = gpstk::StringUtils::for2doub(currentLine.substr(60,19));
      }
      catch (std::exception &e)
      {
         FFStreamError err("std::exception: " +
                           string(e.what()));
         GPSTK_THROW(err);
      }
   }
Exemple #23
0
void BattleUI::InitHeroUI()
{
    ArmatureDataManager::getInstance()->addArmatureFileInfo("Texiao.ExportJson");
    
    auto layout_Bottom = m_RootWidget->getChildByName<Layout*>("Layout_Bottom");
    
    auto text_HeroText = layout_Bottom->getChildByName<Text*>("Text_HeroText");
    
    auto langId = (int)LanguageIdEnum::SelfLangId;
    auto langText = MultiLanguage::getInstance()->GetText(langId);
    text_HeroText->setString(langText);
    
    auto lbar_HeroHp = layout_Bottom->getChildByName<LoadingBar*>("LBar_HeroHp");
    lbar_HeroHp->setPercent(100);
    
    
    //自动或手动控制战斗
    auto btn_Auto = layout_Bottom->getChildByName<Button*>("Btn_Auto");
    auto btn_UnAuto = layout_Bottom->getChildByName<Button*>("Btn_UnAuto");
    if (BattleData::getInstance()->m_HeroAutoAttack)
    {
        btn_Auto->setVisible(true); btn_UnAuto->setVisible(false);
        
    }else
    {
        btn_Auto->setVisible(false); btn_UnAuto->setVisible(true);
    }
    
    langId = (int)LanguageIdEnum::AutoAttackLangId;
    langText = MultiLanguage::getInstance()->GetText(langId);
    btn_Auto->setTitleText(langText); btn_UnAuto->setTitleText(langText);
    btn_Auto->addClickEventListener([=](Ref* sender)
     {
         btn_Auto->setVisible(false);
         btn_UnAuto->setVisible(true);
         BattleData::getInstance()->m_HeroAutoAttack = false;
         UserData::getInstance()->Update_Value(UserDataEnum::AutoAttack, Value(0));
     });
    
    btn_UnAuto->addClickEventListener([=](Ref* sender)
    {
        btn_Auto->setVisible(true);
        btn_UnAuto->setVisible(false);
        for (auto pb : *m_VecProgressBar) pb->Resume();
        BattleData::getInstance()->m_HeroAutoAttack = true;
        UserData::getInstance()->Update_Value(UserDataEnum::AutoAttack, Value(1) );
    });
    
    auto btn_Bread = layout_Bottom->getChildByName<Button*>("Btn_Bread");
    auto text_BreadName = btn_Bread->getChildByName<Text*>("Text_BreadNAME");
    langId = (int)LanguageIdEnum::BreadLangId;
    langText = MultiLanguage::getInstance()->GetText(langId);
    text_BreadName->setString(langText);
    
    auto text_Bread = btn_Bread->getChildByName<Text*>("Text_Bread");
    
    
    auto bread_Num = 0;
    auto breadData = UserData::getInstance()->Get_MVI_Value(UserDataEnum::BackPack, (int)CfgIdEnum::BreadId);
    if(breadData != Value::Null) bread_Num = breadData.asInt();
    
    text_Bread->setString(StringUtils::format("%d", bread_Num));
    
    auto lbar_Bread = btn_Bread->getChildByName<LoadingBar*>("LBar_Bread");
    
    string pbName = "BreadHpSchedule";
    auto progressBar = new ProgressBar();
    progressBar->SetTotalTime(3); //3秒吃一个面包
    progressBar->SetScheduleName(pbName);
    progressBar->SetLoadingBar(lbar_Bread);
    
    m_VecProgressBar->push_back(progressBar);
    
    progressBar->SetCallBack([this, progressBar]()
     {
         progressBar->Restart();
         progressBar->GetLoadingBar()->setPercent(0);
         m_RootWidget->unschedule(progressBar->GetScheduleName());
     });
    
    
    btn_Bread->addClickEventListener([=](Ref* sender)
     {

         auto bread_Num = 0;
         auto breadData = UserData::getInstance()->Get_MVI_Value(UserDataEnum::BackPack, (int)CfgIdEnum::BreadId);
         if(breadData != Value::Null) bread_Num = breadData.asInt();

         if (bread_Num == 0)
         {
             auto langId = (int)LanguageIdEnum::BreadNotEnoughId;
             auto langText = MultiLanguage::getInstance()->GetText(langId);
             MoveText::getInstance()->AddDefaultTextData(m_RootWidget, langText);
         }else
         {
             if(progressBar->GetRemainTime() == progressBar->GetTotalTime())
             {
                 auto bread_Num = UserData::getInstance()->Update_VMI_Fun(
                                  UserDataEnum::BackPack, (int)CfgIdEnum::BreadId, -1);
                 if (bread_Num >= 0)
                 {
                     text_Bread->setString(StringUtils::format("%d", bread_Num));
                     //回血
                     BattleData::getInstance()->BreadRevertHp();
                     
                     m_RootWidget->schedule([this, progressBar](float f)
                        {
                            progressBar->Update(f);
                        }, progressBar->GetScheduleName());
                 }
             }
             AchievementSystem::getInstance()->CheckAchievement(UserEventType::BattleEatBread, 1);
         }
     });
    
    vector<pair<int, int> >heroVec;
    BattlePubUI::getInstance()->GetBackPackHero(&heroVec);
    auto idx = 0; //创建英雄技能
    for (auto heroData : heroVec)
    {
        auto heroId = heroData.first;
        auto heroNum = heroData.second;
        for (auto i = 0; i < heroNum ; i++)
        {
            CreateHeroEvent(heroId, idx);  idx++;
        }
    }

    auto talentTeamTotalHp = BattleData::getInstance()->m_TalentTeamTotalHp;
    auto text_HeroHp = layout_Bottom->getChildByName<Text*>("Text_HeroHp");
    text_HeroHp->setString(StringUtils::format("%d/%d", talentTeamTotalHp, talentTeamTotalHp));
    
    BattleData::getInstance()->m_HeroHpLBar = lbar_HeroHp;
    BattleData::getInstance()->m_TextHeroHp = text_HeroHp;

}
	unsigned int asUint( const std::string& optname) const
	{
		int rt = asInt( optname);
		if (rt < 0) throw strus::runtime_error( _TXT("non negative value expected for option '%s'"), optname.c_str());
		return (unsigned int)rt;
	}
    void animation_converter::run() {
        for (auto it = root_.begin(); it != root_.end(); ++it) {
            std::string model_name = it.key().asString();
            auto& value = *it;

            std::unordered_map<int, bone> bone_hierachy;
            auto skeleton = value["skeleton"];
            if (skeleton.isNull()) {
                throw std::runtime_error("no skeleton data in " + model_name);
            }
            for (auto& b : skeleton) {
                bone bn;

                auto id = b["id"];
                if (id.isNull()) {
                    throw std::runtime_error("no id attribute in bone data of " + model_name);
                }
                bn.id = id.asInt();

                auto parent = b["parent"];
                if (parent.isNull()) {
                    bn.parent = -1;
                } else {
                    bn.parent = parent.asInt();
                }

                auto translation = b["translation"];
                if (translation.isNull()) {
                    throw std::runtime_error("no translation attribute in bone data of " + model_name);
                }
                if (translation.size() != 3) {
                    throw std::runtime_error("translation attribute has not the apropriate size in " + model_name);
                }
                auto trans = glm::vec3{translation[0].asFloat(), translation[1].asFloat(), translation[2].asFloat()};

                auto rotation = b["rotation"];
                if (rotation.isNull()) {
                    throw std::runtime_error("no rotation attribute in bone data of " + model_name);
                }
                if (rotation.size() != 4) {
                    throw std::runtime_error("rotation attribute has not the apropriate size in " + model_name);
                }
                auto rot = glm::quat{rotation[0].asFloat(), rotation[1].asFloat(), rotation[2].asFloat(), rotation[3].asFloat()};
                rot = glm::normalize(rot);

                auto transform = glm::toMat4(rot);
                transform[3].x = trans.x;
                transform[3].y = trans.y;
                transform[3].z = trans.z;

                static auto offset = glm::angleAxis(glm::radians(-90.f), glm::vec3{1.f, 0.f, 0.f});
                static auto offset_matrix = glm::toMat4(offset);
                static auto offset_matrix_t = glm::transpose(offset_matrix);

                transform = offset_matrix * transform * offset_matrix_t;

                bn.relative_transform = transform;
                bn.absolute_transform = transform;

                bone_hierachy.insert(std::make_pair(bn.id, bn));
            }

            /*
            for (auto i = 0; i < bone_hierachy.size(); ++i) {
                auto parent = bone_hierachy[i].parent;
                if (parent != -1) {
                    bone_hierachy[i].absolute_transform = bone_hierachy[parent].absolute_transform * bone_hierachy[i].absolute_transform;
                }
            }
            */
            std::stack<int32_t> traversal;
            traversal.push(0);
            while (!traversal.empty()) {
                auto current = traversal.top();
                traversal.pop();
                auto node = value["bone_hierachy"][std::to_string(current)];
                if (node.isNull()) {
                    continue;
                }
                for (auto& child : node) {
                    auto c = child.asInt();
                    traversal.push(c);
                    bone_hierachy[c].absolute_transform = bone_hierachy[current].absolute_transform * bone_hierachy[c].absolute_transform;
                }
            }

            std::vector<bone> bones;
            for (auto i = 0ul; i < bone_hierachy.size(); ++i) {
                bone_hierachy[i].absolute_transform = glm::inverse(bone_hierachy[i].absolute_transform);
                bones.emplace_back(bone_hierachy[i]);
            }

            auto animations = value["animations"];
            if (animations.isNull()) {
                throw std::runtime_error("no animation data in " + model_name);
            }

            header h;
            h.bone_count = bones.size();
            h.animation_count = animations.size();

            std::string output_file = output_path_ + "anims/" + model_name + ".skl";
            std::ofstream output(output_file, std::ios::binary | std::ios::trunc);
            if (!output.is_open()) {
                throw std::runtime_error("could not open output file " + output_file);
            }

            std::vector<animation> anims;
            std::vector<track> all_tracks;
            std::vector<translation_keyframe> all_tkeys;
            std::vector<rotation_keyframe> all_qkeys;
            std::vector<scale_keyframe> all_skeys;
            for (auto at = animations.begin(); at != animations.end(); ++at) {
                animation a;
                a.name = at.key().asString();

                auto& anim = *at;
                auto length = anim["length"];
                if (length.isNull()) {
                    throw std::runtime_error("animation " + a.name + " has no length attribute");
                }
                a.length = length.asFloat();

                auto tracks = anim["tracks"];
                if (tracks.isNull()) {
                    throw std::runtime_error("animation " + a.name + " has no tracks");
                }
                a.track_count = tracks.size();

                anims.emplace_back(a);

                for (auto tt = tracks.begin(); tt != tracks.end(); ++tt) {
                    auto bone_name = tt.key().asString();

                    auto& anim_track = *tt;


                    auto bone_id = anim_track["id"];
                    if (bone_id.isNull()) {
                        throw std::runtime_error("track " + bone_name + " in animation " + a.name + " has no id");
                    }
                    auto& b = bone_hierachy[bone_id.asInt()];

                    track t;
                    t.id = b.id;
                    t.parent = b.parent;

                    auto tkeys = anim_track["location"];
                    if (tkeys.isNull()) {
                        throw std::runtime_error("track " + bone_name + " in animation " + a.name + " has no translation keys");
                    }
                    t.tkey_count = tkeys.size();

                    auto qkeys = anim_track["rotation_quaternion"];
                    if (qkeys.isNull()) {
                        throw std::runtime_error("track " + bone_name + " in animation " + a.name + " has no rotation keys");
                    }
                    t.qkey_count = qkeys.size();

                    auto skeys = anim_track["scale"];
                    if (skeys.isNull()) {
                        throw std::runtime_error("track " + bone_name + " in animation " + a.name + " has no scale keys");
                    }
                    t.skey_count = skeys.size();

                    all_tracks.emplace_back(t);
                }

                for (auto tt = tracks.begin(); tt != tracks.end(); ++tt) {
                    auto bone_name = tt.key().asString();

                    auto& anim_track = *tt;

                    auto tkeys = anim_track["location"];
                    for (auto& tkey : tkeys) {
                        auto frame = tkey["frame"];
                        if (frame.isNull()) {
                            throw std::runtime_error("track " + bone_name + " in animations " + a.name + " has no frame number in keyframe");
                        }

                        auto data = tkey["data"];
                        if (data.isNull()) {
                            throw std::runtime_error("track " + bone_name + " in animation " + a.name + " has no data in keframe " +  frame.asString());
                        }
                        if (data.size() != 3) {
                            throw std::runtime_error("data in keyframe " + frame.asString() + " in track " + bone_name + " in animation " + a.name + " is too small");
                        }

                        translation_keyframe tk;
                        tk.time = frame.asFloat();
                        tk.translate = glm::vec3{data[0].asFloat(), data[2].asFloat(), -data[1].asFloat()};

                        all_tkeys.emplace_back(tk);
                    }

                    auto qkeys = anim_track["rotation_quaternion"];
                    for (auto& qkey : qkeys) {
                        auto frame = qkey["frame"];
                        if (frame.isNull()) {
                            throw std::runtime_error("track " + bone_name + " in animations " + a.name + " has no frame number in keyframe");
                        }

                        auto data = qkey["data"];
                        if (data.isNull()) {
                            throw std::runtime_error("track " + bone_name + " in animation " + a.name + " has no data in keframe " +  frame.asString());
                        }
                        if (data.size() != 4) {
                            throw std::runtime_error("data in keyframe " + frame.asString() + " in track " + bone_name + " in animation " + a.name + " is too small");
                        }

                        rotation_keyframe rk;
                        rk.time = frame.asFloat();
                        rk.rotate = glm::quat{data[0].asFloat(), data[1].asFloat(), data[2].asFloat(), data[3].asFloat()};

                        static auto offset = glm::angleAxis(glm::radians(-90.f), glm::vec3{1.f, 0.f, 0.f});
                        static auto offset_matrix = glm::toMat4(offset);
                        static auto offset_matrix_t = glm::transpose(offset_matrix);
                        auto rotation_matrix = glm::toMat4(rk.rotate);
                        rotation_matrix = offset_matrix * rotation_matrix * offset_matrix_t;
                        rk.rotate = glm::quat_cast(rotation_matrix);

                        all_qkeys.emplace_back(rk);
                    }

                    auto skeys = anim_track["scale"];
                    for (auto& skey : skeys) {
                        auto frame = skey["frame"];
                        if (frame.isNull()) {
                            throw std::runtime_error("track " + bone_name + " in animations " + a.name + " has no frame number in keyframe");
                        }

                        auto data = skey["data"];
                        if (data.isNull()) {
                            throw std::runtime_error("track " + bone_name + " in animation " + a.name + " has no data in keframe " +  frame.asString());
                        }
                        if (data.size() != 3) {
                            throw std::runtime_error("data in keyframe " + frame.asString() + " in track " + bone_name + " in animation " + a.name + " is too small");
                        }

                        scale_keyframe sk;
                        sk.time = frame.asFloat();
                        sk.scale = glm::vec3{data[0].asFloat(), data[2].asFloat(), -data[1].asFloat()};

                        all_skeys.emplace_back(sk);
                    }
                }
            }

            auto animation_size = 20 + sizeof(float) + sizeof(int64_t);

            auto bone_count = int(h.bone_count);
            h.size = sizeof(header)
                + bone_count * sizeof(bone)
                + bone_count * sizeof(node) + (bone_count - 1) * sizeof(int32_t)
                + h.animation_count * animation_size
                + all_tracks.size() *  sizeof(track)
                + all_tkeys.size() * sizeof(translation_keyframe)
                + all_qkeys.size() * sizeof(rotation_keyframe)
                + all_skeys.size() * sizeof(scale_keyframe);

            output.write(reinterpret_cast<char*>(&h), sizeof(header));
            output.write(reinterpret_cast<char*>(bones.data()), bones.size() * sizeof(bone));

            auto stuff = 0ul;
            for (auto i = 0ul; i < value["bone_hierachy"].size(); ++i) {
                node n;
                n.id = i;
                auto children = value["bone_hierachy"][std::to_string(i)];
                n.children_count = children.size();
                output.write(reinterpret_cast<char*>(&n), sizeof(node));
                stuff += sizeof(node);
                for (auto& child : children) {
                    output.write(reinterpret_cast<char*>(&child), sizeof(int32_t));
                    stuff += sizeof(int32_t);
                }
            }

            auto track_ptr = 0ul;
            auto tkey_ptr = 0ul;
            auto qkey_ptr = 0ul;
            auto skey_ptr = 0ul;
            for (auto& a : anims) {
                if (a.name.size() < 20) {
                    output.write(a.name.c_str(), a.name.size() * sizeof(char));
                    for (auto i = 0ul; i < 20 - a.name.size(); ++i) {
                        output.write("\0", sizeof(char));
                    }
                } else {
                    output.write(a.name.c_str(), 20 * sizeof(char));
                }
                output.write(reinterpret_cast<char*>(&a.length), sizeof(float));
                output.write(reinterpret_cast<char*>(&a.track_count), sizeof(size_t));

                for (auto i = uint64_t{0}; i < a.track_count; ++i) {
                    auto& t = all_tracks[track_ptr + i];
                    output.write(reinterpret_cast<char*>(&t), sizeof(track));

                    for (auto i = 0ul; i < t.tkey_count; ++i) {
                        output.write(reinterpret_cast<char*>(&all_tkeys[tkey_ptr + i]), sizeof(translation_keyframe));
                    }
                    tkey_ptr += t.tkey_count;

                    for (auto j = 0ul; j < t.qkey_count; ++j) {
                        if (j > 0) {
                            auto& q1 = all_qkeys[qkey_ptr + j - 1].rotate;
                            auto& q2 = all_qkeys[qkey_ptr + j].rotate;
                            auto scalar = glm::dot(q1, q2);
                            if (scalar < 0.f) {
                                q2 = -q2;
                            }
                        }
                        output.write(reinterpret_cast<char*>(&all_qkeys[qkey_ptr + j]), sizeof(rotation_keyframe));
                    }
                    qkey_ptr += t.qkey_count;

                    for (auto k = 0ul; k < t.skey_count; ++k) {
                        output.write(reinterpret_cast<char*>(&all_skeys[skey_ptr + k]), sizeof(scale_keyframe));
                    }
                    skey_ptr += t.skey_count;
                }
                track_ptr += a.track_count;
            }
        }
    }
Exemple #26
0
static Bool ascii85EncodeBuffer( FILELIST *filter )
{
  register FILELIST *uflptr ;
  register int32    count , i ;
  register uint32   c ;
  register uint32   *ptr ;
  FOURBYTES         fb ;
  FOURBYTES         out ; /* high order bytes of the output 5-tuple */

  HQASSERT( filter , "filter NULL in ascii85EncodeBuffer." ) ;

  count = theICount( filter ) ;
  uflptr = theIUnderFile( filter ) ;
  ptr = ( uint32 * )theIBuffer( filter ) ;

  if ( ! count && ! isIClosing( filter ))
    return TRUE ;

  HQASSERT( uflptr , "uflptr NULL in ascii85EncodeBuffer." ) ;

  if ( ! isIOpenFileFilterById( theIUnderFilterId( filter ) , uflptr ))
    return error_handler( IOERROR ) ;

  HQASSERT( ptr , "ptr NULL in ascii85EncodeBuffer." ) ;

  while ( count >= 4 ) {
    asInt( fb ) = *ptr ;
    HighOrder4Bytes( asBytes( fb )) ;

    c = asInt( fb ) / POWER4 ;
    asInt( fb ) -= c * POWER4 ;
    asBytes( out )[ 0 ] = ( uint8 )c ;
    c = asInt( fb ) / POWER3 ;
    asInt( fb ) -= c * POWER3 ;
    asBytes( out )[ 1 ] = ( uint8 )c ;
    c = asInt( fb ) / POWER2 ;
    asInt( fb ) -= c * POWER2 ;
    asBytes( out )[ 2 ] = ( uint8 )c ;
    c = asInt( fb ) / POWER1 ;
    asInt( fb ) -= c * POWER1 ;
    asBytes( out )[ 3 ] = ( uint8 )c ;

    if (( asInt( out ) == 0 ) && ( asInt( fb ) == 0 )) { /* output 'z' */
      if ( Putc( 'z' , uflptr ) == EOF )
        return error_handler( IOERROR ) ;
      theIFilterState( filter )++ ;
    } else { /* output five chars */
      for ( i = 0 ; i < 4 ; i++ ) {
        c = ( uint32 )asBytes( out )[ i ] + 33 ;
        if ( Putc( c , uflptr ) == EOF )
          return error_handler( IOERROR ) ;
      }
      c = asInt( fb ) + 33 ;
      if ( Putc( c , uflptr ) == EOF )
        return error_handler( IOERROR ) ;
      theIFilterState( filter ) += 5 ;
    }
    if ( theIFilterState( filter ) >= 65 ) {
      theIFilterState( filter ) = 0 ;
      if ( Putc( '\n' , uflptr ) == EOF )
        return error_handler( IOERROR ) ;
    }

    count -= 4 ; ptr++ ;
  }

  /* Copy remaining bytes (1, 2 or 3) to start of buffer. */

  if ( count )
    *(( uint32 * )theIBuffer( filter )) = *ptr ;

  if ( isIClosing( filter )) {
    if ( count > 0 ) {
      FOURBYTES fb ;
      FOURBYTES out ;
      uint32 i ;
      uint32 c ;

      /* There may be a faster way to do this, but my brain is suffering
       * enough. This conversion is only required once for the end of the
       * filter, and it is not worthwhile optimizing it. The problem
       * is that the bytes chopped off the end of the 5-tuple, may have
       * caused a carry when converted back to base-256. The description on
       * p.129 is oversimplified.
       */

      asInt( fb ) = 0 ;
      for ( i = 0 ; ( int32 )i < count ; i++ )
        asBytes( fb )[ BYTE_INDEX( i ) ] = theIBuffer( filter )[ i ] ;
      c = asInt( fb ) / POWER4 ;
      asInt( fb ) -= c * POWER4 ;
      asBytes( out )[ 0 ] = ( uint8 )c ;
      c = asInt( fb ) / POWER3 ;
      asInt( fb ) -= c * POWER3 ;
      asBytes( out )[ 1 ] = ( uint8 )c ;
      c = asInt( fb ) / POWER2 ;
      asInt( fb ) -= c * POWER2 ;
      asBytes( out )[ 2 ] = ( uint8 )c ;
      c = asInt( fb ) / POWER1 ;
      asInt( fb ) -= c * POWER1 ;
      asBytes( out )[ 3 ] = ( uint8 )c ;

      for ( i = 0 ; ( int32 )i <= count ; i++ ) {
        c = ( uint32 ) asBytes( out )[ i ] + 33 ;
        if ( Putc( c , uflptr ) == EOF )
          return error_handler( IOERROR ) ;
      }
    }

    if (( Putc( '~' , uflptr ) == EOF ) ||
        ( Putc( '>' , uflptr ) == EOF ))
      return error_handler( IOERROR ) ;
  }
  else {
    theICount( filter ) = count ;
    theIPtr( filter ) = theIBuffer( filter ) + count ;
  }

  return TRUE ;
}
Exemple #27
0
/**
 * This routine gets characters from the filter's underlying file, and
 * decodes them according to the ascii85 scheme. It returns the number
 * of bytes placed into the filter's buffer through the ret_bytes arguments.
 * This number is negative if the EOD is found.
 * It returns FALSE if anything goes wrong.
 *
 * \param[in,out]  filter       Input and output streams for the filter
 * \param[out]     ret_bytes    Number of bytes placed in output buffer
 *                              (negative if EOD found)
 * \return                      Success status
 */
static Bool ascii85DecodeBuffer(FILELIST *filter, int32 *ret_bytes)
{
  ASCII85DECODESTATE *ascii85state ;
  uint32    *ptr, *end;
  int32     i5, nbytes;
  FILELIST  *in;
  FOURBYTES  fb;

  HQASSERT(filter, "NULL /ASCII85Decode filter");
  ascii85state = theIFilterPrivate( filter ) ;
  HQASSERT( ascii85state, "ascii85state NULL in ascii85DecodeBuffer." ) ;

  if (ascii85state->cached_error != NOT_AN_ERROR)
    return error_handler( ascii85state->cached_error ) ;

  in = filter->underlying_file;
  ptr = (uint32 *)(filter->buffer);
  end = ptr + (filter->buffersize/sizeof(uint32));
  asInt(fb) = 0;

  HQASSERT(in, "NULL /ASCII85Decode input buffer");
  HQASSERT(ptr,  "NULL /ASCII85Decode output buffer");

  for ( i5 = 0, nbytes = 0; ptr < end; )
  {
    /*
     * Optimised code for the typical case :
     *
     * 0xffffffff (ascii85)-> s8W-! == 82/23/54/12/0
     * So if the first byte is less than 's'
     * then we do not need to test for overflow
     */
    if ( i5 == 0 && in->count > 5 && in->ptr[0] >= '!' && in->ptr[0] < 's' &&
         IS85(in->ptr[1]) && IS85(in->ptr[2]) &&
         IS85(in->ptr[3]) && IS85(in->ptr[4]) )
    {
      FOURBYTES  b4;

      asInt(b4) = POWER4 * (uint32)(in->ptr[0] - 33) +
                  POWER3 * (uint32)(in->ptr[1] - 33) +
                  POWER2 * (uint32)(in->ptr[2] - 33) +
                  POWER1 * (uint32)(in->ptr[3] - 33) +
                           (uint32)(in->ptr[4] - 33);

      HighOrder4Bytes(asBytes(b4));
      *ptr++ = asInt(b4);
      in->count -= 5;
      in->ptr   += 5;
    }
    else
    {
      register int32 ch = Getc(in);

      if ( IS85(ch) ) /* Part of valid ascii85 5-tuple */
      {
        if ( i5 == 4 )
        {
          if ( asInt(fb) > MAXHIGH4BYTES )
            return error_handler(IOERROR);
          asInt(fb) = POWER4 * (uint32)asBytes(fb)[BYTE_INDEX(0)] +
                      POWER3 * (uint32)asBytes(fb)[BYTE_INDEX(1)] +
                      POWER2 * (uint32)asBytes(fb)[BYTE_INDEX(2)] +
                      POWER1 * (uint32)asBytes(fb)[BYTE_INDEX(3)] +
                               (uint32)(ch - 33);
          HighOrder4Bytes(asBytes(fb));
          *ptr++ = asInt(fb);
          i5 = 0;
          asInt(fb) = 0;
        }
        else
          asBytes(fb)[BYTE_INDEX(i5++)] = (uint8)(ch - 33);
      }
      else if ( ch == 'z') /* special zero case */
      {
        if ( i5 != 0 )
          return error_handler(IOERROR);
        *ptr++ = 0;
      }
      else if ((ch == EOF ) || ( ch == '~' )) /* found EOD marker */
      {
        nbytes = (int32)(sizeof(uint32)*(ptr - (uint32 *)(filter->buffer)));

        if ( isIIOError(in) )
          return FALSE;
        if ( ch == '~' )
        {
          do
          {
            ch = Getc(in);
          } while ( IsWhiteSpace(ch) );

          if ( ch != '>')
            return error_handler(IOERROR);
        }
        if ( i5 > 0 ) /* only partial 5-tuple */
        {
          if ( i5 == 1 )
            return delay_filter_error(ascii85state, IOERROR, ret_bytes, nbytes);
          if ( asInt( fb ) > MAXHIGH4BYTES )
            return error_handler( IOERROR );
          asInt(fb) = POWER4 * (uint32)asBytes(fb)[BYTE_INDEX(0)] +
                      POWER3 * (uint32)asBytes(fb)[BYTE_INDEX(1)] +
                      POWER2 * (uint32)asBytes(fb)[BYTE_INDEX(2)] +
                      POWER1 * (uint32)asBytes(fb)[BYTE_INDEX(3)];
          if ( (int32)asBytes(fb)[BYTE_INDEX(i5 - 1)] >= 128 ) /* carry 1 */
            asInt(fb) += (uint32) (1 << (( 4 - i5 + 1 ) * 8 ));
          HighOrder4Bytes(asBytes(fb));
          *ptr++ = asInt(fb);
          nbytes = -(nbytes + i5 - 1);
        }
        else
          nbytes = -nbytes;
        break;
      }
      else if ( !IsWhiteSpace(ch) ) /* skip spaces, everything else errors */
        return error_handler(IOERROR);
    }
  }
  if ( nbytes == 0 )
    nbytes = (int32)(sizeof(uint32)*(ptr - (uint32 *)(filter->buffer)));
  *ret_bytes = nbytes;
  return TRUE;
}
Exemple #28
0
bool Storage::reload()
{
	storageFilePath_.clear();
	logSocketPath_.clear();
	binariesPath_.clear();
	prefixByName_.clear();
	loaderByName_.clear();
	linkByPath_.clear();

	// Add default WINE prefix
	std::string name = "default";
	std::string path = FileSystem::realPath("~") + "/.wine";
	prefixByName_.emplace(makePair(name, path));

	// Add default WINE loader
	name = "default";
	path = FileSystem::fullNameFromPath("wine");
	loaderByName_.emplace(makePair(name, path));

	// Initialize default values
	binariesPath_ = INSTALL_PREFIX "/bin";

	const char* string = getenv("TMPDIR");
	std::string tempPath = string ? string : "/tmp";
	logSocketPath_ = tempPath + "/" PROJECT_NAME ".sock";

	defaultLogLevel_ = LogLevel::kTrace;

	// Find and read a configuration file
	string = getenv("XDG_CONFIG_PATH");
	std::string configPath = string ? string : std::string();
	if(configPath.empty())
		configPath = "~/.config";

	configPath = FileSystem::realPath(configPath);
	if(configPath.back() != '/')
		configPath += '/';

	if(!FileSystem::isDirExists(configPath))
		return false;

	storageFilePath_ = configPath + PROJECT_NAME "/" PROJECT_NAME ".conf";

	std::ifstream file(storageFilePath_);
	if(!file.is_open())
		return false;

	Json::Value root;
	Json::Reader reader;
	if(!reader.parse(file, root, false))
		return false;

	// Load general variables
	auto value = root["binaries_path"];
	if(!value.isNull())
		binariesPath_ = value.asString();

	value = root["log_socket_path"];
	if(!value.isNull())
		logSocketPath_ = value.asString();

	value = root["default_log_level"];
	if(!value.isNull()) {
		defaultLogLevel_ = static_cast<LogLevel>(value.asInt());
		if(defaultLogLevel_ < LogLevel::kQuiet || defaultLogLevel_ > LogLevel::kFlood)
			defaultLogLevel_ = LogLevel::kTrace;
	}

	// Load prefixes
	Json::Value prefixes = root["prefixes"];
	for(uint i = 0; i < prefixes.size(); ++i) {
		Json::Value prefix = prefixes[i];

		name = prefix["name"].asString();
		path = prefix["path"].asString();

		if(name.empty() || path.empty())
			continue;

		prefixByName_.emplace(makePair(name, path));
	}

	// Load loaders
	Json::Value loaders = root["loaders"];
	for(uint i = 0; i < loaders.size(); ++i) {
		Json::Value loader = loaders[i];

		name = loader["name"].asString();
		path = loader["path"].asString();

		if(name.empty() || path.empty())
			continue;

		loaderByName_.emplace(makePair(name, path));
	}

	// Load links
	Json::Value links = root["links"];
	for(uint i = 0; i < links.size(); ++i) {
		Json::Value link = links[i];

		LinkInfo info;
		info.target = link["target"].asString();

		info.loader = link["loader"].asString();
		if(info.loader.empty())
			info.loader = "default;";

		info.prefix = link["prefix"].asString();
		if(info.prefix.empty())
			info.prefix = "default;";

		auto value = link["log_level"];
		if(value.isNull()) {
			info.level = LogLevel::kDefault;
		}
		else {
			info.level = static_cast<LogLevel>(value.asInt());
			if(info.level < LogLevel::kDefault || info.level > LogLevel::kFlood)
				info.level = LogLevel::kDefault;
		}

		path = link["path"].asString();
		linkByPath_.emplace(makePair(path, info));
	}

	return true;
}
Exemple #29
0
   void YumaData::reallyGetRecord(FFStream& ffs) 
      throw(std::exception, FFStreamError, 
               gpstk::StringUtils::StringException)  
   {
      YumaStream& strm = dynamic_cast<YumaStream&>(ffs);
            
      string line;
 
      // We don't need first line as we will get all the information from the others
      strm.formattedGetLine(line, true);
      
      //Second Line - PRN
      strm.formattedGetLine(line, true);
      stripLeading( line, sID );
      PRN = asInt(line);

      //Third Line - Satellite Health
      strm.formattedGetLine(line, true);
      stripLeading( line, sHlth ); 
      SV_health = asInt(line);
      
      //Fourth Line - Eccentricity
      strm.formattedGetLine(line, true);
      stripLeading( line, sEcc ); 
      ecc = asDouble(line);

      //Fifth Line - Time of Applicability
      strm.formattedGetLine(line, true);
      stripLeading( line, sTOA ); 
      double dToa = asDouble(line);
      Toa = (long) dToa;

      //Sixth Line - Orbital Inclination
      strm.formattedGetLine(line, true);
      stripLeading( line, sOrbI ); 
      double i_total = asDouble(line);
      i_offset = i_total - 54.0 * (gpstk::PI / 180.0);
      
      //Seventh Line - Rate of Right Ascen
      strm.formattedGetLine(line, true);
      stripLeading( line, sRRA ); 
      OMEGAdot = asDouble(line);
      
      //Eigth Line - SqrtA
      strm.formattedGetLine(line, true);
      stripLeading( line, sSqrA ); 
      Ahalf = asDouble(line);
      
      //Ninth Line - Right Ascen at Week
      strm.formattedGetLine(line, true);
      stripLeading( line, sRtAs ); 
      OMEGA0 = asDouble(line);
      
      //Tenth Line - Argument of Perigee
      strm.formattedGetLine(line, true);
      stripLeading( line, sArgP ); 
      w = asDouble(line);
      
      //Eleventh Line - Mean Anomaly
      strm.formattedGetLine(line, true);
      stripLeading( line, sMnAn ); 
      M0 = asDouble(line);
      
      //Twelfth Line - Af0
      strm.formattedGetLine(line, true);
      stripLeading( line, sAf0 ); 
      AF0 = asDouble(line);
      
      //Thirteenth Line - Af1
      strm.formattedGetLine(line, true);
      stripLeading( line, sAf1 ); 
      AF1 = asDouble(line);
      
      //Fourteenth Line - week
      strm.formattedGetLine(line, true);
      stripLeading( line, sweek ); 
      int epoch_week = asInt(line);
      week = epoch_week + 1024;                    // Need a way to set epoch     Do we??
      
      xmit_time = 0;
      strm.formattedGetLine(line,true);
      
   } // end of reallyGetRecord()
Exemple #30
0
      // this function parses a single header record
   void Rinex3ClockHeader::ParseHeaderRecord(string& line)
      throw(FFStreamError)
   {

      string label(line, 60, 20);

         // RINEX VERSION / TYPE
      if ( label == versionString )
      {

         version  =  asDouble(line.substr(0,9));
         fileType =  strip(line.substr(20, 20));

            // check version
         if ( version <= 0.0 ||
              version > 3.0 )
         {
            FFStreamError e( "This isn't an anticipated version number." +
                              asString(version) );
            GPSTK_THROW(e);
         }

            // check type
         if ( (fileType[0] != 'C') &&
              (fileType[0] != 'c'))
         {
            FFStreamError e( "This isn't a Rinex3 Clock file type." );
            GPSTK_THROW(e);
         }

            // get satellite system
         string system_str = strip(line.substr(40, 20));
         try
         {
            system.fromString(system_str);
         }
         catch (Exception& e)
         {
            FFStreamError ffse( "Input satellite system is unsupported: "
                                 + system_str + e.getText() );
            GPSTK_THROW(ffse);
         }

         valid |= versionValid;

      }
         // PGM / RUN BY / DATE
      else if ( label == runByString )
      {

         fileProgram =  strip(line.substr( 0, 20));
         fileAgency  =  strip(line.substr(20, 20));
         date        =  strip(line.substr(40, 20));
         isPGM = true;

         valid |= runByValid;

      }
         // COMMENT
      else if ( label == commentString )
      {

         string s = strip(line.substr(0, 60));
         commentList.push_back(s);

         valid |= commentValid;

      }
         // SYS / # / OBS TYPES
      else if ( label == numObsString )
      {

         numObsTyp   =  asInt( line.substr(3,3) );

         // TODO: more work needed

         valid |= numObsValid;

      }
         // TIME SYSTEM ID
      else if ( label == timeSystemString )
      {

         timeSystem = line.substr(3,3);
         valid |= timeSystemValid;

      }
         // LEAP SECONDS
      else if ( label == leapSecondsString )
      {

         leapSeconds = asInt(line.substr(0,6));

         valid |= leapSecondsValid;

      }
         // DCBS APPLIED
      else if ( label == sysDCBString )
      {

         valid |= sysDCBsValid;

      }
         // PCVS APPLIED
      else if ( label == sysPCVString )
      {

         valid |= sysPCVsValid;

      }
         // # / TYPES OF DATA
      else if ( label == dataTypesString )
      {

            // number of clock data types
         int nTyp = asInt(line.substr(0,6));
            // allocate memory
         dataTypeList.resize(nTyp);
            // add clock data types
         for( int iTyp = 0; iTyp < nTyp; iTyp++ )
         {
            dataTypeList[iTyp] = strip( line.substr(6*(iTyp+1),6) );
         }

         valid |= dataTypesValid;

      }
         // STATION NAME / NUM
      else if ( label == stationNameString )
      {

         clk0Name = line.substr(0,4);

         valid |= stationNameValid;

      }
         // STATION CLK REF
      else if ( label == calibrationClkString )
      {
         calName = strip( line.substr(0,60) );

         valid |= calibrationClkValid;

      }
         // ANALYSIS CENTER
      else if ( label == acNameString )
      {

         ac       =  line.substr(0, 3);
         acName   =  strip(line.substr(5,55));
         isAC     =  true;

         valid |= acNameValid;

      }
         // # OF CLK REF
      else if ( label == numRefClkString )
      {

            // new reference clock record
         RefClkRecord ref;
            // get the number of reference clocks for this record
         ref.nRef = asInt( line.substr(0,6) );
            // epoch
         if( asInt(line.substr(7,4)) )
         {
            CommonTime T0 = parseTime( line.substr(7,26) );
               // only one time
            if( timeFirst == CommonTime::BEGINNING_OF_TIME )
            {
               timeFirst = T0;
            }
               // left boundary
            ref.refWin[0] = T0 - timeFirst;
               // right boundary
            T0 = parseTime( line.substr(34,26) );
            ref.refWin[1] = T0 - timeFirst;

               // time inconsistency
            if (T0 < timeFirst)
            {
               FFStreamError e( "Wrong epoch of file, expected epoch: " +
                                 timeFirst.asString() + " detected epoch: " +
                                 T0.asString() );
               GPSTK_THROW(e);
            }
         }

            // add the ref clk record to the list
         refClkList.push_back(ref);

         valid |= numRefClkValid;

      }
         /// ANALYSIS CLK REF
      else if ( label == analysisClkRefString )
      {

            // get the previous reference clock record
         std::list<RefClkRecord>::iterator iRef = refClkList.end();
         --iRef;

            // how many ref clk have been stored
         size_t nClks = iRef->clk.size();

            // is there any inconsistency?
         if ( nClks < iRef->nRef )
         {

            RefClk refclk;
               // reference clock info
            refclk.name    =  line.substr(0,4);
            refclk.sigma   =  asDouble( strip( line.substr(40,20) ) );
            refclk.sigma   *= 1e6; // ms^2
               // add into the list
            iRef->clk.push_back(refclk);

         }
         else
         {
            FFStreamError e( string("Number of items found in header ") +
                             "is inconsitent to the entry in header" );
            GPSTK_THROW(e);
         }

         valid |= analysisClkRefValid;

      }
         /// # OF SOLN STA / TRF
      else if ( label == numStationsString )
      {

         numSta   =  asInt(line.substr( 0,  6));
         trfName  =  strip(line.substr(10, 50));

         valid |= numStationsValid;

      }
         /// SOLN STA NAME / NUM
      else if ( label == solnStaNameString )
      {

            // get 4-character station name
         string name = line.substr(0,4);
            // add it into the list
         clkNameList.push_back( name );

            // get integer & decimal part of the coordinates
         int X    =  asInt( strip(line.substr(25,8)) );
         int Xf   =  asInt( strip(line.substr(33,3)) );

         int Y    =  asInt( strip(line.substr(37,8)) );
         int Yf   =  asInt( strip(line.substr(45,3)) );

         int Z    =  asInt( strip(line.substr(49,8)) );
         int Zf   =  asInt( strip(line.substr(57,3)) );

            // geocentric coordinates (be careful to the sign)
         double x = X>0 ? X*1.0+Xf*1e-3 : X*1.0-Xf*1e-3;
         double y = Y>0 ? Y*1.0+Yf*1e-3 : Y*1.0-Yf*1e-3;
         double z = Z>0 ? Z*1.0+Zf*1e-3 : Z*1.0-Zf*1e-3;

            // check the coordinates
         double radius = std::sqrt(x*x+y*y+z*z);
            // add them into the map
         if (radius >= 5000.0e3 && radius < 12000.0e3)
         {
            staCoordList.push_back( Triple(X,Y,Z) );
         }
         else
         {
            staCoordList.push_back( Triple(0.0,0.0,0.0) );
         }

         valid |= solnStaNameValid;

      }
         // # OF SOLN SATS
      else if ( label == numSatsString )
      {

         numSVs = asInt(line.substr(0,6));

         valid |= numSatsValid;

      }
         // PRN LIST
      else if ( label == prnListString )
      {

         string s    =  line.substr(0,60);
         string word =  stripFirstWord(s);

         while ( !word.empty() )
         {
            clkNameList.push_back( word.append(" ") );
            word = stripFirstWord(s);
         }

         valid |= prnListValid;

      }
         // END OF HEADER
      else if ( label == endOfHeader )
      {

         valid |= endValid;

      }
      else
      {

         FFStreamError e("Unidentified label: " + label);
         GPSTK_THROW(e);

      }

      return;

   }   // End of method 'Rinex3ClockHeader::ParseHeaderRecord(string& line)'