Example #1
0
ValueType getSystemVar(const EERIE_SCRIPT * es, Entity * entity, const std::string & name,
                       std::string& txtcontent, float * fcontent,long * lcontent) {
	
	arx_assert(!name.empty() && name[0] == '^', "bad system variable: \"%s\"", name.c_str());
	
	char c = (name.length() < 2) ? '\0' : name[1];
	switch(c) {
		
		case '$': {
			
			if(name == "^$param1") {
				txtcontent = SSEPARAMS[0];
				return TYPE_TEXT;
			}
			
			if(name == "^$param2") {
				txtcontent = SSEPARAMS[1];
				return TYPE_TEXT;
			}
			
			if(name == "^$param3") {
				txtcontent = SSEPARAMS[2];
				return TYPE_TEXT;
			}
			
			if(name == "^$objontop") {
				txtcontent = "none";
				if(entity) {
					MakeTopObjString(entity, txtcontent);
				}
				return TYPE_TEXT;
			}
			
			break;
		}
		
		case '&': {
			
			if(name == "^&param1") {
				*fcontent = (float)atof(SSEPARAMS[0]);
				return TYPE_FLOAT;
			}
			
			if(name == "^&param2") {
				*fcontent = (float)atof(SSEPARAMS[1]);
				return TYPE_FLOAT;
			}
			
			if(name == "^&param3") {
				*fcontent = (float)atof(SSEPARAMS[2]);
				return TYPE_FLOAT;
			}
			
			if(name == "^&playerdist") {
				if(entity) {
					*fcontent = fdist(player.pos, entity->pos);
					return TYPE_FLOAT;
				}
			}
			
			break;
		}
		
		case '#': {
			
			if(name == "^#playerdist") {
				if(entity) {
					*lcontent = (long)fdist(player.pos, entity->pos);
					return TYPE_LONG;
				}
			}
			
			if(name == "^#param1") {
				*lcontent = atol(SSEPARAMS[0]);
				return TYPE_LONG;
			}
			
			if(name == "^#param2") {
				*lcontent = atol(SSEPARAMS[1]);
				return TYPE_LONG;
			}
			
			if(name == "^#param3") {
				*lcontent = atol(SSEPARAMS[2]);
				return TYPE_LONG;
			}
			
			if(name == "^#timer1") {
				if(!entity || entity->script.timers[0] == 0) {
					*lcontent = 0;
				} else {
					*lcontent = long((unsigned long)(arxtime) - es->timers[0]);
				}
				return TYPE_LONG;
			}
			
			if(name == "^#timer2") {
				if(!entity || entity->script.timers[1] == 0) {
					*lcontent = 0;
				} else {
					*lcontent = long((unsigned long)(arxtime) - es->timers[1]);
				}
				return TYPE_LONG;
			}
			
			if(name == "^#timer3") {
				if(!entity || entity->script.timers[2] == 0) {
					*lcontent = 0;
				} else {
					*lcontent = long((unsigned long)(arxtime) - es->timers[2]);
				}
				return TYPE_LONG;
			}
			
			if(name == "^#timer4") {
				if(!entity || entity->script.timers[3] == 0) {
					*lcontent = 0;
				} else {
					*lcontent = long((unsigned long)(arxtime) - es->timers[3]);
				}
				return TYPE_LONG;
			}
			
			break;
		}
		
		case 'g': {
			
			if(name == "^gore") {
				*lcontent = 1;
				return TYPE_LONG;
			}
			
			if(name == "^gamedays") {
				*lcontent = static_cast<long>(float(arxtime) / 86400000);
				return TYPE_LONG;
			}
			
			if(name == "^gamehours") {
				*lcontent = static_cast<long>(float(arxtime) / 3600000);
				return TYPE_LONG;
			}
			
			if(name == "^gameminutes") {
				*lcontent = static_cast<long>(float(arxtime) / 60000);
				return TYPE_LONG;
			}
			
			if(name == "^gameseconds") {
				*lcontent = static_cast<long>(float(arxtime) / 1000);
				return TYPE_LONG;
			}
			
			break;
		}
		
		case 'a': {
			
			if(boost::starts_with(name, "^amount")) {
				if(entity && (entity->ioflags & IO_ITEM)) {
					*fcontent = entity->_itemdata->count;
				} else {
					*fcontent = 0;
				}
				return TYPE_FLOAT;
			}
			
			if(name == "^arxdays") {
				*lcontent = static_cast<long>(float(arxtime) / 7200000);
				return TYPE_LONG;
			}
			
			if(name == "^arxhours") {
				*lcontent = static_cast<long>(float(arxtime) / 600000);
				return TYPE_LONG;
			}
			
			if(name == "^arxminutes") {
				*lcontent = static_cast<long>(float(arxtime) / 10000);
				return TYPE_LONG;
			}
			
			if(name == "^arxseconds") {
				*lcontent = static_cast<long>(float(arxtime) / 1000) * 6;
				return TYPE_LONG;
			}
			
			if(name == "^arxtime_hours") {
				*lcontent = static_cast<long>(float(arxtime) / 600000);
				while(*lcontent > 12) {
					*lcontent -= 12;
				}
				return TYPE_LONG;
			}
			
			if(name == "^arxtime_minutes") {
				*lcontent = static_cast<long>(float(arxtime) / 10000);
				while(*lcontent > 60) {
					*lcontent -= 60;
				}
				return TYPE_LONG;
			}
			
			if(name == "^arxtime_seconds") {
				*lcontent = static_cast<long>(float(arxtime) * 6 / 1000);
				while(*lcontent > 60) {
					*lcontent -= 60;
				}
				return TYPE_LONG;
			}
			
			break;
		}
		
		case 'r': {
			
			if(boost::starts_with(name, "^realdist_")) {
				if(entity) {
					const char * obj = name.c_str() + 10;
					
					if(!strcmp(obj, "player")) {
						if(entity->requestRoomUpdate) {
							UpdateIORoom(entity);
						}
						long Player_Room = ARX_PORTALS_GetRoomNumForPosition(player.pos, 1);
						*fcontent = SP_GetRoomDist(entity->pos, player.pos, entity->room, Player_Room);
						return TYPE_FLOAT;
					}
					
					EntityHandle t = entities.getById(obj);
					if(ValidIONum(t)) {
						if((entity->show == SHOW_FLAG_IN_SCENE
						    || entity->show == SHOW_FLAG_IN_INVENTORY)
						   && (entities[t]->show == SHOW_FLAG_IN_SCENE
						       || entities[t]->show == SHOW_FLAG_IN_INVENTORY)) {
							
							Vec3f pos  = GetItemWorldPosition(entity);
							Vec3f pos2 = GetItemWorldPosition(entities[t]);
							
							if(entity->requestRoomUpdate) {
								UpdateIORoom(entity);
							}
							
							if(entities[t]->requestRoomUpdate) {
								UpdateIORoom(entities[t]);
							}
							
							*fcontent = SP_GetRoomDist(pos, pos2, entity->room, entities[t]->room);
							
						} else {
							// Out of this world item
							*fcontent = 99999999999.f;
						}
						return TYPE_FLOAT;
					}
					
					*fcontent = 99999999999.f;
					return TYPE_FLOAT;
				}
			}
			
			if(boost::starts_with(name, "^repairprice_")) {
				EntityHandle t = entities.getById(name.substr(13));
				if(ValidIONum(t)) {
					*fcontent = ARX_DAMAGES_ComputeRepairPrice(entities[t], entity);
				} else {
					*fcontent = 0;
				}
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^rnd_")) {
				const char * max = name.c_str() + 5;
				// TODO should max be inclusive or exclusive?
				// if inclusive, use proper integer random, otherwise fix rnd()?
				if(max[0]) {
					float t = (float)atof(max);
					*fcontent = Random::getf(0.f, t);
					return TYPE_FLOAT;
				}
				*fcontent = 0;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^rune_")) {
				std::string temp = name.substr(6);
				*lcontent = 0;
				if(temp == "aam") {
					*lcontent = player.rune_flags & FLAG_AAM;
				} else if(temp == "cetrius") {
					*lcontent = player.rune_flags & FLAG_CETRIUS;
				} else if(temp == "comunicatum") {
					*lcontent = player.rune_flags & FLAG_COMUNICATUM;
				} else if(temp == "cosum") {
					*lcontent = player.rune_flags & FLAG_COSUM;
				} else if(temp == "folgora") {
					*lcontent = player.rune_flags & FLAG_FOLGORA;
				} else if(temp == "fridd") {
					*lcontent = player.rune_flags & FLAG_FRIDD;
				} else if(temp == "kaom") {
					*lcontent = player.rune_flags & FLAG_KAOM;
				} else if(temp == "mega") {
					*lcontent = player.rune_flags & FLAG_MEGA;
				} else if(temp == "morte") {
					*lcontent = player.rune_flags & FLAG_MORTE;
				} else if(temp == "movis") {
					*lcontent = player.rune_flags & FLAG_MOVIS;
				} else if(temp == "nhi") {
					*lcontent = player.rune_flags & FLAG_NHI;
				} else if(temp == "rhaa") {
					*lcontent = player.rune_flags & FLAG_RHAA;
				} else if(temp == "spacium") {
					*lcontent = player.rune_flags & FLAG_SPACIUM;
				} else if(temp == "stregum") {
					*lcontent = player.rune_flags & FLAG_STREGUM;
				} else if(temp == "taar") {
					*lcontent = player.rune_flags & FLAG_TAAR;
				} else if(temp == "tempus") {
					*lcontent = player.rune_flags & FLAG_TEMPUS;
				} else if(temp == "tera") {
					*lcontent = player.rune_flags & FLAG_TERA;
				} else if(temp == "vista") {
					*lcontent = player.rune_flags & FLAG_VISTA;
				} else if(temp == "vitae") {
					*lcontent = player.rune_flags & FLAG_VITAE;
				} else if(temp == "yok") {
					*lcontent = player.rune_flags & FLAG_YOK;
				}
				return TYPE_LONG;
			}
			
			break;
		}
		
		case 'i': {
			
			if(boost::starts_with(name, "^inzone_")) {
				const char * zone = name.c_str() + 8;
				ARX_PATH * ap = ARX_PATH_GetAddressByName(zone);
				*lcontent = 0;
				if(entity && ap) {
					if(ARX_PATH_IsPosInZone(ap, entity->pos)) {
						*lcontent = 1;
					}
				}
				return TYPE_LONG;
			}
			
			if(boost::starts_with(name, "^ininitpos")) {
				*lcontent = 0;
				if(entity) {
					Vec3f pos = GetItemWorldPosition(entity);
					if(pos == entity->initpos)
						*lcontent = 1;
				}
				return TYPE_LONG;
			}
			
			if(boost::starts_with(name, "^inplayerinventory")) {
				*lcontent = 0;
				if(entity && (entity->ioflags & IO_ITEM) && IsInPlayerInventory(entity)) {
					*lcontent = 1;
				}
				return TYPE_LONG;
			}
			
			break;
		}
		
		case 'b': {
			
			if(boost::starts_with(name, "^behavior")) {
				txtcontent = "";
				if(entity && (entity->ioflags & IO_NPC)) {
					if(entity->_npcdata->behavior & BEHAVIOUR_LOOK_AROUND) {
						txtcontent += "l";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_SNEAK) {
						txtcontent += "s";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_DISTANT) {
						txtcontent += "d";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_MAGIC) {
						txtcontent += "m";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_FIGHT) {
						txtcontent += "f";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_GO_HOME) {
						txtcontent += "h";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_FRIENDLY) {
						txtcontent += "r";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_MOVE_TO) {
						txtcontent += "t";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_FLEE) {
						txtcontent += "e";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_LOOK_FOR) {
						txtcontent += "o";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_HIDE) {
						txtcontent += "i";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_WANDER_AROUND) {
						txtcontent += "w";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_GUARD) {
						txtcontent += "u";
					}
					if(entity->_npcdata->behavior & BEHAVIOUR_STARE_AT) {
						txtcontent += "a";
					}
				}
				return TYPE_TEXT;
			}
			
			break;
		}
		
		case 's': {
			
			if(boost::starts_with(name, "^sender")) {
				if(!EVENT_SENDER) {
					txtcontent = "none";
				} else if(EVENT_SENDER == entities.player()) {
					txtcontent = "player";
				} else {
					txtcontent = EVENT_SENDER->idString();
				}
				return TYPE_TEXT;
			}
			
			if(boost::starts_with(name, "^scale")) {
				*fcontent = (entity) ? entity->scale * 100.f : 0.f;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^speaking")) {
				if(entity) {
					for(size_t i = 0; i < MAX_ASPEECH; i++) {
						if(aspeech[i].exist && entity == aspeech[i].io) {
							*lcontent = 1;
							return TYPE_LONG;
						}
					}
				}
				*lcontent = 0;
				return TYPE_LONG;
			}
			
			break;
		}
		
		case 'm': {
			
			if(boost::starts_with(name, "^me")) {
				if(!entity) {
					txtcontent = "none";
				} else if(entity == entities.player()) {
					txtcontent = "player";
				} else {
					txtcontent = entity->idString();
				}
				return TYPE_TEXT;
			}
			
			if(boost::starts_with(name, "^maxlife")) {
				*fcontent = 0;
				if(entity && (entity->ioflags & IO_NPC)) {
					*fcontent = entity->_npcdata->lifePool.max;
				}
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^mana")) {
				*fcontent = 0;
				if(entity && (entity->ioflags & IO_NPC)) {
					*fcontent = entity->_npcdata->manaPool.current;
				}
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^maxmana")) {
				*fcontent = 0;
				if(entity && (entity->ioflags & IO_NPC)) {
					*fcontent = entity->_npcdata->manaPool.max;
				}
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^myspell_")) {
				SpellType id = GetSpellId(name.substr(9));
				if(id != SPELL_NONE) {
					if(spells.ExistAnyInstanceForThisCaster(id, entity->index())) {
						*lcontent = 1;
						return TYPE_LONG;
					}
				}
				*lcontent = 0;
				return TYPE_LONG;
			}
			
			if(boost::starts_with(name, "^maxdurability")) {
				*fcontent = (entity) ? entity->max_durability : 0.f;
				return TYPE_FLOAT;
			}
			
			break;
		}
		
		case 'l': {
			
			if(boost::starts_with(name, "^life")) {
				*fcontent = 0;
				if(entity && (entity->ioflags & IO_NPC)) {
					*fcontent = entity->_npcdata->lifePool.current;
				}
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^last_spawned")) {
				txtcontent = (LASTSPAWNED) ? LASTSPAWNED->idString() : "none";
				return TYPE_TEXT;
			}
			
			break;
		}
		
		case 'd': {
			
			if(boost::starts_with(name, "^dist_")) {
				if(entity) {
					const char * obj = name.c_str() + 6;
					
					if(!strcmp(obj, "player")) {
						*fcontent = fdist(player.pos, entity->pos);
						return TYPE_FLOAT;
					}
					
					EntityHandle t = entities.getById(obj);
					if(ValidIONum(t)) {
						if((entity->show == SHOW_FLAG_IN_SCENE
						    || entity->show == SHOW_FLAG_IN_INVENTORY)
						   && (entities[t]->show == SHOW_FLAG_IN_SCENE
						       || entities[t]->show == SHOW_FLAG_IN_INVENTORY)) {
							Vec3f pos  = GetItemWorldPosition(entity);
							Vec3f pos2 = GetItemWorldPosition(entities[t]);
							*fcontent = fdist(pos, pos2);
							return TYPE_FLOAT;
						}
					}
					
					*fcontent = 99999999999.f;
					return TYPE_FLOAT;
				}
			}
			
			if(boost::starts_with(name, "^demo")) {
				*lcontent = (resources->getReleaseType() & PakReader::Demo) ? 1 : 0;
				return TYPE_LONG;
			}
			
			if(boost::starts_with(name, "^durability")) {
				*fcontent = (entity) ? entity->durability : 0.f;
				return TYPE_FLOAT;
			}
			
			break;
		}
		
		case 'p': {
			
			if(boost::starts_with(name, "^price")) {
				*fcontent = 0;
				if(entity && (entity->ioflags & IO_ITEM)) {
					*fcontent = static_cast<float>(entity->_itemdata->price);
				}
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_zone")) {
				txtcontent = (player.inzone) ? player.inzone->name : "none";
				return TYPE_TEXT;
			}
			
			if(boost::starts_with(name, "^player_life")) {
				*fcontent = player.Full_life; // TODO why not player.life like everywhere else?
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^poisoned")) {
				*fcontent = 0;
				if(entity && (entity->ioflags & IO_NPC)) {
					*fcontent = entity->_npcdata->poisonned;
				}
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^poisonous")) {
				*fcontent = (entity) ? entity->poisonous : 0.f;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^possess_")) {
				EntityHandle t = entities.getById(name.substr(9));
				if(ValidIONum(t)) {
					if(IsInPlayerInventory(entities[t])) {
						*lcontent = 1;
						return TYPE_LONG;
					}
					for(long i = 0; i < MAX_EQUIPED; i++) {
						if(ValidIONum(player.equiped[i]) && player.equiped[i] == t) {
							*lcontent = 2;
							return TYPE_LONG;
						}
					}
				}
				*lcontent = 0;
				return TYPE_LONG;
			}
			
			if(boost::starts_with(name, "^player_gold")) {
				*fcontent = static_cast<float>(player.gold);
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_maxlife")) {
				*fcontent = player.Full_maxlife;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_attribute_strength")) {
				*fcontent = player.m_attributeFull.strength;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_attribute_dexterity")) {
				*fcontent = player.m_attributeFull.dexterity;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_attribute_constitution")) {
				*fcontent = player.m_attributeFull.constitution;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_attribute_mind")) {
				*fcontent = player.m_attributeFull.mind;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_stealth")) {
				*fcontent = player.m_skillFull.stealth;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_mecanism")) {
				*fcontent = player.m_skillFull.mecanism;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_intuition")) {
				*fcontent = player.m_skillFull.intuition;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_etheral_link")) {
				*fcontent = player.m_skillFull.etheralLink;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_object_knowledge")) {
				*fcontent = player.m_skillFull.objectKnowledge;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_casting")) {
				*fcontent = player.m_skillFull.casting;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_projectile")) {
				*fcontent = player.m_skillFull.projectile;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_close_combat")) {
				*fcontent = player.m_skillFull.closeCombat;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_skill_defense")) {
				*fcontent = player.m_skillFull.defense;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_hunger")) {
				*fcontent = player.hunger;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^player_poison")) {
				*fcontent = player.poison;
				return TYPE_FLOAT;
			}
			
			if(boost::starts_with(name, "^playercasting")) {
				for(size_t i = 0; i < MAX_SPELLS; i++) {
					const SpellBase * spell = spells[SpellHandle(i)];
					
					if(spell && spell->m_caster == PlayerEntityHandle) {
						if(   spell->m_type == SPELL_LIFE_DRAIN
						   || spell->m_type == SPELL_HARM
						   || spell->m_type == SPELL_FIRE_FIELD
						   || spell->m_type == SPELL_ICE_FIELD
						   || spell->m_type == SPELL_LIGHTNING_STRIKE
						   || spell->m_type == SPELL_MASS_LIGHTNING_STRIKE
						) {
							*lcontent = 1;
							return TYPE_LONG;
						}
					}
				}
				*lcontent = 0;
				return TYPE_LONG;
			}
			
			if(boost::starts_with(name, "^playerspell_")) {
				std::string temp = name.substr(13);
				
				SpellType id = GetSpellId(temp);
				if(id != SPELL_NONE) {
					if(spells.ExistAnyInstanceForThisCaster(id, PlayerEntityHandle)) {
						*lcontent = 1;
						return TYPE_LONG;
					}
				}
				
				if(temp == "invisibility" && entities.player()->invisibility > 0.3f) {
					*lcontent = 1;
					return TYPE_LONG;
				}
				
				*lcontent = 0;
				return TYPE_LONG;
			}
			
			break;
		}
		
		case 'n': {
			
			if(boost::starts_with(name, "^npcinsight")) {
				Entity * ioo = ARX_NPC_GetFirstNPCInSight(entity);
				if(!ioo) {
					txtcontent = "none";
				} else if(ioo == entities.player()) {
					txtcontent = "player";
				} else {
					txtcontent = ioo->idString();
				}
				return TYPE_TEXT;
			}
			
			break;
		}
		
		case 't': {
			
			if(boost::starts_with(name, "^target")) {
				if(!entity) {
					txtcontent = "none";
				} else if(entity->targetinfo == PlayerEntityHandle) {
					txtcontent = "player";
				} else if(!ValidIONum(entity->targetinfo)) {
					txtcontent = "none";
				} else {
					txtcontent = entities[entity->targetinfo]->idString();
				}
				return TYPE_TEXT;
			}
			
			break;
		}
		
		case 'f': {
			
			if(boost::starts_with(name, "^focal")) {
				if(entity && (entity->ioflags & IO_CAMERA)) {
					*fcontent = entity->_camdata->cam.focal;
					return TYPE_FLOAT;
				}
			}
			
			if(boost::starts_with(name, "^fighting")) {
				*lcontent = long(ARX_PLAYER_IsInFightMode());
				return TYPE_LONG;
			}
			
			break;
		}
		
	}
	
	*lcontent = 0;
	return TYPE_LONG;
}
Example #2
0
void CDC::converteStringParaMinuscula(std::string &str) {
    for(unsigned int pos=0; pos<str.length(); pos++) {
        if(str[pos]>=65 && str[pos]<=90) str[pos]+=32;
    }
}
Example #3
0
bool TimeUtils::convert8601TimeStringToUnix(const std::string& timeString, int64_t* convertedTime) {
    // TODO : Use std::get_time once we only support compilers that implement this function (GCC 5.1+ / Clang 3.3+)

    if (!convertedTime) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("convertedTime parameter was nullptr."));
        return false;
    }

    std::tm timeInfo;

    if (timeString.length() != ENCODED_TIME_STRING_EXPECTED_LENGTH) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").d("unexpected time string length:", timeString.length()));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_YEAR_OFFSET, ENCODED_TIME_STRING_YEAR_STRING_LENGTH),
            &(timeInfo.tm_year))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing year. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_MONTH_OFFSET, ENCODED_TIME_STRING_MONTH_STRING_LENGTH),
            &(timeInfo.tm_mon))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing month. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_DAY_OFFSET, ENCODED_TIME_STRING_DAY_STRING_LENGTH),
            &(timeInfo.tm_mday))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing day. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_HOUR_OFFSET, ENCODED_TIME_STRING_HOUR_STRING_LENGTH),
            &(timeInfo.tm_hour))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing hour. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_MINUTE_OFFSET, ENCODED_TIME_STRING_MINUTE_STRING_LENGTH),
            &(timeInfo.tm_min))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing minute. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_SECOND_OFFSET, ENCODED_TIME_STRING_SECOND_STRING_LENGTH),
            &(timeInfo.tm_sec))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing second. Input:" + timeString));
        return false;
    }

    // adjust for C struct tm standard
    timeInfo.tm_isdst = 0;
    timeInfo.tm_year -= 1900;
    timeInfo.tm_mon -= 1;

    std::time_t convertedTimeT;
    bool ok = convertToUtcTimeT(&timeInfo, &convertedTimeT);

    if (!ok) {
        return false;
    }

    *convertedTime = static_cast<int64_t>(convertedTimeT);
    return true;
}
Example #4
0
bool cTIFFFile::Load(GLCD::cImage & image, const std::string & fileName)
{
    FILE         *fIN;
    TIFFTAG       tifftag;
    unsigned int  tiff_header, tiff_anztags, tiff_data;
    unsigned char cl,ch,y,i;
    unsigned char height, width, strip, invert;
    unsigned char fLittleEndian=0;
    int j;
    int t;
    unsigned char *bitmap = NULL;
    bool  bInvert = false;

    if (fileName.length() > 0)
    {
        fIN = fopen(fileName.c_str(), "rb");
        if (fIN)
        {
            //    isyslog("graphlcd plugin: try to load logo %s.", szFileName);
            if (fseek(fIN, 0, SEEK_SET)==EOF)
            {
                fclose(fIN);
                return false;
            }
            GETANDCHECK; cl=(unsigned char)t;
            GETANDCHECK; ch=(unsigned char)t;
            if ((cl==0x49) && (ch==0x49))
            {
                fLittleEndian=1;
            }

            if (fseek(fIN, 4, SEEK_SET)==EOF)
            {
                fclose(fIN);
                return false;
            }
            GETANDCHECK; cl=(unsigned char)t;
            GETANDCHECK; ch=(unsigned char)t;
            tiff_header = cl+256*ch;
            //printf("tiff_header:%d %x\n", tiff_header, tiff_header);

            if (fseek(fIN, tiff_header, SEEK_SET)==EOF)
            {
                fclose(fIN);
                return false;
            }

            GETANDCHECK; cl=(unsigned char)t;
            GETANDCHECK; ch=(unsigned char)t;
            tiff_anztags = cl+256*ch;
            //printf("tiff_anztags:%d %x\n", tiff_anztags, tiff_anztags);

            height=0;
            width=0;
            strip=0;
            invert=0;
            for (i=0; (i<tiff_anztags)&&(!height||!width||!strip||!invert); i++)
            {
                if (fread(&tifftag, sizeof(tifftag), 1, fIN)!=1)
                {
                    fclose(fIN);
                    return false;
                }
                if (tifftag.tag==0x0100) width=tifftag.off_val;
                if (tifftag.tag==0x0101) height=tifftag.off_val;
                if (tifftag.tag==0x0111) strip=tifftag.off_val;
                if (tifftag.tag==0x0106) invert=tifftag.off_val+1;
                //printf("tag%d: %d %d %ld %ld\n", i,tifftag.tag, tifftag.type, tifftag.length, tifftag.off_val );
            }

            if (fseek(fIN,strip, SEEK_SET)==EOF)
            {
                fclose(fIN);
                return false;
            }
            GETANDCHECK; cl=(unsigned char)t;
            GETANDCHECK; ch=(unsigned char)t;
            tiff_data = cl+256*ch;
            //printf("tiff_data:%d %x\n", tiff_data, tiff_data);

            if (fseek(fIN, tiff_data, SEEK_SET)==EOF)
            {
                fclose(fIN);
                return false;
            }


            image.Clear();
            image.SetWidth(width);
            image.SetHeight(height);
            image.SetDelay(100);
            bitmap = new unsigned char[height * ((width + 7) / 8)];
            if (bitmap)
            {
                if (fread(bitmap, height*((width+7)/8), 1, fIN)!=1)
                {
                    delete [] bitmap;
                    fclose(fIN);
                    image.Clear();
                    return false;
                }

                if (invert-1==1) bInvert = !bInvert; // 'Black is zero'
                if (bInvert)
                {
                    for (j=0; j < height * ((width+7)/8); j++)
                    {
                        (*(bitmap+j)) = (*(bitmap+j))^0xff;
                    }
                }

                // cut the rest of the line
                if (width%8)
                {
                    for (y=1; y<=height; y++) {
                        j=y*((width+7)/8)-1;
                        (*(bitmap+j)) = ((*(bitmap+j))>>(8-width%8))<<(8-width%8);
                    }
                }
                image.AddBitmap(new GLCD::cBitmap(width, height, bitmap));
            }
            else
            {
                fprintf(stderr, "ERROR: cannot allocate memory\n");
            }
            fclose(fIN);
        }
Example #5
0
void RPCClient::net_process(const std::function<void(std::string)>& disconnect) {
	connected = true;

	uint8_t count = 0;
	while (true) {
		int content_length = -2;
		bool close_after_read = false;
		int max_read;
		char buf[2048];
		std::string line;

		while (true) {
			std::string::size_type line_break;
			while ((line_break = line.find("\r\n")) == std::string::npos) {
				if (line.find("\r") != std::string::npos)
					max_read = 1;
				else
					max_read = 2;

				if (read_all(buf, max_read, std::chrono::seconds(10)) != max_read)
					return disconnect("Failed to read server response");
				line.append(buf, buf + max_read);

				if (line.length() > 16384)
					return disconnect("Got header longer than 16k!");
			}

			std::string current_line(line.substr(0, line_break));
			line = line.substr(line_break + 2);

			if (content_length == -2) {
				if (current_line != std::string("HTTP/1.1 200 OK"))
					return disconnect("Got HTTP error message: " + asciifyString(current_line));
				content_length++;
			} else if (current_line.length()) {
				std::string::size_type colon(current_line.find(':'));
				if (colon == std::string::npos)
					return disconnect("Got Bad HTTP header line: " + asciifyString(current_line));
				if (current_line.compare(0, strlen("Connection: "), "Connection: ") == 0) {
					if (current_line.compare(strlen("Connection: "), strlen("close"), "close") == 0)
						close_after_read = true;
					else if (current_line.compare(strlen("Connection: "), strlen("keep-alive"), "keep-alive") != 0)
						return disconnect("Got Bad HTTP Connection header line: " + asciifyString(current_line));
				} else if (current_line.compare(0, strlen("Content-Length: "), "Content-Length: ") == 0) {
					try {
						size_t endpos;
						content_length = std::stoi(&(current_line.c_str())[strlen("Content-Length: ")], &endpos);
						if (content_length < 0 || endpos != current_line.length() - strlen("Content-Length: "))
							return disconnect("Got Bad HTTP Content-Length header line: " + asciifyString(current_line));
					} catch (std::exception& e) {
						return disconnect("Got Bad HTTP Content-Length header line: " + asciifyString(current_line));
					}
				}
			} else if (content_length < 0)
				return disconnect("Got to end of HTTP headers without a Content-Length");
			else
				break;
		}

		if (content_length < 0 || content_length > 1024*1024*100)
			return disconnect("Got unreasonably large response size");

		//Dumb JSON parser that mostly assumes valid (minimal-size) JSON...
		static const std::string expected_start("{\"result\":{");
		{
			char resp[expected_start.length()];
			if (read_all(resp, expected_start.length()) != (ssize_t)expected_start.length())
				return disconnect("Failed to read response");
			if (memcmp(resp, &expected_start[0], expected_start.length()) != 0)
				return disconnect("Got result which was not an object");
		}

		std::vector<unsigned char> resp(content_length - expected_start.length());
		if (read_all((char*)&resp[0], content_length - expected_start.length()) != content_length - (ssize_t)expected_start.length())
			return disconnect("Failed to read response");
		auto it = resp.begin();

		//These do not move
		std::list<CTxMemPoolEntry> txn;
		//These index into txn
		std::vector<CTxMemPoolEntry*> vectorToSort;
		std::unordered_map<std::string, CTxMemPoolEntry*> hashToEntry;
		std::unordered_multimap<std::string, CTxMemPoolEntry*> txnWaitingOnDeps;

		// These are values/flags about the current status of the parser
		int32_t stringStart = -1, fieldValueStart = -1;
		std::string txHash, fieldString;
		long tx_size = -1; uint64_t tx_fee = -1; double tx_prio = -1;
		bool inTx = false, inFieldString = false, inFieldValue = false;
		std::unordered_set<std::string> txDeps;

		static const std::string expected_end("},\"error\":null,\"id\":1}\n");
		while (it < resp.end() - expected_end.length()) {
			while ((*it == ' ') && it < resp.end() - 1) it++;
			switch(*it) {
			case '"':
				if (stringStart != -1) {
					if (!inTx)
						txHash = std::string(resp.begin() + stringStart, it);
					else if (inFieldString)
						fieldString = std::string(resp.begin() + stringStart, it);
					else if (inFieldValue)
						return disconnect("got string as a field value");
					stringStart = -1;
				} else
					stringStart = it - resp.begin() + 1;
				break;
			case ':':
				if (stringStart != -1)
					return disconnect("Got : in a string (all strings should have been hex");
				if (inFieldString) {
					inFieldValue = true;
					inFieldString = false;
					fieldValueStart = it - resp.begin() + 1;
				} else if (inFieldValue)
					return disconnect("Got : in an unexpected place");
				break;
			case ',':
				if (stringStart != -1)
					return disconnect("Got , in a string (all strings should have been hex");
				if (inFieldValue) {
					inFieldValue = false;
					inFieldString = true;
					if (fieldString == "size") {
						try {
							tx_size = std::stol(std::string(resp.begin() + fieldValueStart, it));
						} catch (std::exception& e) {
							return disconnect("transaction size could not be parsed");
						}
					} else if (fieldString == "fee") {
						try {
							tx_fee = uint64_t(std::stod(std::string(resp.begin() + fieldValueStart, it)) * 100000000);
						} catch (std::exception& e) {
							return disconnect("transaction value could not be parsed");
						}
					} else if (fieldString == "currentpriority") {
						try {
							tx_prio = std::stod(std::string(resp.begin() + fieldValueStart, it));
						} catch (std::exception& e) {
							return disconnect("transaction prio could not be parsed");
						}
					}
				} else if (inTx)
					return disconnect("Got unexpected ,");
				break;
			case '[':
			{
				it++;
				int32_t depStringStart = -1;
				while (*it != ']' && it < resp.end() - 1) {
					if (*it == '"') {
						if (depStringStart != -1) {
							txDeps.insert(std::string(resp.begin() + depStringStart, it));
							depStringStart = -1;
						} else
							depStringStart = it - resp.begin() + 1;
					}
					it++;
				}
				if (*it != ']' || depStringStart != -1)
					return disconnect("Missing array end character (])");
				break;
			}
			case '{':
				if (stringStart != -1)
					return disconnect("Got { in a string (all strings should have been hex");
				else if (!inTx) {
					inTx = true;
					inFieldString = true;
				} else
					return disconnect("Got JSON object start when we weren't expecting one");
				break;
			case '}':
				if (inTx) {
					if (inFieldValue) {
						inFieldValue = false;
						if (fieldString == "size") {
							try {
								tx_size = std::stol(std::string(resp.begin() + fieldValueStart, it));
							} catch (std::exception& e) {
								return disconnect("transaction size could not be parsed");
							}
						} else if (fieldString == "fee") {
							try {
								tx_fee = uint64_t(std::stod(std::string(resp.begin() + fieldValueStart, it)) * 100000000);
							} catch (std::exception& e) {
								return disconnect("transaction value could not be parsed");
							}
						} else if (fieldString == "currentpriority") {
							try {
								tx_prio = std::stod(std::string(resp.begin() + fieldValueStart, it));
							} catch (std::exception& e) {
								return disconnect("transaction prio could not be parsed");
							}
						}
					} else
						return disconnect("Got unepxecpted }");

					if (tx_size < 0)
						return disconnect("Did not get transaction size");
					else if (tx_fee < 0)
						return disconnect("Did not get transaction fee");
					else if (tx_prio < 0)
						return disconnect("Did not get transaction prio");

					std::vector<unsigned char> hash;
					if (!hex_str_to_reverse_vector(txHash, hash) || hash.size() != 32)
						return disconnect("got bad hash");

					txn.emplace_back(tx_fee, tx_size, tx_prio, hash, txDeps.size());
					if (!hashToEntry.insert(std::make_pair(txHash, &txn.back())).second)
						return disconnect("Duplicate transaction");

					if (txDeps.empty())
						vectorToSort.push_back(&txn.back());
					else {
						for (const std::string& dep : txDeps) {
							auto depIt = hashToEntry.find(dep);
							if (depIt == hashToEntry.end())
								txnWaitingOnDeps.insert(std::make_pair(dep, &txn.back()));
							else
								depIt->second->setDeps.insert(&txn.back());
						}
					}

					auto waitingIts = txnWaitingOnDeps.equal_range(txHash);
					for (auto waitingIt = waitingIts.first; waitingIt != waitingIts.second; waitingIt++)
						txn.back().setDeps.insert(waitingIt->second);
					txnWaitingOnDeps.erase(txHash);

					inTx = false;
					tx_size = -1;
					tx_fee = -1;
					txDeps.clear();
				} else
					return disconnect("Global JSON object closed before the end");
				break;
			}
			it++;
		}
		if (it != resp.end() - expected_end.length() || memcmp(&(*it), &expected_end[0], expected_end.length()) != 0)
			return disconnect("JSON object was not closed at the end");

		if (!txnWaitingOnDeps.empty())
			return disconnect("Tx depended on another one which did not exist");

		std::vector<std::pair<std::vector<unsigned char>, size_t> > txn_selected;
		std::function<bool (const CTxMemPoolEntry* a, const CTxMemPoolEntry* b)> comp = [](const CTxMemPoolEntry* a, const CTxMemPoolEntry* b) {
			return a->feePerKb < b->feePerKb || (a->feePerKb == b->feePerKb && a->prio < b->prio);
		};
		std::make_heap(vectorToSort.begin(), vectorToSort.end(), comp);

		uint64_t minFeePerKbSelected = 4000000000;
		unsigned minFeePerKbTxnCount = 0;
		uint64_t totalSizeSelected = 0;
		while (totalSizeSelected < 9*MAX_FAS_TOTAL_SIZE/10 && vectorToSort.size()) {
			std::pop_heap(vectorToSort.begin(), vectorToSort.end(), comp);
			CTxMemPoolEntry* e = vectorToSort.back();
			vectorToSort.pop_back();
			if (e->size <= MAX_RELAY_TRANSACTION_BYTES) {
				for (CTxMemPoolEntry* dep : e->setDeps)
					if ((--dep->reqCount) == 0) {
						vectorToSort.push_back(dep);
						std::push_heap(vectorToSort.begin(), vectorToSort.end(), comp);
					}
				txn_selected.push_back(std::make_pair(e->hash, e->size));
				totalSizeSelected += e->size;
				if (e->feePerKb == minFeePerKbSelected)
					minFeePerKbTxnCount++;
				else if (e->feePerKb < minFeePerKbSelected) {
					minFeePerKbSelected = e->feePerKb;
					minFeePerKbTxnCount = 1;
				}
			}
		}

		unsigned minFeePerKbTxnSkipped = 0;
		while (vectorToSort.size()) {
			std::pop_heap(vectorToSort.begin(), vectorToSort.end(), comp);
			CTxMemPoolEntry* e = vectorToSort.back();
			vectorToSort.pop_back();
			if (e->feePerKb != minFeePerKbSelected)
				break;
			minFeePerKbTxnSkipped++;
		}

		if (++count == 0 && minFeePerKbTxnSkipped > 1 && minFeePerKbTxnCount > 1)
			printf("WARNING: Skipped %u txn while accepting %u identical-fee txn\n", minFeePerKbTxnSkipped, minFeePerKbTxnCount);

		txn_for_block_func(txn_selected, txn.size());
		awaiting_response = false;

		if (close_after_read)
			return disconnect("Got Connection: close");
	}
}
Example #6
0
 /** Convert regular argument into the network-specific setting */
 static inline std::string NetworkArg(const ArgsManager& am, const std::string& arg)
 {
     assert(arg.length() > 1 && arg[0] == '-');
     return "-" + am.m_network + "." + arg.substr(1);
 }
Example #7
0
    }
    BLOCK_END("ChatHandler::handleMessage")
}

void ChatHandler::talk(const std::string &restrict text,
                       const std::string &restrict channel A_UNUSED) const
{
    if (!localPlayer)
        return;

    const std::string mes = std::string(localPlayer->getName()).append(
        " : ").append(text);

    createOutPacket(CMSG_CHAT_MESSAGE);
    // Added + 1 in order to let eAthena parse admin commands correctly
    outMsg.writeInt16(static_cast<int16_t>(mes.length() + 4 + 1), "len");
    outMsg.writeString(mes, static_cast<int>(mes.length() + 1), "message");
}

void ChatHandler::talkRaw(const std::string &mes) const
{
    createOutPacket(CMSG_CHAT_MESSAGE);
    outMsg.writeInt16(static_cast<int16_t>(mes.length() + 4), "len");
    outMsg.writeString(mes, static_cast<int>(mes.length()), "message");
}

void ChatHandler::privateMessage(const std::string &restrict recipient,
                                 const std::string &restrict text)
{
    createOutPacket(CMSG_CHAT_WHISPER);
    outMsg.writeInt16(static_cast<int16_t>(text.length() + 28), "len");
Example #8
0
int64_t rsg::RsgCommHandler::send_async(const int64_t sender, const int64_t dest, const std::string& data, const int64_t size, const int64_t simulatedByteAmount) {
    s4u::MailboxPtr mbox = rsg::RsgMailboxHandler::pMailboxes.at(dest);
    std::string *strData = new std::string(data.data(), data.length());
    return (int64_t) &s4u::Comm::send_async(mbox, (void*) strData, simulatedByteAmount);
}
Example #9
0
void rsg::RsgCommHandler::setSrcData(const int64_t addr, const std::string& buff) {
    s4u::Comm *comm = (s4u::Comm*) addr;
    std::string *payload = new std::string(buff.data(), buff.length());
    comm->setSrcData((void*)payload, sizeof(void*));
}
Example #10
0
void NCursesIOManager::removeCharFromOrder(std::string & input)
{
	input.resize(input.length() == 0 ? 0 : input.length() - 1);
}
bool StringUtils::istarts_with(const std::string &string, const std::string &prefix)
{
    return starts_with_internal(string.c_str(), string.size(),
                                prefix.c_str(), prefix.length(),
                                true);
}
Example #12
0
void writeOutput(const std::string& filename, const std::string& output)
{
	std::ofstream file(filename.c_str(), std::ios::binary);

	file.write(output.c_str(), output.length());
}
Example #13
0
void RemoveApostrophes(std::string &s)
{
	for(unsigned int i = 0; i < s.length(); ++i)
		if(s[i] == '\'')
			 s[i] = '_';
}
Example #14
0
                //=================================================================
                bool TileAssembler::readRawFile(std::string& pModelFilename,  ModelPosition& pModelPosition, AABSPTree<SubModel *> *pMainTree)
                {
                    bool result = false;

                    std::string filename = iSrcDir;
                    if(filename.length() >0)
                        filename.append("/");
                    filename.append(pModelFilename);
                    FILE *rf = fopen(filename.c_str(), "rb");
                    if(!rf)
                    {
                        // depending on the extractor version, the data could be located in the root dir
                        std::string baseModelFilename = pModelFilename.substr((pModelFilename.find_first_of("/")+1),pModelFilename.length());
                        filename = iSrcDir;
                        if(filename.length() >0)
                            filename.append("/");
                        filename.append(baseModelFilename);
                        rf = fopen(filename.c_str(), "rb");
                    }
                    char ident[8];

                    int trianglecount =0;

                    #ifdef _ASSEMBLER_DEBUG
                    int startgroup = 0;                     //2;
                    int endgroup = INT_MAX;                 //2;
                    fprintf(::g_df,"-------------------------------------------------\n");
                    fprintf(::g_df,"%s\n", pModelFilename.c_str());
                    fprintf(::g_df,"-------------------------------------------------\n");
                    #else
                    int startgroup = 0;
                    int endgroup = INT_MAX;
                    #endif

                    if(rf)
                    {
                        if(fread(&ident, 8, 1, rf) != 1) { fclose(rf); return(false); }
                        if(strcmp(ident, "VMAP001") == 0)
                        {
                            // OK, do nothing
                        }
                        else if(strcmp(ident, "VMAP002") == 0)
                        {
                            // we have to read one int. This is needed during the export and we have to skip it here
                            int tempNVectors;
                            if(fread(&tempNVectors, sizeof(int), 1, rf) != 1) { fclose(rf); return(false); }

                        }
                        else
                        {
                            // wrong version
                            fclose(rf);
                            return(false);
                        }
                        unsigned int groups;
                        char blockId[5];
                        blockId[4] = 0;
                        int blocksize;

                        if(fread(&groups, sizeof(unsigned int), 1, rf) != 1) { fclose(rf); return(false); }

                        for(int g=0;g<(int)groups;g++)
                        {
                            // group MUST NOT have more then 65536 indexes !! Array will have a problem with that !! (strange ...)
                            Array<int> tempIndexArray;
                            Array<Vector3> tempVertexArray;

                            AABSPTree<Triangle> *gtree = new AABSPTree<Triangle>();

                            unsigned int flags;
                            if(fread(&flags, sizeof(unsigned int), 1, rf) != 1) { fclose(rf); return(false); }

                            unsigned int branches;
                            if(fread(&blockId, 4, 1, rf) != 1) { fclose(rf); return(false); }
                            if(strcmp(blockId, "GRP ") != 0) { fclose(rf); return(false); }
                            if(fread(&blocksize, sizeof(int), 1, rf) != 1) { fclose(rf); return(false); }
                            if(fread(&branches, sizeof(unsigned int), 1, rf) != 1) { fclose(rf); return(false); }
                            for(int b=0;b<(int)branches; b++)
                            {
                                unsigned int indexes;
                                // indexes for each branch (not used jet)
                                if(fread(&indexes, sizeof(unsigned int), 1, rf) != 1) { fclose(rf); return(false); }
                            }

                            // ---- indexes
                            if(fread(&blockId, 4, 1, rf) != 1) { fclose(rf); return(false); }
                            if(strcmp(blockId, "INDX") != 0) { fclose(rf); return(false); }
                            if(fread(&blocksize, sizeof(int), 1, rf) != 1) { fclose(rf); return(false); }
                            unsigned int nindexes;
                            if(fread(&nindexes, sizeof(unsigned int), 1, rf) != 1) { fclose(rf); return(false); }
                            if(nindexes >0)
                            {
                                unsigned short *indexarray = new unsigned short[nindexes*sizeof(unsigned short)];
                                if(fread(indexarray, sizeof(unsigned short), nindexes, rf) != nindexes) { fclose(rf); return(false); }
                                for(int i=0;i<(int)nindexes; i++)
                                {
                                    unsigned short val = indexarray[i];
                                    tempIndexArray.append(val);
                                }
                                delete indexarray;
                            }

                            // ---- vectors
                            if(fread(&blockId, 4, 1, rf) != 1) {fclose(rf); return(false); }
                            if(strcmp(blockId, "VERT") != 0) { fclose(rf); return(false); }
                            if(fread(&blocksize, sizeof(int), 1, rf) != 1) { fclose(rf); return(false); }
                            unsigned int nvectors;
                            if(fread(&nvectors, sizeof(int), 1, rf) != 1) { fclose(rf); return(false); }
                            float *vectorarray = 0;
                            if(nvectors >0)
                            {
                                vectorarray = new float[nvectors*sizeof(float)*3];
                                if(fread(vectorarray, sizeof(float)*3, nvectors, rf) != nvectors) { fclose(rf); return(false); }
                            }
                            // ----- liquit
                            if(flags & 1)
                            {
                                // we have liquit -> not handled yet ... skip
                                if(fread(&blockId, 4, 1, rf) != 1) { fclose(rf); return(false); }
                                if(strcmp(blockId, "LIQU") != 0) { fclose(rf); return(false); }
                                if(fread(&blocksize, sizeof(int), 1, rf) != 1) { fclose(rf); return(false); }
                                fseek(rf, blocksize, SEEK_CUR);
                            }

                            for(unsigned int i=0, indexNo=0; indexNo<nvectors; indexNo++)
                            {
                                Vector3 v = Vector3(vectorarray[i+2], vectorarray[i+1], vectorarray[i+0]);
                                i+=3;
                                v = pModelPosition.transform(v);

                                float swapy = v.y;
                                v.y = v.x;
                                v.x = swapy;

                                tempVertexArray.append(v);
                            }

                            // ---- calculate triangles
                            int rest = nindexes%3;
                            if(rest != 0)
                            {
                                nindexes -= rest;
                            }

                            for(unsigned int i=0;i<(nindexes);)
                            {
                                Triangle t = Triangle(tempVertexArray[tempIndexArray[i+2]], tempVertexArray[tempIndexArray[i+1]], tempVertexArray[tempIndexArray[i+0]] );
                                i+=3;
                                trianglecount++;
                                if(g>= startgroup && g <= endgroup)
                                {
                                    gtree->insert(t);
                                }
                            }

                            if(vectorarray != 0)
                            {
                                delete vectorarray;
                            }

                            if(gtree->size() >0)
                            {
                                gtree->balance();
                                SubModel *sm = new SubModel(gtree);
                                #ifdef _ASSEMBLER_DEBUG
                                if(::g_df) fprintf(::g_df,"group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size());
                                if(sm->getNTriangles() !=  gtree->memberTable.size())
                                {
                                    if(::g_df) fprintf(::g_df,"ERROR !!!! group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size());
                                }
                                #endif
                                sm->setBasePosition(pModelPosition.iPos);
                                pMainTree->insert(sm);
                            }
                            delete gtree;
                        }
                        fclose(rf);
                        result = true;
                    }
                    return(result);
                }
Example #15
0
//
// CheckIWAD
//
// Tries to find an IWAD from a set of know IWAD names, and checks the first
// one found's contents to determine whether registered/commercial features
// should be executed (notably loading PWAD's).
//
static bool CheckIWAD (std::string suggestion, std::string &titlestring)
{
	static const char *doomwadnames[] =
	{
		"doom2f.wad",
		"doom2.wad",
		"plutonia.wad",
		"tnt.wad",
		"doomu.wad", // Hack from original Linux version. Not necessary, but I threw it in anyway.
		"doom.wad",
		"doom1.wad",
		"freedoom.wad",
		"freedm.wad",
		"chex.wad",		// [ML] 1/7/10: Hello Chex Quest!
		NULL
	};

	std::string iwad;
	std::string iwad_file;
	int i;

	if(suggestion.length())
	{
		std::string found = BaseFileSearch(suggestion, ".WAD");

		if(found.length())
			iwad = found;
		else
		{
			if(M_FileExists(suggestion.c_str()))
				iwad = suggestion;
		}
		/*	[ML] Removed 1/13/10: we can trust the user to provide an iwad
		if(iwad.length())
		{
			FILE *f;

			if ( (f = fopen (iwad.c_str(), "rb")) )
			{
				wadinfo_t header;
				fread (&header, sizeof(header), 1, f);
				header.identification = LONG(header.identification);
				if (header.identification != IWAD_ID)
				{
					if(header.identification == PWAD_ID)
					{
						Printf(PRINT_HIGH, "Suggested file is a PWAD, not an IWAD: %s \n", iwad.c_str());
					}
					else
					{
						Printf(PRINT_HIGH, "Suggested file is not an IWAD: %s \n", iwad.c_str());
					}
					iwad = "";
				}
				fclose(f);
			}
		}
		*/
	}

	if(!iwad.length())
	{
		// Search for a pre-defined IWAD from the list above
		for (i = 0; doomwadnames[i]; i++)
		{
			std::string found = BaseFileSearch(doomwadnames[i]);

			if(found.length())
			{
				iwad = found;
				break;
			}
		}
	}

	// Now scan the contents of the IWAD to determine which one it is
	if (iwad.length())
	{
#define NUM_CHECKLUMPS 9
		static const char checklumps[NUM_CHECKLUMPS][8] = {
			"E1M1", "E2M1", "E4M1", "MAP01",
			{ 'A','N','I','M','D','E','F','S'},
			"FINAL2", "REDTNT2", "CAMO1",
			{ 'E','X','T','E','N','D','E','D'}
		};
		int lumpsfound[NUM_CHECKLUMPS];
		wadinfo_t header;
		FILE *f;
		M_ExtractFileName(iwad,iwad_file);

		memset (lumpsfound, 0, sizeof(lumpsfound));
		if ( (f = fopen (iwad.c_str(), "rb")) )
		{
			fread (&header, sizeof(header), 1, f);
			header.identification = LONG(header.identification);
			if (header.identification == IWAD_ID ||
				header.identification == PWAD_ID)
			{
				header.numlumps = LONG(header.numlumps);
				if (0 == fseek (f, LONG(header.infotableofs), SEEK_SET))
				{
					for (i = 0; i < header.numlumps; i++)
					{
						filelump_t lump;
						int j;

						if (0 == fread (&lump, sizeof(lump), 1, f))
							break;
						for (j = 0; j < NUM_CHECKLUMPS; j++)
							if (!strnicmp (lump.name, checklumps[j], 8))
								lumpsfound[j]++;
					}
				}
			}
			fclose (f);
		}

		gamemode = undetermined;

		if (lumpsfound[3])
		{
			gamemode = commercial;
			gameinfo = CommercialGameInfo;
			if (lumpsfound[6])
			{
				gamemission = pack_tnt;
				titlestring = "DOOM 2: TNT - Evilution";
			}
			else if (lumpsfound[7])
			{
				gamemission = pack_plut;
				titlestring = "DOOM 2: Plutonia Experiment";
			}
			else
			{
				gamemission = doom2;
				titlestring = "DOOM 2: Hell on Earth";
			}
		}
		else if (lumpsfound[0])
		{
			gamemission = doom;
			if (lumpsfound[1])
			{
				if (lumpsfound[2])
				{
					if (!StdStringCompare(iwad_file,"chex.wad",true))	// [ML] 1/7/10: HACK - There's no unique lumps in the chex quest
					{								// iwad.  It's ultimate doom with their stuff replacing most things.
						gamemission = chex;
						gamemode = retail_chex;
						gameinfo = RetailGameInfo;
						titlestring = "Chex Quest";
					}
					else
					{
						gamemode = retail;
						gameinfo = RetailGameInfo;
						titlestring = "The Ultimate DOOM";
					}
				}
				else
				{
					gamemode = registered;
					gameinfo = RegisteredGameInfo;
					titlestring = "DOOM Registered";
				}
			}
			else
			{
				gamemode = shareware;
				gameinfo = SharewareGameInfo;
				titlestring = "DOOM Shareware";
			}
		}
	}

	if (gamemode == undetermined)
	{
		gameinfo = SharewareGameInfo;
	}

	if (iwad.length())
		wadfiles.push_back(iwad);

	return iwad.length() ? true : false;
}
Example #16
0
bool JavaString::operator==(const std::string& str) const {
	jsize len = Length();
	if(len != (jsize) str.length())
		return false;
	return str == Value();
}
Example #17
0
//
// denis - BaseFileSearchDir
// Check single paths for a given file with a possible extension
// Case insensitive, but returns actual file name
//
std::string BaseFileSearchDir(std::string dir, std::string file, std::string ext, std::string hash = "")
{
	std::string found;

	if(dir[dir.length() - 1] != PATHSEPCHAR)
		dir += PATHSEP;

	std::transform(hash.begin(), hash.end(), hash.begin(), toupper);
	std::string dothash = ".";
	if(hash.length())
		dothash += hash;
	else
		dothash = "";

	// denis - list files in the directory of interest, case-desensitize
	// then see if wanted wad is listed
#ifdef UNIX
	// denis - todo -find a way to deal with dir="./" and file="DIR/DIR/FILE.WAD"
	struct dirent **namelist = 0;
	int n = scandir(dir.c_str(), &namelist, 0, alphasort);

	for(int i = 0; i < n && namelist[i]; i++)
	{
		std::string d_name = namelist[i]->d_name;

		M_Free(namelist[i]);

		if(!found.length())
		{
			if(d_name == "." || d_name == "..")
				continue;

			std::string tmp = d_name;
			std::transform(tmp.begin(), tmp.end(), tmp.begin(), toupper);

			if(file == tmp || (file + ext) == tmp || (file + dothash) == tmp || (file + ext + dothash) == tmp)
			{
				std::string local_file = (dir + d_name).c_str();
				std::string local_hash = W_MD5(local_file.c_str());

				if(!hash.length() || hash == local_hash)
				{
					found = d_name;
				}
				else if(hash.length())
				{
					Printf (PRINT_HIGH, "WAD at %s does not match required copy\n", local_file.c_str());
					Printf (PRINT_HIGH, "Local MD5: %s\n", local_hash.c_str());
					Printf (PRINT_HIGH, "Required MD5: %s\n\n", hash.c_str());
				}
			}
		}
	}

	M_Free(namelist);
#else
	if(dir[dir.length() - 1] != PATHSEPCHAR)
		dir += PATHSEP;

	std::string all_ext = dir + "*";
	//all_ext += ext;

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = FindFirstFile(all_ext.c_str(), &FindFileData);
	DWORD dwError = GetLastError();

	if (hFind == INVALID_HANDLE_VALUE)
	{
		Printf (PRINT_HIGH, "FindFirstFile failed for %s\n", all_ext.c_str());
		Printf (PRINT_HIGH, "GetLastError: %d\n", dwError);
		return "";
	}

	while (true)
	{
		if(!FindNextFile(hFind, &FindFileData))
		{
			dwError = GetLastError();

			if(dwError != ERROR_NO_MORE_FILES)
				Printf (PRINT_HIGH, "FindNextFile failed. GetLastError: %d\n", dwError);

			break;
		}

		if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			continue;

		std::string tmp = FindFileData.cFileName;
		std::transform(tmp.begin(), tmp.end(), tmp.begin(), toupper);

		if(file == tmp || (file + ext) == tmp || (file + dothash) == tmp || (file + ext + dothash) == tmp)
		{
			std::string local_file = (dir + FindFileData.cFileName).c_str();
			std::string local_hash = W_MD5(local_file.c_str());

			if(!hash.length() || hash == local_hash)
			{
				found = FindFileData.cFileName;
				break;
			}
			else if(hash.length())
			{
				Printf (PRINT_HIGH, "WAD at %s does not match required copy\n", local_file.c_str());
				Printf (PRINT_HIGH, "Local MD5: %s\n", local_hash.c_str());
				Printf (PRINT_HIGH, "Required MD5: %s\n\n", hash.c_str());
			}
		}
	}

	FindClose(hFind);
#endif

	return found;
}
Example #18
0
bool isOperation(const std::string &item) {
    char c = item[0];
    return (item.length() == 1) &&
        (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
Example #19
0
  void CIFData::ExtractSpacegroup(const bool verbose)
  {
    map<ci_string,string>::const_iterator positem;
    bool found = false;
    positem=mvItem.find("_space_group_IT_number");
    if(positem!=mvItem.end())
      {
        mSpacegroupNumberIT=CIFNumeric2Int(positem->second);
        found = true;
        if(verbose) cout<<"Found spacegroup IT number:"<<mSpacegroupNumberIT<<endl;
      }
    else
      {
        positem=mvItem.find("_symmetry_Int_Tables_number");
        if(positem!=mvItem.end())
          {
            mSpacegroupNumberIT=CIFNumeric2Int(positem->second);
            found = true;
            if(verbose) cout<<"Found spacegroup IT number (with OBSOLETE CIF #1.0 TAG):"<<mSpacegroupNumberIT<<endl;
          }
        else {
          positem=mvItem.find("_symmetry_group_IT_number");
          if(positem!=mvItem.end())
          {
            mSpacegroupNumberIT=CIFNumeric2Int(positem->second);
            found = true;
            if(verbose) cout<<"Found spacegroup IT number (with NON-STANDARD CIF TAG):"<<mSpacegroupNumberIT<<endl;
          }
          else
            mSpacegroupNumberIT=0;
        }
      }

    positem=mvItem.find("_space_group_name_Hall");
    if(positem!=mvItem.end())
      {
        mSpacegroupSymbolHall=positem->second;
        found = true;
        if(verbose) cout<<"Found spacegroup Hall symbol:"<<mSpacegroupSymbolHall<<endl;
      }
    else
      {
        positem=mvItem.find("_symmetry_space_group_name_Hall");
        if(positem!=mvItem.end())
          {
            mSpacegroupSymbolHall=positem->second;
            found = true;
            if(verbose) cout<<"Found spacegroup Hall symbol (with OBSOLETE CIF #1.0 TAG):"<<mSpacegroupSymbolHall<<endl;
          }
      }

    positem=mvItem.find("_space_group_name_H-M_alt");
    if(positem!=mvItem.end())
      {
        mSpacegroupHermannMauguin=positem->second;
        found = true;
        if(verbose) cout<<"Found spacegroup Hermann-Mauguin symbol:"<<mSpacegroupHermannMauguin<<endl;
      }
    else
      {
        positem=mvItem.find("_symmetry_space_group_name_H-M");
        if(positem!=mvItem.end())
          {
            mSpacegroupHermannMauguin=positem->second;
            found = true;
            if(verbose) cout<<"Found spacegroup Hermann-Mauguin symbol (with OBSOLETE CIF #1.0 TAG):"<<mSpacegroupHermannMauguin<<endl;
          }
      }
    mSpaceGroup=NULL;
    if (mSpacegroupNumberIT != 0) {
      mSpaceGroup = SpaceGroup::GetSpaceGroup(mSpacegroupNumberIT);
    }
    else if (mSpacegroupSymbolHall.length() > 0) {
      mSpaceGroup = SpaceGroup::GetSpaceGroup(mSpacegroupSymbolHall);
    }
    else if (mSpacegroupHermannMauguin.length() > 0) {
      mSpaceGroup = SpaceGroup::GetSpaceGroup(mSpacegroupHermannMauguin);
    }
    else {
      SpaceGroup *sg = new SpaceGroup();
      positem=mvItem.find("_symmetry_equiv_pos_as_xyz");
      if(positem!=mvItem.end())
        {
          sg->AddTransform (positem->second);
          found = true;
        }
      else {
        for(map<set<ci_string>,map<ci_string,vector<string> > >::const_iterator loop=mvLoop.begin();
            loop!=mvLoop.end();++loop)
          {
            map<ci_string,vector<string> >::const_iterator pos;
            unsigned i, nb;
            pos=loop->second.find("_symmetry_equiv_pos_as_xyz");
            if (pos!=loop->second.end())
              {
                nb=pos->second.size();
                found = true;
                for (i = 0; i < nb; i++)
                  sg->AddTransform(pos->second[i]);
                break; // found the transforms, so we have done with them
              }
          }
        if (found)
          mSpaceGroup = SpaceGroup::Find(sg);
        delete sg;
      }
    }
    if (mSpaceGroup != NULL)
      // set the space group name to Hall symbol
      mSpacegroupSymbolHall = mSpaceGroup->GetHallName();
  }
Example #20
0
void MBConnection::createPreparedStatements()
{
  this->_insPlayerRowStatement = mysql_stmt_init(this->_conn);
  this->_insWordRowStatement = mysql_stmt_init(this->_conn);
  this->_insConvRowStatement = mysql_stmt_init(this->_conn);
  this->_getRandomStartingWordStatement = mysql_stmt_init(this->_conn);
  this->_getRandomNextWordStatement = mysql_stmt_init(this->_conn);
  this->_getProperCaseStatement = mysql_stmt_init(this->_conn);
  this->_getBigramCountStatement = mysql_stmt_init(this->_conn);  
  this->_getPlayerLineCountStatement = mysql_stmt_init(this->_conn);
  this->_getPlayerNameStatement = mysql_stmt_init(this->_conn);
  this->_insTextRowStatement = mysql_stmt_init(this->_conn);
  this->_getRandomChatMessageStatement = mysql_stmt_init(this->_conn);

  if (!this->_insPlayerRowStatement || 
    !this->_insWordRowStatement || 
    !this->_insConvRowStatement ||
    !this->_getRandomStartingWordStatement ||
    !this->_getRandomNextWordStatement ||
    !this->_getProperCaseStatement ||
    !this->_getBigramCountStatement ||
    !this->_getPlayerLineCountStatement ||
    !this->_getPlayerNameStatement ||
    !this->_insTextRowStatement ||
    !this->_getRandomChatMessageStatement)
  {
    std::cout << "Initializating prepared statements failed" << std::endl;
    throw 0;
  }

  static const std::string INSERT_PLAYER_ROW_SQL("INSERT INTO markovsbot.player_names (id,name) VALUES (?,?)");
  static const std::string INSERT_WORD_ROW_SQL("INSERT INTO markovsbot.words (id,word) VALUES (?,?)");
  static const std::string INSERT_CONV_ROW_SQL("INSERT INTO markovsbot.conversations (name_id, word_a, word_b, is_starting) VALUES (?,?,?,?)");

  static const std::string GET_RANDOM_STARTING_WORD_SQL("SELECT markovsbot.words.id, markovsbot.words.word FROM ("
    "(SELECT markovsbot.conversations.word_a FROM markovsbot.player_names INNER JOIN markovsbot.conversations "
      "ON markovsbot.player_names.id=markovsbot.conversations.name_id "
      "WHERE markovsbot.player_names.name=? AND markovsbot.conversations.is_starting=1) "
    "AS t1) "
    "INNER JOIN markovsbot.words ON markovsbot.words.id=t1.word_a ORDER BY RAND() LIMIT 1");

  static const std::string GET_RANDOM_NEXT_WORD_SQL("SELECT markovsbot.words.id, markovsbot.words.word FROM ("
    "(SELECT markovsbot.conversations.word_b FROM markovsbot.player_names INNER JOIN markovsbot.conversations "
      "ON markovsbot.player_names.id=markovsbot.conversations.name_id "
      "WHERE markovsbot.player_names.name=? AND markovsbot.conversations.word_a=?) "
    "AS t1) "
    "INNER JOIN markovsbot.words ON markovsbot.words.id=t1.word_b ORDER BY RAND() LIMIT 1");

  static const std::string GET_PROPER_CASE_SQL("SELECT markovsbot.player_names.name FROM markovsbot.player_names WHERE name=? LIMIT 1");
  static const std::string GET_BIGRAM_COUNT_SQL("SELECT name_id, COUNT(*) AS c FROM ("
      "SELECT * FROM markovsbot.words WHERE word=?"
    ") AS t1, ("
      "SELECT * FROM markovsbot.words WHERE word=?"
    ") AS t2 INNER JOIN markovsbot.conversations WHERE markovsbot.conversations.word_a=t1.id AND "
    "markovsbot.conversations.word_b=t2.id GROUP BY markovsbot.conversations.name_id ORDER BY c DESC LIMIT 20");
  static const std::string GET_PLAYER_LINE_COUNT_SQL("SELECT COUNT(*) FROM markovsbot.conversations WHERE name_id=? GROUP BY name_id");
  static const std::string GET_PLAYER_NAME_SQL("SELECT name FROM markovsbot.player_names WHERE id=?");
  static const std::string INSERT_TEXT_SQL("INSERT INTO markovsbot.fulltext_log (name, `text`) VALUES (?, ?)");
  static const std::string GET_RANDOM_CHAT_MESSAGE_SQL("SELECT `name`,`text` FROM markovsbot.fulltext_log WHERE MATCH(`text`) AGAINST (CONCAT('\"', ?, '\"') IN BOOLEAN MODE) ORDER BY RAND() DESC LIMIT 1");

  int r1 = mysql_stmt_prepare(this->_insPlayerRowStatement, INSERT_PLAYER_ROW_SQL.c_str(), INSERT_PLAYER_ROW_SQL.length());
  int r2 = mysql_stmt_prepare(this->_insWordRowStatement, INSERT_WORD_ROW_SQL.c_str(), INSERT_WORD_ROW_SQL.length());
  int r3 = mysql_stmt_prepare(this->_insConvRowStatement, INSERT_CONV_ROW_SQL.c_str(), INSERT_CONV_ROW_SQL.length());

  int r4 = mysql_stmt_prepare(this->_getRandomStartingWordStatement, GET_RANDOM_STARTING_WORD_SQL.c_str(), GET_RANDOM_STARTING_WORD_SQL.length());
  int r5 = mysql_stmt_prepare(this->_getRandomNextWordStatement, GET_RANDOM_NEXT_WORD_SQL.c_str(), GET_RANDOM_NEXT_WORD_SQL.length());

  int r6 = mysql_stmt_prepare(this->_getProperCaseStatement, GET_PROPER_CASE_SQL.c_str(), GET_PROPER_CASE_SQL.length());
  int r7 = mysql_stmt_prepare(this->_getBigramCountStatement, GET_BIGRAM_COUNT_SQL.c_str(), GET_BIGRAM_COUNT_SQL.length());
  int r8 = mysql_stmt_prepare(this->_getPlayerLineCountStatement, GET_PLAYER_LINE_COUNT_SQL.c_str(), GET_PLAYER_LINE_COUNT_SQL.length());
  int r9 = mysql_stmt_prepare(this->_getPlayerNameStatement, GET_PLAYER_NAME_SQL.c_str(), GET_PLAYER_NAME_SQL.length());

  int r10 = mysql_stmt_prepare(this->_insTextRowStatement, INSERT_TEXT_SQL.c_str(), INSERT_TEXT_SQL.length());
  int r11 = mysql_stmt_prepare(this->_getRandomChatMessageStatement, GET_RANDOM_CHAT_MESSAGE_SQL.c_str(), GET_RANDOM_CHAT_MESSAGE_SQL.length());

  if (r1 || r2 || r3 || r4 || r5 || r6 || r7 || r8 || r9 || r10 || r11)
  {
    std::cout << "Creating prepared statements failed" << std::endl;
    throw 0;
  }
}
Example #21
0
Chromosome runGA(std::string target, int popSize, double mr, double cr)
{
	// implement genetic algorithm here
	// use a vector<Chromosome> for the population
	// I recommend using STL algorithms such as std::sort

	// remember, the GA is a loop until you find a chromosome
	// of fitness 0

	// on each iteration, you should be generating a new population
	// of twice the size of popSize, filling it with chromosomes
	// that have been mutated, crossed, and/or copied based on
	// the probabilities given by mr and cr
	// then sort it and keep only the best half as the population
	// for the next iteration
	// when you find a chromosome of fitness 0, you have finished and
	// you should return it

	std::vector<Chromosome> population;
	population = newVector(population, popSize, target.length());

	Chromosome solution(population[0]);
	int iteration = 0;
	do
	{
		std::vector<Chromosome> newPopulation;

		for (int i = 0; i<(popSize * 2); ++i)
		{
			int randomIndex = rand() % population.size();
			Chromosome aChromosome(population[randomIndex]);

			double randomPercentage = (rand() % 101) / 100.0;
			if (randomPercentage <= mr)
			{
				aChromosome = aChromosome.mutate();
			}

			randomPercentage = (rand() % 101) / 100.0;
			if (randomPercentage <= cr)
			{
				randomIndex = rand() % population.size();

				aChromosome = aChromosome.crossover(population[randomIndex]);
			}

			newPopulation.push_back(aChromosome);
		}

		auto lessThan = [&target](Chromosome& a, Chromosome& b)->bool { return a.fitness(target) < b.fitness(target); };
		std::sort(newPopulation.begin(), newPopulation.end(), lessThan);

		copyHalf(newPopulation, population);

		solution = population[0];

		std::cout << "Iteration number: " << iteration << std::endl;
		std::cout << "Solution: " << solution << std::endl;
		++iteration;

	} while (solution.fitness(target));
	return solution;
}
Example #22
0
static std::string getValueFromOs_release(std::string key)
{
  FILE* os_rel = fopen("/etc/os-release", "r");
  if (!os_rel)
    return "";

  char* buf = new char[10 * 1024]; // more than enough
  size_t len = fread(buf, 1, 10 * 1024, os_rel);
  fclose(os_rel);
  if (len == 0)
  {
    delete[] buf;
    return "";
  }

  std::string content(buf, len);
  delete[] buf;

  // find begin of value string
  size_t valStart = 0, seachPos;
  key += '=';
  if (content.compare(0, key.length(), key) == 0)
    valStart = key.length();
  else
  {
    key = "\n" + key;
    seachPos = 0;
    do
    {
      seachPos = content.find(key, seachPos);
      if (seachPos == std::string::npos)
        return "";
      if (seachPos == 0 || content[seachPos - 1] != '\\')
        valStart = seachPos + key.length();
      else
        seachPos++;
    } while (valStart == 0);
  }

  if (content[valStart] == '\n')
    return "";
  
  // find end of value string
  seachPos = valStart;
  do
  {
    seachPos = content.find('\n', seachPos + 1);
  } while (seachPos != std::string::npos && content[seachPos - 1] == '\\');
  size_t const valEnd = seachPos;

  std::string value(content, valStart, valEnd - valStart);
  if (value.empty())
    return value;

  // remove quotes
  if (value[0] == '\'' || value[0] == '"')
  {
    if (value.length() < 2)
      return value;
    size_t qEnd = value.rfind(value[0]);
    if (qEnd != std::string::npos)
    {
      value.erase(qEnd);
      value.erase(0, 1);
    }
  }

  // unescape characters
  for (size_t slashPos = value.find('\\'); slashPos < value.length() - 1; slashPos = value.find('\\', slashPos))
  {
    if (value[slashPos + 1] == '\n')
      value.erase(slashPos, 2);
    else
    {
      value.erase(slashPos, 1);
      slashPos++; // skip unescaped character
    }
  }

  return value;
}
//Helper function of parsing message list table
const resource_message_list resource_message_list_reader::parse_message_list(const std::string& resource_data)
{
	resource_message_list ret;

	//Check resource data length
	if(resource_data.length() < sizeof(message_resource_data))
		throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table);

	const message_resource_data* message_data = reinterpret_cast<const message_resource_data*>(resource_data.data());

	//Check resource data length more carefully and some possible overflows
	if(message_data->NumberOfBlocks >= pe_utils::max_dword / sizeof(message_resource_block)
		|| !pe_utils::is_sum_safe(message_data->NumberOfBlocks * sizeof(message_resource_block), sizeof(message_resource_data))
		|| resource_data.length() < message_data->NumberOfBlocks * sizeof(message_resource_block) + sizeof(message_resource_data))
		throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table);

	//Iterate over all message resource blocks
	for(unsigned long i = 0; i != message_data->NumberOfBlocks; ++i)
	{
		//Get block
		const message_resource_block* block =
			reinterpret_cast<const message_resource_block*>(resource_data.data() + sizeof(message_resource_data) - sizeof(message_resource_block) + sizeof(message_resource_block) * i);

		//Check resource data length and IDs
		if(resource_data.length() < block->OffsetToEntries || block->LowId > block->HighId)
			throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table);

		unsigned long current_pos = 0;
		static const unsigned long size_of_entry_headers = 4;
		//List all message resource entries in block
		for(uint32_t curr_id = block->LowId; curr_id <= block->HighId; curr_id++)
		{
			//Check resource data length and some possible overflows
			if(!pe_utils::is_sum_safe(block->OffsetToEntries, current_pos)
				|| !pe_utils::is_sum_safe(block->OffsetToEntries + current_pos, size_of_entry_headers)
				|| resource_data.length() < block->OffsetToEntries + current_pos + size_of_entry_headers)
				throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table);

			//Get entry
			const message_resource_entry* entry = reinterpret_cast<const message_resource_entry*>(resource_data.data() + block->OffsetToEntries + current_pos);

			//Check resource data length and entry length and some possible overflows
			if(entry->Length < size_of_entry_headers
				|| !pe_utils::is_sum_safe(block->OffsetToEntries + current_pos, entry->Length)
				|| resource_data.length() < block->OffsetToEntries + current_pos + entry->Length
				|| entry->Length < size_of_entry_headers)
				throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table);

			if(entry->Flags & message_resource_unicode)
			{
				//If string is UNICODE
				//Check its length
				if(entry->Length % 2)
					throw pe_exception("Incorrect resource message table", pe_exception::resource_incorrect_message_table);

				//Add ID and string to message table
#ifdef PE_BLISS_WINDOWS
				ret.insert(std::make_pair(curr_id, message_table_item(
					std::wstring(reinterpret_cast<const wchar_t*>(resource_data.data() + block->OffsetToEntries + current_pos + size_of_entry_headers),
					(entry->Length - size_of_entry_headers) / 2)
					)));
#else
				ret.insert(std::make_pair(curr_id, message_table_item(
					pe_utils::from_ucs2(u16string(reinterpret_cast<const unicode16_t*>(resource_data.data() + block->OffsetToEntries + current_pos + size_of_entry_headers),
					(entry->Length - size_of_entry_headers) / 2))
					)));
#endif
			}
			else
			{
				//If string is ANSI
				//Add ID and string to message table
				ret.insert(std::make_pair(curr_id, message_table_item(
					std::string(resource_data.data() + block->OffsetToEntries + current_pos + size_of_entry_headers,
					entry->Length - size_of_entry_headers)
					)));
			}

			//Go to next entry
			current_pos += entry->Length;
		}
	}

	return ret;
}
Example #24
0
Nibbler::Nibbler (const std::string& input)
: _input (std::make_shared <std::string> (input))
, _length (input.length ())
, _cursor (0)
{
}
Example #25
0
void CDC::converteStringParaMaiuscula(std::string &str) {
    for(unsigned int pos=0; pos<str.length(); pos++) {
        if(str[pos]>=97 && str[pos]<=122) str[pos]-=32;
    }
}
Example #26
0
bool Nibbler::getDate (const std::string& format, time_t& t)
{
  auto i = _cursor;

  int month  = -1;   // So we can check later.
  int day    = -1;
  int year   = -1;
  int hour   = -1;
  int minute = -1;
  int second = -1;

  // For parsing, unused.
  int wday    = -1;
  int week    = -1;

  for (unsigned int f = 0; f < format.length (); ++f)
  {
    switch (format[f])
    {
    case 'm':
    case 'M':
      if (! parseDigits(i, month, 2, format[f] == 'M'))
        return false;
      break;

    case 'd':
    case 'D':
      if (! parseDigits(i, day, 2, format[f] == 'D'))
        return false;
      break;

    case 'y':
    case 'Y':
      if (! parseDigits(i, year, format[f] == 'y' ? 2 : 4))
        return false;
      if (format[f] == 'y')
          year += 2000;
      break;

    case 'h':
    case 'H':
      if (! parseDigits(i, hour, 2, format[f] == 'H'))
        return false;
      break;

    case 'n':
    case 'N':
      if (! parseDigits(i, minute, 2, format[f] == 'N'))
        return false;
      break;

    case 's':
    case 'S':
      if (! parseDigits(i, second, 2, format[f] == 'S'))
        return false;
      break;

    // Merely parse, not extract.
    case 'v':
    case 'V':
      if (! parseDigits(i, week, 2, format[f] == 'V'))
        return false;
      break;

    // Merely parse, not extract.
    case 'a':
    case 'A':
      if (i + 3 <= _length          &&
          ! Lexer::isDigit ((*_input)[i + 0]) &&
          ! Lexer::isDigit ((*_input)[i + 1]) &&
          ! Lexer::isDigit ((*_input)[i + 2]))
      {
        wday = ISO8601d::dayOfWeek (_input->substr (i, 3).c_str ());
        i += (format[f] == 'a') ? 3 : ISO8601d::dayName (wday).size ();
      }
      else
        return false;
      break;

    case 'b':
    case 'B':
      if (i + 3 <= _length          &&
          ! Lexer::isDigit ((*_input)[i + 0]) &&
          ! Lexer::isDigit ((*_input)[i + 1]) &&
          ! Lexer::isDigit ((*_input)[i + 2]))
      {
        if (month != -1)
          return false;
        month = ISO8601d::monthOfYear (_input->substr (i, 3).c_str());
        i += (format[f] == 'b') ? 3 : ISO8601d::monthName (month).size ();
      }
      else
        return false;
      break;

    default:
      if (i + 1 <= _length &&
          (*_input)[i] == format[f])
        ++i;
      else
        return false;
      break;
    }
  }

  // By default, the most global date variables that are undefined are put to
  // the current date (for instance, the year to the current year for formats
  // that lack Y/y). If even 'second' is undefined, then the date is parsed as
  // now.
  if (year == -1)
  {
    ISO8601d now;
    year = now.year ();
    if (month == -1)
    {
      month = now.month ();
      if (day == -1)
      {
        day = now.day ();
        if (hour == -1)
        {
          hour = now.hour ();
          if (minute == -1)
          {
            minute = now.minute ();
            if (second == -1)
              second = now.second ();
          }
        }
      }
    }
  }

  // Put all remaining undefined date variables to their default values (0 or
  // 1).
  month  = (month  == -1) ? 1 : month;
  day    = (day    == -1) ? 1 : day;
  hour   = (hour   == -1) ? 0 : hour;
  minute = (minute == -1) ? 0 : minute;
  second = (second == -1) ? 0 : second;

  // Check that values are correct
  if (! ISO8601d::valid (month, day, year, hour, minute, second))
    return false;

  // Convert to epoch.
  struct tm tms {};
  tms.tm_isdst = -1;   // Requests that mktime determine summer time effect.
  tms.tm_mon   = month - 1;
  tms.tm_mday  = day;
  tms.tm_year  = year - 1900;
  tms.tm_hour  = hour;
  tms.tm_min   = minute;
  tms.tm_sec   = second;

  t = mktime (&tms);
  _cursor = i;
  return true;
}
Example #27
0
int qwe(std::string s1, std::string s2){
    int result=0;
    int k,n;

    if (s1.length() >= s2.length()){
        for (int i=0; i < s1.length(); i++){
            k=0;
            n=i;
            if (result > (s1.length()-i)) break;
            if ((s1.length()-i) >= s2.length()){
                for (int j=0; j < s2.length(); j++){
                    if (s1[n] == s2[j]) k++;
                    n++;
                }
            }else{
                for (int j=0; j<(s1.length()-i); j++){
                    if (s1[n] == s2[j]) k++;
                    n++;
                }
            }
            if (result < k) result = k;

        }
    }

    if (s2.length() > s1.length()){
        for (int i=0; i < s2.length(); i++){
            k=0;
            n=i;
            if (result > (s2.length()-i)) break;
            if ((s2.length()-i) >= s1.length()){
                for (int j=0; j < s1.length(); j++){
                    if (s2[n] == s1[j]) k++;
                    n++;
                }
            }else{
                for (int j=0; j<(s2.length()-i); j++){
                    if (s2[n] == s1[j]) k++;
                    n++;
                }
            }
            if (result < k) result = k;

        }
    }

    return result;
}
Example #28
0
	static inline uint64_t Translate(std::string key)
	{
		return Hash64(key.c_str(), key.length());
	}
Example #29
0
namespace timing {

using namespace avsCommon::utils::logger;
using namespace avsCommon::utils::string;

/// String to identify log entries originating from this file.
static const std::string TAG("TimeUtils");

/**
 * Create a LogEntry using this file's TAG and the specified event string.
 *
 * @param The event string for this @c LogEntry.
 */
#define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event)

/// The length of the year element in an ISO-8601 formatted string.
static const int ENCODED_TIME_STRING_YEAR_STRING_LENGTH = 4;
/// The length of the month element in an ISO-8601 formatted string.
static const int ENCODED_TIME_STRING_MONTH_STRING_LENGTH = 2;
/// The length of the day element in an ISO-8601 formatted string.
static const int ENCODED_TIME_STRING_DAY_STRING_LENGTH = 2;
/// The length of the hour element in an ISO-8601 formatted string.
static const int ENCODED_TIME_STRING_HOUR_STRING_LENGTH = 2;
/// The length of the minute element in an ISO-8601 formatted string.
static const int ENCODED_TIME_STRING_MINUTE_STRING_LENGTH = 2;
/// The length of the second element in an ISO-8601 formatted string.
static const int ENCODED_TIME_STRING_SECOND_STRING_LENGTH = 2;
/// The length of the post-fix element in an ISO-8601 formatted string.
static const int ENCODED_TIME_STRING_POSTFIX_STRING_LENGTH = 4;
/// The dash separator used in an ISO-8601 formatted string.
static const std::string ENCODED_TIME_STRING_DASH_SEPARATOR_STRING = "-";
/// The 'T' separator used in an ISO-8601 formatted string.
static const std::string ENCODED_TIME_STRING_T_SEPARATOR_STRING = "T";
/// The colon separator used in an ISO-8601 formatted string.
static const std::string ENCODED_TIME_STRING_COLON_SEPARATOR_STRING = ":";
/// The plus separator used in an ISO-8601 formatted string.
static const std::string ENCODED_TIME_STRING_PLUS_SEPARATOR_STRING = "+";

/// The offset into an ISO-8601 formatted string where the year begins.
static const unsigned long ENCODED_TIME_STRING_YEAR_OFFSET = 0;
/// The offset into an ISO-8601 formatted string where the month begins.
static const unsigned long ENCODED_TIME_STRING_MONTH_OFFSET = ENCODED_TIME_STRING_YEAR_OFFSET +
                                                              ENCODED_TIME_STRING_YEAR_STRING_LENGTH +
                                                              ENCODED_TIME_STRING_DASH_SEPARATOR_STRING.length();
/// The offset into an ISO-8601 formatted string where the day begins.
static const unsigned long ENCODED_TIME_STRING_DAY_OFFSET = ENCODED_TIME_STRING_MONTH_OFFSET +
                                                            ENCODED_TIME_STRING_MONTH_STRING_LENGTH +
                                                            ENCODED_TIME_STRING_DASH_SEPARATOR_STRING.length();
/// The offset into an ISO-8601 formatted string where the hour begins.
static const unsigned long ENCODED_TIME_STRING_HOUR_OFFSET = ENCODED_TIME_STRING_DAY_OFFSET +
                                                             ENCODED_TIME_STRING_DAY_STRING_LENGTH +
                                                             ENCODED_TIME_STRING_T_SEPARATOR_STRING.length();
/// The offset into an ISO-8601 formatted string where the minute begins.
static const unsigned long ENCODED_TIME_STRING_MINUTE_OFFSET = ENCODED_TIME_STRING_HOUR_OFFSET +
                                                               ENCODED_TIME_STRING_HOUR_STRING_LENGTH +
                                                               ENCODED_TIME_STRING_COLON_SEPARATOR_STRING.length();
/// The offset into an ISO-8601 formatted string where the second begins.
static const unsigned long ENCODED_TIME_STRING_SECOND_OFFSET = ENCODED_TIME_STRING_MINUTE_OFFSET +
                                                               ENCODED_TIME_STRING_MINUTE_STRING_LENGTH +
                                                               ENCODED_TIME_STRING_COLON_SEPARATOR_STRING.length();

/// The total expected length of an ISO-8601 formatted string.
static const unsigned long ENCODED_TIME_STRING_EXPECTED_LENGTH =
    ENCODED_TIME_STRING_SECOND_OFFSET + ENCODED_TIME_STRING_SECOND_STRING_LENGTH +
    ENCODED_TIME_STRING_PLUS_SEPARATOR_STRING.length() + ENCODED_TIME_STRING_POSTFIX_STRING_LENGTH;

/**
 * Utility function that wraps localtime conversion to std::time_t.
 *
 * This function also creates a copy of the given timeStruct since mktime can
 * change the object.
 *
 * @param timeStruct Required pointer to timeStruct to be converted to time_t.
 * @param[out] ret Required pointer to object where the result will be saved.
 * @return Whether the conversion was successful.
 */
static bool convertToLocalTimeT(const std::tm* timeStruct, std::time_t* ret) {
    if (timeStruct == nullptr) {
        return false;
    }

    std::tm tmCopy = *timeStruct;
    *ret = std::mktime(&tmCopy);
    return *ret >= 0;
}

TimeUtils::TimeUtils() : m_safeCTimeAccess{SafeCTimeAccess::instance()} {
}

bool TimeUtils::convertToUtcTimeT(const std::tm* utcTm, std::time_t* ret) {
    std::time_t converted;
    std::time_t offset;

    if (ret == nullptr) {
        ACSDK_ERROR(LX("convertToUtcTimeT").m("return variable is null"));
        return false;
    }

    if (!convertToLocalTimeT(utcTm, &converted) || !localtimeOffset(&offset)) {
        ACSDK_ERROR(LX("convertToUtcTimeT").m("failed to convert to local time"));
        return false;
    }

    // adjust converted time
    *ret = converted - offset;
    return true;
}

bool TimeUtils::convert8601TimeStringToUnix(const std::string& timeString, int64_t* convertedTime) {
    // TODO : Use std::get_time once we only support compilers that implement this function (GCC 5.1+ / Clang 3.3+)

    if (!convertedTime) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("convertedTime parameter was nullptr."));
        return false;
    }

    std::tm timeInfo;

    if (timeString.length() != ENCODED_TIME_STRING_EXPECTED_LENGTH) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").d("unexpected time string length:", timeString.length()));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_YEAR_OFFSET, ENCODED_TIME_STRING_YEAR_STRING_LENGTH),
            &(timeInfo.tm_year))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing year. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_MONTH_OFFSET, ENCODED_TIME_STRING_MONTH_STRING_LENGTH),
            &(timeInfo.tm_mon))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing month. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_DAY_OFFSET, ENCODED_TIME_STRING_DAY_STRING_LENGTH),
            &(timeInfo.tm_mday))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing day. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_HOUR_OFFSET, ENCODED_TIME_STRING_HOUR_STRING_LENGTH),
            &(timeInfo.tm_hour))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing hour. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_MINUTE_OFFSET, ENCODED_TIME_STRING_MINUTE_STRING_LENGTH),
            &(timeInfo.tm_min))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing minute. Input:" + timeString));
        return false;
    }

    if (!stringToInt(
            timeString.substr(ENCODED_TIME_STRING_SECOND_OFFSET, ENCODED_TIME_STRING_SECOND_STRING_LENGTH),
            &(timeInfo.tm_sec))) {
        ACSDK_ERROR(LX("convert8601TimeStringToUnixFailed").m("error parsing second. Input:" + timeString));
        return false;
    }

    // adjust for C struct tm standard
    timeInfo.tm_isdst = 0;
    timeInfo.tm_year -= 1900;
    timeInfo.tm_mon -= 1;

    std::time_t convertedTimeT;
    bool ok = convertToUtcTimeT(&timeInfo, &convertedTimeT);

    if (!ok) {
        return false;
    }

    *convertedTime = static_cast<int64_t>(convertedTimeT);
    return true;
}

bool TimeUtils::getCurrentUnixTime(int64_t* currentTime) {
    if (!currentTime) {
        ACSDK_ERROR(LX("getCurrentUnixTimeFailed").m("currentTime parameter was nullptr."));
        return false;
    }

    auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    *currentTime = static_cast<int64_t>(now);

    return now >= 0;
}

bool TimeUtils::convertTimeToUtcIso8601Rfc3339(
    const std::chrono::high_resolution_clock::time_point& tp,
    std::string* iso8601TimeString) {
    // The length of the RFC 3339 string for the time is maximum 28 characters, include an extra byte for the '\0'
    // terminator.
    char buf[29];
    memset(buf, 0, sizeof(buf));

    // Need to assign it to time_t since time_t in some platforms is long long
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
    auto sec = std::chrono::duration_cast<std::chrono::seconds>(ms);
    const time_t timeSecs = static_cast<time_t>(sec.count());

    std::tm utcTm;
    if (!m_safeCTimeAccess->getGmtime(timeSecs, &utcTm)) {
        ACSDK_ERROR(LX("convertTimeToUtcIso8601Rfc3339").m("cannot retrieve tm struct"));
        return false;
    }

    // it's possible for std::strftime to correctly return length = 0, but not with the format string used.  In this
    // case length == 0 is an error.
    #ifndef __TizenRT__
    auto strftimeResult = std::strftime(buf, sizeof(buf) - 1, "%Y-%m-%dT%H:%M:%S", &utcTm);
    #else
    auto strftimeResult = strftime(buf, sizeof(buf) - 1, "%Y-%m-%dT%H:%M:%S", &utcTm);
    #endif
    if (strftimeResult == 0) {
        ACSDK_ERROR(LX("convertTimeToUtcIso8601Rfc3339Failed").m("strftime(..) failed"));
        return false;
    }

    std::stringstream millisecondTrailer;
    millisecondTrailer << buf << "." << std::setfill('0') << std::setw(3) << (ms.count() % 1000) << "Z";

    *iso8601TimeString = millisecondTrailer.str();
    return true;
}

bool TimeUtils::localtimeOffset(std::time_t* ret) {
    static const std::chrono::time_point<std::chrono::system_clock> timePoint{std::chrono::hours(24)};
    auto fixedTime = std::chrono::system_clock::to_time_t(timePoint);

    std::tm utcTm;
    std::time_t utc;
    std::tm localTm;
    std::time_t local;
    if (!m_safeCTimeAccess->getGmtime(fixedTime, &utcTm) || !convertToLocalTimeT(&utcTm, &utc) ||
        !m_safeCTimeAccess->getLocaltime(fixedTime, &localTm) || !convertToLocalTimeT(&localTm, &local)) {
        ACSDK_ERROR(LX("localtimeOffset").m("cannot retrieve tm struct"));
        return false;
    }

    *ret = utc - local;
    return true;
}

}  // namespace timing
    const char* odf_average(const char* out_name,
                     const char* const * file_names,
                     unsigned int num_files)
{
    static std::string error_msg,report;
    tessellated_icosahedron ti;
    float vs[3];
    image::basic_image<unsigned char,3> mask;
    std::vector<std::vector<float> > odfs;
    begin_prog("averaging");
    unsigned int half_vertex_count = 0;
    unsigned int row,col;
    float mni[16]={0};
    for (unsigned int index = 0;check_prog(index,num_files);++index)
    {
        const char* file_name = file_names[index];
        gz_mat_read reader;
        if(!reader.load_from_file(file_name))
        {
            error_msg = "Cannot open file ";
            error_msg += file_name;
            check_prog(0,0);
            return error_msg.c_str();
        }
        if(index == 0)
        {
            {
                const char* report_buf = 0;
                if(reader.read("report",row,col,report_buf))
                    report = std::string(report_buf,report_buf+row*col);
            }
            const float* odf_buffer;
            const short* face_buffer;
            const unsigned short* dimension;
            const float* vs_ptr;
            const float* fa0;
            const float* mni_ptr;
            unsigned int face_num,odf_num;
            error_msg = "";
            if(!reader.read("dimension",row,col,dimension))
                error_msg = "dimension";
            if(!reader.read("fa0",row,col,fa0))
                error_msg = "fa0";
            if(!reader.read("voxel_size",row,col,vs_ptr))
                error_msg = "voxel_size";
            if(!reader.read("odf_faces",row,face_num,face_buffer))
                error_msg = "odf_faces";
            if(!reader.read("odf_vertices",row,odf_num,odf_buffer))
                error_msg = "odf_vertices";
            if(!reader.read("trans",row,col,mni_ptr))
                error_msg = "trans";
            if(error_msg.length())
            {
                error_msg += " missing in ";
                error_msg += file_name;
                check_prog(0,0);
                return error_msg.c_str();
            }
            mask.resize(image::geometry<3>(dimension));
            for(unsigned int index = 0;index < mask.size();++index)
                if(fa0[index] != 0.0)
                    mask[index] = 1;
            std::copy(vs_ptr,vs_ptr+3,vs);
            ti.init(odf_num,odf_buffer,face_num,face_buffer);
            half_vertex_count = odf_num >> 1;
            std::copy(mni_ptr,mni_ptr+16,mni);
        }
        else
        // check odf consistency
        {