void Commands::showPosition(Player* player, const std::string& cmd, const std::string& param)
{
	if (!param.empty() && player->isAccessPlayer()) {
		StringVec exploded = explodeString(param, ", ", 2);
		if (!exploded.size() || exploded.size() < 3) {
			player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, "Not enough params.");
			return;
		}

		uint16_t x = atoi(exploded[0].c_str());
		uint16_t y = atoi(exploded[1].c_str());
		uint8_t z = atoi(exploded[2].c_str());

		Position oldPosition = player->getPosition();

		if (g_game.internalTeleport(player, Position(x, y, z)) == RET_NOERROR) {
			g_game.addMagicEffect(oldPosition, NM_ME_POFF, player->isInGhostMode());
			g_game.addMagicEffect(player->getPosition(), NM_ME_TELEPORT, player->isInGhostMode());
			return;
		}
	}

	const Position& pos = player->getPosition();

	std::ostringstream ss;
	ss << "Your current position is [X: " << pos.x << " | Y: " << pos.y << " | Z: " << pos.getZ() << "].";
	player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, ss.str());
}
Beispiel #2
0
void Grammar::add_alias( const string& alias, const StringVec& pairs )
{
    assert( pairs.size() % 2 == 0 ); // pairs must be even.
    if( alias == "field" ) {
        for( size_t i = 0 ; i < pairs.size() ; i += 2 ) {
            m_field_alias[pairs[i]] = pairs[i+1];
        }
    } else if ( alias == "pseudo" ) {
        for ( size_t i = 0; i < pairs.size(); i += 2 ) {
            m_num_pseudo_alias[pairs[i + 1]] = pairs[i];
        }
    } else if( alias == "unit" ) {
        for( size_t i = 0 ; i < pairs.size() ; i += 2 ) {
            m_unit_alias[pairs[i]] = pairs[i+1];
            string name = pairs[i+1];
            Unit unit = unit_null;
            if( name == "year" ) {
                unit = unit_year;
            } else if( name == "month" ) {
                unit = unit_month;
            } else if( name == "week" ) {
                unit = unit_week;
            } else if( name == "day" ) {
                unit = unit_day;
            } else {
                continue;
            }
            string key = make_key( pairs[i] );
            m_unit_type_alias[key] = unit;
        }
    }
}
Beispiel #3
0
Argument::Argument(const std::string& str,
                   SymbolTable symbol_table,
                   bool isRel,
                   Log log)
{
  StrVarMap v_map;

  if(str[0] != '(')
  {
    if(str[0] == '?')
    {
      t = Argument::Var;
      val = str;
      return;
    }

    Symbol* sym;
    size_t id = symbol_table.CheckEntry(str, 0, isRel, sym);

    if(sym == NULL) id = symbol_table.AddEntry(str, Location(), 0, isRel);

    if(isRel)
      t = Argument::Relation;
    else t = Argument::Function;
    value = id;
    return;
  }

  std::string cmd;
  StringVec args;
  if(!SeparateCommand(str, cmd, args, log))
  {
    log.Fatal << "Unable to construct argument from " << str << std::endl;
    return;
  }

  Symbol* sym;
  size_t id = symbol_table.CheckEntry(cmd, args.size(), isRel, sym);

  if(sym == NULL)
    id = symbol_table.AddEntry(cmd, Location(), args.size(), isRel);

  if(isRel)
    t = Argument::Relation;
  else t = Argument::Function;
  value = id;

  for(size_t i = 0;i < args.size();i++)
  {
    Argument *arg;
    if(id == SymbolTable::NotID || id == SymbolTable::OrID)
      arg = ConstructArgument(args[i], v_map, symbol_table, true, log);
    else
      arg = ConstructArgument(args[i], v_map, symbol_table, false, log);

    if(arg != NULL) this->args.push_back(arg);
  }
}
void SBFrameworksBuildPhase::loadFrameworkBlockListFromFile(const String& fileName)
{
    // Get the path to the file which has the block list.
    const BuildSettings bs(NULL);
    String templateDir = bs.getValue("VSIMPORTER_TEMPLATES_DIR");
    
    // If we have reached this far the folder is guaranteed to exist as we must have already called checkWinObjCSDK().
    assert(!sb_realpath(templateDir).empty());
    
    String blockListFilePath = joinPaths(templateDir, fileName);
    ifstream file(blockListFilePath);
    if (file.is_open())
    {
        String line;
        while (getline(file, line))
        {
            StringVec tokens;
            tokenize(line, tokens, "-> ");
            if (tokens.size() == 0)
            {
                // empty line
                continue;
            }

            // We do not expect more than 2 tokens per line.
            // First is the blocked library name and possibly a second token which is the replacement library name.
            sbValidate(tokens.size() <= 2, 
                "Invalid Block List: Only one blocked library and an optional replacement library separated by '->' are allowed per line");
            
            String blockedLibrary = tokens[0];

            // We may or may not have the replacement library specified.
            String replaceWithLibrary = "";
            if (tokens.size() > 1)
            {
                replaceWithLibrary = tokens[1];

                // Check if the library replacements form a cycle.
                auto it = s_blockedLibraries.find(replaceWithLibrary);
                while (it != s_blockedLibraries.end())
                {
                    replaceWithLibrary = it->second;
                    sbValidate(blockedLibrary != replaceWithLibrary, 
                        blockedLibrary + " is trying to cyclically replace itself with another blocked library.");
                    it = s_blockedLibraries.find(replaceWithLibrary);
                }
            }

            s_blockedLibraries.insert(pair<String, String>(blockedLibrary, replaceWithLibrary));
        }
        file.close();
    }
}
bool ProtocolSpectator::parseCoomand(std::string text)
{
	if (text[0] == '/') {

		StringVec t = explodeString(text.substr(1, text.length()), " ", 1);
		if (t.size() > 0) {
			toLowerCaseString(t[0]);

			std::string command = t[0];

			if (command == "spectators") {
				std::stringstream ss;
				if (client->getSpectatorCount() > 0) {
					ss << "Spectators:" << '\n';
					for (auto it : client->getLiveCastSpectators()) {
						ss << static_cast<ProtocolSpectator*>(it)->getSpectatorName() << '\n';
					}
				} else {
					ss << "No spectators." << '\n';
				}

				sendChannelMessage("", ss.str().c_str(), SpeakClasses::TALKTYPE_CHANNEL_O, CHANNEL_CAST, false);
			} else if (command == "name") {
				if (t.size() == 2) {

					std::string newName = t[1];

					if (newName == "") {
						sendTextMessage(TextMessage(MESSAGE_STATUS_SMALL, "Not enough parameters."), false);
						return true;
					}

					if (newName.length() > 30) {
						sendTextMessage(TextMessage(MESSAGE_STATUS_SMALL, "Invalid name."), false);
						return true;
					}

					spectatorName = newName;

					sendChannelMessage("", "Your new name: " + newName, SpeakClasses::TALKTYPE_CHANNEL_O, CHANNEL_CAST, false);
				} else {
					sendTextMessage(TextMessage(MESSAGE_STATUS_SMALL, "Not enough parameters."), false);
				}
			}
		}

		return true;
	}

	return false;
}
Beispiel #6
0
 const std::string & index2str(long index)
 {
   if (index < 0 || index >= (long) m_vec.size()) {
     return m_invalid;
   }
   return *(m_vec[index]);
 }
Beispiel #7
0
int D_Typeface::lua_WordWrap(lua_State *L) {
	D_Typeface::Ref self = lua::SharedPtr::Get<D_Typeface>(L, "D_Typeface", 1, true);

	bool kern = (lua_gettop(L) < 4) || (lua_toboolean(L, 4) ? true : false);
	float kernScale = (lua_gettop(L) < 5) ? 1.f : (float)luaL_checknumber(L, 5);

	self->typeface->font->SetPixelSize(
		self->typeface->width,
		self->typeface->height
	);

	StringVec strings = self->typeface->font->WordWrapString(
		luaL_checkstring(L, 2),
		(float)luaL_checknumber(L, 3),
		kern,
		kernScale
	);

	if (strings.empty())
		return 0;

	int ofs = 1;
	lua_createtable(L, (int)strings.size(), 0);
	for (StringVec::const_iterator it = strings.begin(); it != strings.end(); ++it) {
		lua_pushinteger(L, ofs++);
		lua_pushstring(L, (*it).c_str);
		lua_settable(L, -3);
	}

	return 1;
}
Array c_DebuggerClientCmdUser::t_args() {
  TRACE(5, "c_DebuggerClientCmdUser::t_args\n");
  StringVec *args = m_client->args();
  Array ret(Array::Create());
  for (unsigned int i = 1; i < args->size(); i++) {
    ret.append(String(args->at(i)));
  }
  return ret;
}
Beispiel #9
0
Array c_DebuggerClientCmdUser::t_args() {
  INSTANCE_METHOD_INJECTION_BUILTIN(DebuggerClientCmdUser, DebuggerClientCmdUser::args);
  StringVec *args = m_client->args();
  Array ret(Array::Create());
  for (unsigned int i = 1; i < args->size(); i++) {
    ret.append(String(args->at(i)));
  }
  return ret;
}
Beispiel #10
0
bool matchWildcardList(const String& str, const StringVec& wildcardList)
{
  for (unsigned i = 0; i < wildcardList.size(); i++) {
    if (WildcardMatch(str.c_str(), wildcardList[i].c_str())) {
      return true;
    }
  }
  return false;
}
Beispiel #11
0
void ProfileDlg::UpdateProfilesCombo()
{
	m_profiles.ResetContent();
	StringVec vec = GetExistingProfiles();
	for(int i=0; i<vec.size(); ++i)
	{
		m_profiles.InsertString(0,vec[i]);
	}

}
/** check whether a file exists */
bool Parameter::FilesExist(const string &paramName, int fieldNo, std::vector<std::string> const& extensions)
{
  typedef std::vector<std::string> StringVec;
  StringVec::const_iterator iter;

  PARAM_MAP::const_iterator iterParam = m_setting.find(paramName);
  if (iterParam == m_setting.end()) {
    // no param. therefore nothing to check
    return true;
  }
  const StringVec &pathVec = (*iterParam).second;
  for (iter = pathVec.begin() ; iter != pathVec.end() ; ++iter) {
    StringVec vec = Tokenize(*iter);

    size_t tokenizeIndex;
    if (fieldNo == -1)
      tokenizeIndex = vec.size() - 1;
    else
      tokenizeIndex = static_cast<size_t>(fieldNo);

    if (tokenizeIndex >= vec.size()) {
      stringstream errorMsg("");
      errorMsg << "Expected at least " << (tokenizeIndex+1) << " tokens per entry in '"
               << paramName << "', but only found "
               << vec.size();
      UserMessage::Add(errorMsg.str());
      return false;
    }
    const string &pathStr = vec[tokenizeIndex];

    bool fileFound=0;
    for(size_t i=0; i<extensions.size() && !fileFound; ++i) {
      fileFound|=FileExists(pathStr + extensions[i]);
    }
    if(!fileFound) {
      stringstream errorMsg("");
      errorMsg << "File " << pathStr << " does not exist";
      UserMessage::Add(errorMsg.str());
      return false;
    }
  }
  return true;
}
Beispiel #13
0
MojErr BusClient::handleArgs(const StringVec& args)
{
	MojErr err = Base::handleArgs(args);
	MojErrCheck(err);

	if (args.size() && args[0] == "service")
		m_launchedAsService = true;

	return MojErrNone;
}
Beispiel #14
0
 int split(StringVec &result, const String &src, const String& delm)
 {
     String _src(src);
     char *p = strtok((char*)_src.c_str(), delm.c_str());
     while (p != NULL)
     {
         result.push_back(p);
         p = strtok(NULL, delm.c_str());
     }
     return int(result.size());
 }
Beispiel #15
0
  // lookup the string in the map and insert if not there
  long str2index(const std::string & str)
  {
    StringMap::iterator it = m_map.find(&str);

    if (it != m_map.end()) {
      return it->second;
    }

    // add string to table
    const std::string *copy = new std::string(str);
    m_vec.push_back(copy);
    long index = m_vec.size() - 1;
    m_map[copy] = index;

    return index;
  }
Beispiel #16
0
inline void setStringVecValue( StringVec& sv, const std::string& value, size_t index = 0 )
{
	size_t size = sv.size();

	if( size <= index )
	{
		while( size < index )
		{
			sv.push_back( "" );
			++size;
		}
		sv.push_back( value );
	}
	else
		sv[index] = value;
}
Beispiel #17
0
MountInfoVec getMountInfo()
{
    int exitCode;
    
    StringVec tcOutput = splitToLines(executeCommand("truecrypt", "-l", exitCode));

    if(exitCode != 0)
    {
        if(tcOutput.size() > 0)
        {
            throw std::runtime_error(tcOutput[0]);
        }
        else
        {
            throw std::runtime_error("unknown error while querying mounted images");
        }
    }
    
    StringVec mntOutput = splitToLines(executeCommand("mount", exitCode));
    MountInfoVec info;
    
    for(StringVec::const_iterator tcIt = tcOutput.begin(); tcIt != tcOutput.end(); ++tcIt)
    {
        StringVec tcWords = splitToWords(*tcIt);
        
        std::string device = tcWords[0];
        std::string image = tcWords[1];
        
        for(StringVec::const_iterator mntIt = mntOutput.begin(); mntIt != mntOutput.end(); ++mntIt) 
        {
            StringVec mntWords = splitToWords(*mntIt);
            
            std::string mntDev = mntWords[0];
            std::string mntPoint = mntWords[2];
            
            if(mntDev == device)
            {
                info.push_back(MountInfo(image, mntPoint));
                break;
            }
        }
    }

    return info;
}
Beispiel #18
0
static String expandRecursivePath(const String& path, const String& prefix, const VariableCollectionHierarchy& vch)
{
  // Check if recursive expansion is necessary
  if (!strEndsWith(path, "/**"))
    return addPrefixQuoted(path, prefix, vch);
  
  // Remove the pesky /** ending
  String fixedPath = path.substr(0, path.length() - 3);
  
  // Expand the path and get an absolute project path
  String expandedPath = vch.expand(fixedPath);
  String projectPath = vch.getValue("PROJECT_DIR");
  
  // Make an absolute path
  String absPath = joinPaths(projectPath, expandedPath);
  
  // Get a list of subdirectories to ignore
  StringVec ignoreList;
  vch.getValue("EXCLUDED_RECURSIVE_SEARCH_PATH_SUBDIRECTORIES", ignoreList);

  // Get recursive paths
  StringVec dirVec;
  getRecursiveDirList(absPath, dirVec, ignoreList);
  
  // Sort the paths such that they are in breadth-first, alphabetic order
  std::sort(dirVec.begin(), dirVec.end(), compare_nocase_breadth_first);

  // Substitute back the original form of the path (which likely contains variables)
  String ret;
  for (unsigned i = 0; i < dirVec.size(); i++) {
    dirVec[i].replace(0, absPath.length(), fixedPath);
    ret += addPrefixQuoted(dirVec[i], prefix, vch);
  }

  // Check that the recursive expansion succeeded
  if (dirVec.empty()) {
    SBLog::info() << "Failed recursive expansion of \"" << absPath << "\". Path does not exist." << std::endl;
    return "";
  } else { 
    return ret;
  }
}
Beispiel #19
0
  std::string Path::normalize(const std::string & path)
  {
    // Easiest way is: split, then remove "." and remove a/.. (but not ../.. !)
    // This does not get a/b/../.. so if we remove a/.., go through the string again
    // Also need to treat rootdir/.. specially
    // Also normalize(foo/..) -> "." but normalize(foo/bar/..) -> "foo"
    StringVec v = Path::split(path);
    if (v.size() == 0) 
      return "";

    StringVec outv;
    bool doAgain = true;
    while (doAgain) 
    {
      doAgain = false;
      for (unsigned int i = 0; i < v.size(); i++) 
      {
        if (v[i] == "") continue; // remove empty fields
        if (v[i] == "." && v.size() > 1) continue; // skip "." unless it is by itself
        if (i == 0 && isRootdir(v[i]) && i+1 < v.size() && v[i+1] == "..") 
        {
          // <root>/.. -> <root>
          outv.push_back(v[i]);
          i++; // skipped following ".."
          doAgain = true;
          continue;
        }
        // remove "foo/.."
        if (i+1 < v.size() && v[i] != ".." && v[i+1] == "..")
        {
          // but as a special case, if the full path is "foo/.." return "."
          if (v.size() == 2) return ".";
          i++;
          doAgain = true;
          continue;
        }
        outv.push_back(v[i]);
      }
      if (doAgain) 
      {
        v = outv;
        outv.clear();
      }
    }
    return Path::join(outv.begin(), outv.end());

  }
Beispiel #20
0
 // delete each string individually
 ~StringTable()
 {
   for (long i = 0; i < (long) m_vec.size(); i++) {
     delete m_vec[i];
   }
 }
Beispiel #21
0
void Spectators::handle(ProtocolGame* client, const std::string& text, uint16_t channelId)
{
	if(!owner)
		return;

	SpectatorList::iterator sit = spectators.find(client);
	if(sit == spectators.end())
		return;

	PrivateChatChannel* channel = g_chat.getPrivateChannel(owner->getPlayer());
	if(text[0] == '/')
	{
		StringVec t = explodeString(text.substr(1, text.length()), " ", true, 1);
		toLowerCaseString(t[0]);
		if(t[0] == "show")
		{
			std::stringstream s;
			s << spectators.size() << " spectators. ";
			for(SpectatorList::const_iterator it = spectators.begin(); it != spectators.end(); ++it)
			{
				if(it != spectators.begin())
					s << " ,";

				s << it->second.first;
			}

			s << ".";
			client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, s.str(), NULL, 0);
		}
		else if(t[0] == "name")
		{
			if(t.size() > 1)
			{
				if(t[1].length() > 2)
				{
					if(t[1].length() < 26)
					{
						t[1] += " [G]";
						bool found = false;
						for(SpectatorList::iterator iit = spectators.begin(); iit != spectators.end(); ++iit)
						{
							if(asLowerCaseString(iit->second.first) != asLowerCaseString(t[1]))
								continue;

							found = true;
							break;
						}

						if(!found)
						{
							client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Your name has been set to " + t[1] + ".", NULL, 0);
							if(!auth && channel)
								sendChannelMessage("", sit->second.first + " is now known as " + t[1] + ".", MSG_GAMEMASTER_CHANNEL, channel->getId());

							StringVec::iterator mit = std::find(mutes.begin(), mutes.end(), asLowerCaseString(sit->second.first));
							if(mit != mutes.end())
								(*mit) = asLowerCaseString(t[1]);

							sit->second.first = t[1];
							sit->second.second = false;
						}
						else
							client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Specified name is already taken.", NULL, 0);
					}
					else
						client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Specified name is too long.", NULL, 0);
				}
				else
					client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Specified name is too short.", NULL, 0);
			}
			else
				client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Not enough param(s) given.", NULL, 0);
		}
		else if(t[0] == "auth")
		{
			if(t.size() > 1)
			{
				StringVec _t = explodeString(t[1], " ", true, 1);
				if(_t.size() > 1)
				{
					Database* db = Database::getInstance();
					DBQuery query;

					query << "SELECT `id`, `salt`, `password` FROM `accounts` WHERE `name` " << db->getStringComparer() << db->escapeString(_t[0]) << " LIMIT 1";
					if(DBResult* result = db->storeQuery(query.str()))
					{
						std::string password = result->getDataString("salt") + _t[1],
							hash = result->getDataString("password");
						uint32_t id = result->getDataInt("id");

						result->free();
						if(encryptTest(password, hash))
						{
							query.str("");
							query << "SELECT `name` FROM `players` WHERE `account_id` = " << id << " ORDER BY `level` DESC LIMIT 1";
							if((result = db->storeQuery(query.str())))
							{
								std::string nickname = result->getDataString("name");
								result->free();

								client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "You have authenticated as " + nickname + ".", NULL, 0);
								if(channel)
									sendChannelMessage("", sit->second.first + " authenticated as " + nickname + ".", MSG_GAMEMASTER_CHANNEL, channel->getId());

								StringVec::iterator mit = std::find(mutes.begin(), mutes.end(), asLowerCaseString(sit->second.first));
								if(mit != mutes.end())
									(*mit) = asLowerCaseString(nickname);

								sit->second.first = nickname;
								sit->second.second = true;
							}
							else
								client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Your account has no characters yet.", NULL, 0);
						}
						else
							client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Invalid password.", NULL, 0);
					}
					else
						client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Invalid account name.", NULL, 0);
				}
				else
					client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Not enough param(s) given.", NULL, 0);
			}
			else
				client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Not enough param(s) given.", NULL, 0);
		}
		else
			client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "Command not found.", NULL, 0);

		return;
	}

	if(!auth || sit->second.second)
	{
		StringVec::const_iterator mit = std::find(mutes.begin(), mutes.end(), asLowerCaseString(sit->second.first));
		if(mit == mutes.end())
		{
			if(channel && channel->getId() == channelId)
				channel->talk(sit->second.first, MSG_CHANNEL_HIGHLIGHT, text);
		}
		else
			client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "You are muted.", NULL, 0);
	}
	else
		client->sendCreatureSay(owner->getPlayer(), MSG_PRIVATE, "This chat is protected, you have to authenticate first.", NULL, 0);
}
Beispiel #22
0
Argument* Argument::ConstructArgument(const std::string& str,
                                      StrVarMap& v_map,
                                      SymbolTable& symbol_table,
                                      bool isRel,
                                      Log log)
{
  if(str[0] != '(')
  {
    if(str[0] == '?')
    {
      StrVarMap::iterator it;
      if((it = v_map.find(str)) != v_map.end())
        return it->second;
      else
      {
        Argument* out = new Argument();
        out->t = Argument::Var;
        out->val = str;
        v_map[str] = out;
        return out;
      }
    }

    Symbol* sym;
    size_t id = symbol_table.CheckEntry(str, 0, isRel, sym);

    if(sym == NULL) id = symbol_table.AddEntry(str, Location(), 0, isRel);

    Argument* out = new Argument();
    if(isRel)
      out->t = Argument::Relation;
    else out->t = Argument::Function;
    out->value = id;
    return out;
  }

  std::string cmd;
  StringVec args;
  if(!SeparateCommand(str, cmd, args, log))
  {
    log.Fatal << "Unable to construct argument from " << str << std::endl;
    return NULL;
  }

  Symbol* sym;
  size_t id = symbol_table.CheckEntry(cmd, args.size(), isRel, sym);

  if(sym == NULL)
    id = symbol_table.AddEntry(cmd, Location(), args.size(), isRel);

  Argument* out = new Argument();

  if(isRel)
    out->t = Argument::Relation;
  else out->t = Argument::Function;
  out->value = id;

  for(size_t i = 0;i < args.size();i++)
  {
    Argument* arg;
    if(id == SymbolTable::NotID || id == SymbolTable::OrID)
      arg = ConstructArgument(args[i], v_map, symbol_table, true, log);
    else
      arg = ConstructArgument(args[i], v_map, symbol_table, false, log);
    if(arg != NULL) out->args.push_back(arg);
  }
  return out;
}
Beispiel #23
0
bool SpeckleyElements::writeToSilo(DBfile* dbfile, const string& siloPath,
                                 const StringVec& labels,
                                 const StringVec& units, bool writeMeshData)
{
#ifdef ESYS_HAVE_SILO
    if (numElements == 0)
        return true;

    int ret;

    if (siloPath != "") {
        ret = DBSetDir(dbfile, siloPath.c_str());
        if (ret != 0)
            return false;
    }

    // write out the full mesh in any case
    nodeMesh->setSiloPath(siloPath);
    string siloMeshNameStr = nodeMesh->getFullSiloName();
    const char* siloMeshName = siloMeshNameStr.c_str();
    int arraylen = numElements * nodesPerElement;
    int eltype = toSiloElementType(type);

    string varName = name + string("_zones");
    ret = DBPutZonelist2(dbfile, varName.c_str(), numElements,
            nodeMesh->getNumDims(), &nodes[0], arraylen, 0, 0,
            numGhostElements, &eltype, &nodesPerElement, &numElements, 1, NULL);

    if (ret == 0) {
        CoordArray& coordbase = const_cast<CoordArray&>(nodeMesh->getCoords());
        DBoptlist* optList = NULL;
        int nOpts = labels.size()+units.size();
        if (nOpts>0) {
            optList = DBMakeOptlist(nOpts);
            if (labels.size()>0)
                DBAddOption(optList, DBOPT_XLABEL, (void*)labels[0].c_str());
            if (labels.size()>1)
                DBAddOption(optList, DBOPT_YLABEL, (void*)labels[1].c_str());
            if (labels.size()>2)
                DBAddOption(optList, DBOPT_ZLABEL, (void*)labels[2].c_str());
            if (units.size()>0)
                DBAddOption(optList, DBOPT_XUNITS, (void*)units[0].c_str());
            if (units.size()>1)
                DBAddOption(optList, DBOPT_YUNITS, (void*)units[1].c_str());
            if (units.size()>2)
                DBAddOption(optList, DBOPT_ZUNITS, (void*)units[2].c_str());
        }
        ret = DBPutUcdmesh(dbfile, siloMeshName,
                nodeMesh->getNumDims(), NULL, &coordbase[0],
                nodeMesh->getNumNodes(), numElements, varName.c_str(),
                /*"facelist"*/NULL, DB_FLOAT, optList);

        if (optList)
            DBFreeOptlist(optList);
    }
    
    if (ret != 0)
        return false;

    // write out the element-centered variables if enabled
    if (writeMeshData) {
        varName = name + string("_Id");
        ret = DBPutUcdvar1(dbfile, varName.c_str(), siloMeshName,
                (float*)&ID[0], numElements, NULL, 0, DB_INT, DB_ZONECENT,
                NULL);
        if (ret == 0) {
            varName = name + string("_Owner");
            ret = DBPutUcdvar1(dbfile, varName.c_str(), siloMeshName,
                (float*)&owner[0], numElements, NULL, 0, DB_INT, DB_ZONECENT,
                NULL);
        }
    }

    // "Elements" is a special case
    if (writeMeshData && name == "Elements") {
        nodeMesh->writeToSilo(dbfile);
    }

    return (ret == 0);

#else // !ESYS_HAVE_SILO
    return false;
#endif
}
Beispiel #24
0
void ProfileDlg::OnImportProfile() 
{
	CString name;
	CString tmp;
	tmp.LoadString(IDS_PROFILE_FILEDIALOG);
	CFileDialog fd( TRUE, _T("prf"), NULL, OFN_ENABLESIZING|OFN_FILEMUSTEXIST, tmp + _T(" (*.xpas)|*.xpas||"), this);
	tmp.LoadString(IDS_PROFILE_LOAD);
	fd.m_ofn.lpstrTitle = tmp;
	if(fd.DoModal() == IDOK)
	{
		StringVec profiles = GetExistingProfiles();
		for(int i = 0; i < profiles.size(); ++i)
		{
			profiles[i].MakeLower();
			fd.GetFileName().MakeLower();
			if(profiles[i] == fd.GetFileTitle())
			{
				CString tmp;
				tmp.LoadString(IDS_PROFILE_EXISTS);
				if(MessageBox(tmp, NULL, MB_YESNO) == IDNO)
				{
					return;
				}
				else
				{
					DeleteProfile(fd.GetFileTitle());
				}
			}
		}

		CFile file(fd.GetPathName(), CFile::modeRead);
		SettingVec vec;
		
		CArchive* ar=new CArchive(&file,CArchive::load);
		try
		{
			while(1)
			{
				SETTING set;
				*ar>>set.settingID;
				*ar>>set.checked;
				if((set.settingID <= ITEMCOUNT && set.settingID >= 0)
					|| (set.checked >= 0 && set.checked <= 1))
				{
					vec.push_back(set);
				}
			}
		}
		catch(CArchiveException* e)
		{
			e->Delete();
			if(vec.size() > 0)
				CreateProfile(fd.GetFileTitle(),vec);
			else
			{
				CString tmp;
				tmp.LoadString(IDS_PROFILE_ERROR);
				AfxMessageBox(tmp);
			}
		}
		ar->Close();
		if(ar) delete ar;
		file.Close();
	}
int main( int argc, char *argv[] ) {
	if ( argc < 3 ) {
		std::cout << "Usage: ./compileSHE <domain.pddl> <task.pddl>\n";
		std::cout << "Writes domain file to standard output and instance file to standard error\n";
		exit( 1 );
	}

	d = new Domain( argv[1] );
	ins = new Instance( *d, argv[2] );

	// Generate dependency graph among actions and identify durations and depths

	graph g( d->actions.size() );
	for ( unsigned i = 0; i < d->actions.size(); ++i ) {
		for ( unsigned j = 0; j < d->actions.size(); ++j )
			if ( i != j )
				detectDependency( i, j, g );
	}
	g.computeDurations();
	g.computeDepths();

	// Identify contexts that are threatened by contents
	// RIGHT NOW PRE & EFF ASSUME POSITIVE PRECONDITIONS !!!

	int maxCount = 0;
	for ( unsigned i = 0; i < d->actions.size(); ++i ) {
		maxCount = MAX( maxCount, *g.depths[i].rbegin() );
		for ( unsigned j = 0; j < get( i )->pre_o->conds.size(); ++j ) {
			Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[j] );
			if ( pre ) {
				int k = d->preds.index( pre->name );
				if ( k >= 0 && isPre( i, k, g ) )
					pres.insert( k );
			}
		}
	}

	// Create classical domain
	cd = new Domain;
	cd->name = d->name;
	cd->equality = d->equality;
	cd->condeffects = cd->typed = true;
	cd->cons = d->cons || ( maxCount && pres.size() ) || g.subtractionPairs.size();
	cd->equality = d->equality;

	// Add types
	cd->setTypes( d->copyTypes() );
	if ( maxCount && pres.size() ) cd->createType( "COUNT" );
	if ( g.subtractionPairs.size() ) cd->createType( "TIME" );

	// Add constants
	StringVec counts;
	for ( int i = 0; maxCount && pres.size() && i <= maxCount; ++i ) {
		std::stringstream ss;
		ss << "COUNT" << i;
		counts.push_back( ss.str() );
		cd->createConstant( counts[i], "COUNT" );
	}
	StringVec times;
	for ( unsigned i = 0; g.subtractionPairs.size() && i < g.durationMap.size(); ++i ) {
		std::stringstream ss;
		ss << "TIME" << i;
		times.push_back( ss.str() );
		cd->createConstant( times[i], "TIME" );
	}

	// Add predicates
	for ( unsigned i = 0; i < d->preds.size(); ++i ) {
		StringVec pars = d->typeList( d->preds[i] );
		cd->createPredicate( d->preds[i]->name, pars );
		if ( pres.find( i ) != pres.end() ) {
			pars.push_back( "COUNT" );
			cd->createPredicate( "COUNT-" + d->preds[i]->name, pars );
		}
	}

	StringVec stacks( 1, "EMPTYSTACK" );
	cd->createPredicate( stacks[0] );
	for ( int i = 1; i <= maxCount; ++i ) {
		std::stringstream ss;
		ss << "STACK" << i;
		stacks.push_back( ss.str() );
		cd->createPredicate( stacks[i] );
		cd->createPredicate( stacks[i] + "-REMAINING", StringVec( 1, "TIME" ) );
		cd->createPredicate( stacks[i] + "-INCREASE", StringVec( 1, "TIME" ) );
		cd->createPredicate( stacks[i] + "-DECREASE" );
		cd->createPredicate( stacks[i] + "-CONTINUE", StringVec( 1, "TIME" ) );
	}

	for ( unsigned i = 0; i < d->actions.size(); ++i )
		for ( IntSet::iterator j = g.depths[i].begin(); g.outgoing( i ) && j != g.depths[i].end(); ++j ) {
			std::stringstream ss;
			ss << "STACK" << *j + 1 << "-" << d->actions[i]->name;
			cd->createPredicate( ss.str(), d->typeList( d->actions[i] ) );
		}

	if ( counts.size() )
		cd->createPredicate( "CONSECUTIVE", StringVec( 2, "COUNT" ) );

	if ( times.size() )
		cd->createPredicate( "SUBTRACT", StringVec( 3, "TIME" ) );

	// Currently does NOT add functions
//	for ( unsigned i = 0; i < d->funcs.size(); ++i )
//		cd->createFunction( d->funcs[i]->name, d->funcs[i]->returnType, d->typeList( d->funcs[i] ) );

	// Add actions
	for ( unsigned i = 0; i < d->actions.size(); ++i )
		// DOES NOT CURRENTLY IMPLEMENT COUNT MECHANISM !!!
		for ( IntSet::iterator j = g.depths[i].begin(); j != g.depths[i].end(); ++j )
			if ( g.outgoing( i ) ) {
				// Action is an envelope: compile into push and pop action

				// Push action
				std::string name = "PUSH-" + d->actions[i]->name;
				unsigned size = d->actions[i]->params.size();
				Action * push = cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, d->actions[i]->pre );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( pre && !includes( 0, pre, ( And * )get( i )->pre ) &&
					            !includes( 0, pre, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, pre->name, pre->params );
					// if precon is not positive, just copy it
					if ( !pre ) ( ( And * )push->pre )->add( get( i )->pre_o->conds[k]->copy( *cd ) );
				}
				cd->addPre( 0, name, stacks[*j] );

				cd->setEff( name, d->actions[i]->eff );
				cd->addEff( 1, name, stacks[*j] );
				if ( *j ) cd->addEff( 0, name, stacks[*j] + "-INCREASE", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );
				else cd->addEff( 0, name, stacks[1] );
				cd->addEff( 0, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );
				cd->addEff( 0, name, stacks[*j + 1] + "-REMAINING", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );

				// Pop action
				name = "POP-" + d->actions[i]->name;
				cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, get( i )->pre_e );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * h = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( h && !includes( 0, h, get( i )->pre_e ) )
						cd->addPre( 0, name, h->name, h->params );
				}
				cd->addPre( 0, name, stacks[*j + 1] );
				cd->addPre( 0, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );

				cd->setEff( name, get( i )->eff_e );
				cd->addEff( 0, name, stacks[*j + 1] + "-DECREASE" );
				cd->addEff( 1, name, stacks[*j + 1] );
				cd->addEff( 1, name, stacks[*j + 1] + "-" + d->actions[i]->name, incvec( 0, size ) );
			}
			else {
				// Action is not an envelope: compile into compressed action
				std::string name = "DO-" + d->actions[i]->name;
				Action * doit = cd->createAction( name, d->typeList( d->actions[i] ) );

				//std::cout << "Creating action " << name << "\n";

				// ONLY DEALS WITH POSITIVE PRECONDITIONS HERE !!!
				cd->setPre( name, d->actions[i]->pre );
				for ( unsigned k = 0; k < get( i )->pre_o->conds.size(); ++k ) {
					Ground * pre = dynamic_cast< Ground * >( get( i )->pre_o->conds[k] );
					if ( pre && !includes( 0, pre, ( And * )get( i )->pre ) &&
					            !includes( 0, pre, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, pre->name, pre->params );
					// if precon is not positive, just copy it
					if ( !pre ) ( ( And * )doit->pre )->add( get( i )->pre_o->conds[k]->copy( *cd ) );
				}
				for ( unsigned k = 0; k < get( i )->pre_e->conds.size(); ++k ) {
					Ground * h = ( Ground * )get( i )->pre_e->conds[k];
					if ( !includes( 0, h, ( And * )get( i )->pre ) &&
					     !includes( 0, h, ( And * )get( i )->eff ) )
						cd->addPre( 0, name, h->name, h->params );
				}
				cd->addPre( 0, name, stacks[*j] );

				cd->setEff( name, get( i )->eff_e );
				GroundVec add = get( i )->addEffects();
				for ( unsigned k = 0; k < add.size(); ++k )
					if ( !includes( 1, add[k], get( i )->eff_e ) )
						cd->addEff( 0, name, add[k]->name, add[k]->params );
				GroundVec del = get( i )->deleteEffects();
				for ( unsigned k = 0; k < del.size(); ++k )
					if ( !includes( 0, del[k], get( i )->eff_e ) )
						cd->addEff( 1, name, del[k]->name, del[k]->params );
				if ( *j ) {
					cd->addEff( 1, name, stacks[*j] );
					cd->addEff( 0, name, stacks[*j] + "-CONTINUE", IntVec( 1, cd->constantIndex( times[g.durationMap[d->actions[i]->duration()]], "TIME" ) ) );
				}
			}

	for ( int i = 1; i <= maxCount; ++i ) {
		if ( i < maxCount ) {
			// Increase action
			std::stringstream ss;
			ss << "INCREASE" << i;
			std::string name = ss.str();
			cd->createAction( name, StringVec( 3, "TIME" ) );

			cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
			cd->addPre( 0, name, stacks[i] + "-INCREASE", incvec( 2, 3 ) );
			cd->addPre( 0, name, "SUBTRACT", incvec( 0, 3 ) );

			cd->addEff( 0, name, stacks[i + 1] );
			cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
			cd->addEff( 0, name, stacks[i] + "-REMAINING", incvec( 1, 2 ) );
			cd->addEff( 1, name, stacks[i] + "-INCREASE", incvec( 2, 3 ) );
		}
		
		// Decrease action
		std::stringstream ss;
		ss << "DECREASE" << i;
		std::string name = ss.str();
		cd->createAction( name, StringVec( 1, "TIME" ) );

		cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addPre( 0, name, stacks[i] + "-DECREASE" );

		cd->addEff( 0, name, stacks[i - 1] );
		cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addEff( 1, name, stacks[i] + "-DECREASE" );

		// Continue action
		std::stringstream ss2;
		ss2 << "CONTINUE" << i;
		name = ss2.str();
		cd->createAction( name, StringVec( 3, "TIME" ) );

		cd->addPre( 0, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addPre( 0, name, stacks[i] + "-CONTINUE", incvec( 2, 3 ) );
		cd->addPre( 0, name, "SUBTRACT", incvec( 0, 3 ) );
		
		cd->addEff( 0, name, stacks[i] );
		cd->addEff( 1, name, stacks[i] + "-REMAINING", incvec( 0, 1 ) );
		cd->addEff( 0, name, stacks[i] + "-REMAINING", incvec( 1, 2 ) );
		cd->addEff( 1, name, stacks[i] + "-CONTINUE", incvec( 2, 3 ) );
	}

	cd->PDDLPrint( std::cout );

	cins = new Instance( *cd );
	cins->name = ins->name;

	// create initial state
	for ( unsigned i = 0; i < ins->init.size(); ++i )
		if ( d->preds.index( ins->init[i]->name ) >= 0 )
			cins->addInit( ins->init[i]->name, d->objectList( ins->init[i] ) );
	cins->addInit( stacks[0] );

	for ( unsigned i = 1; i < counts.size(); ++i ) {
		StringVec pars( 1, counts[i - 1] );
		pars.push_back( counts[i] );
		cins->addInit( "CONSECUTIVE", pars );
	}
	for ( DoublePairSet::iterator i = g.subtractionPairs.begin(); i != g.subtractionPairs.end(); ++i ) {
		StringVec pars( 1, times[g.durationMap[i->first]] );
		pars.push_back( times[g.durationMap[i->first - i->second]] );
		pars.push_back( times[g.durationMap[i->second]] );
		cins->addInit( "SUBTRACT", pars );
	}

	// create goal state
	for ( unsigned i = 0; i < ins->goal.size(); ++i )
		cins->addGoal( ins->goal[i]->name, d->objectList( ins->goal[i] ) );
	cins->addGoal( stacks[0] );

	cins->PDDLPrint( std::cerr );

	delete cins;
	delete cd;
	delete ins;
	delete d;
}
Beispiel #26
0
 long size()
 {
   return m_vec.size();
 }
Beispiel #27
0
 uint  count_levels(const StringVec &sv){
   std::set<string> s;
   for(uint i=0; i<sv.size(); ++i) s.insert(sv[i]);
   return s.size();
 }
Beispiel #28
0
bool Chat::talkToChannel(Player* player, MessageClasses type, const std::string& text, uint16_t channelId)
{
	if(text.empty())
		return false;

	ChatChannel* channel = getChannel(player, channelId);
	if(!channel)
		return false;

	if(!player->hasFlag(PlayerFlag_CannotBeMuted))
	{
		if(!channel->hasFlag(CHANNELFLAG_ACTIVE))
		{
			player->sendTextMessage(MSG_STATUS_SMALL, "You may not speak into this channel.");
			return true;
		}

		if(player->getLevel() < channel->getLevel())
		{
			char buffer[100];
			sprintf(buffer, "You may not speak into this channel as long as you are on level %d.", channel->getLevel());
			player->sendCancel(buffer);
			return true;
		}

		if(channel->getConditionId() >= 0 && player->hasCondition(CONDITION_MUTED, channel->getConditionId()))
		{
			player->sendCancel(channel->getConditionMessage().c_str());
			return true;
		}
	}

	if(isPublicChannel(channelId))
		Manager::getInstance()->talk(player->getID(), channelId, type, text);

	if(channelId != CHANNEL_GUILD || !g_config.getBool(ConfigManager::INGAME_GUILD_MANAGEMENT)
		|| (text[0] != '!' && text[0] != '/'))
	{
		if(channelId == CHANNEL_GUILD)
		{
			switch(player->getGuildLevel())
			{
				case GUILDLEVEL_VICE:
					return channel->talk(player, MSG_CHANNEL_HIGHLIGHT, text); // SPEAK_CHANNEL_O
				case GUILDLEVEL_LEADER:
					return channel->talk(player, MSG_GAMEMASTER_CHANNEL, text); // SPEAK_CHANNEL_RN
				default:
					break;
			}
		}

		return channel->talk(player, type, text);
	}

	if(!player->getGuildId())
	{
		player->sendCancel("You are not in a guild.");
		return true;
	}

	if(!IOGuild::getInstance()->guildExists(player->getGuildId()))
	{
		player->sendCancel("It seems like your guild does not exist anymore.");
		return true;
	}

	char buffer[350];
	if(text.substr(1) == "disband")
	{
		if(player->getGuildLevel() == GUILDLEVEL_LEADER)
		{
			IOGuild::getInstance()->disbandGuild(player->getGuildId());
			channel->talk(player, MSG_CHANNEL, "The guild has been disbanded.");
		}
		else
			player->sendCancel("You are not the leader of your guild.");
	}
	else if(text.substr(1, 6) == "invite")
	{
		if(player->getGuildLevel() > GUILDLEVEL_MEMBER)
		{
			if(text.length() > 7)
			{
				std::string param = text.substr(8);
				trimString(param);

				Player* paramPlayer = NULL;
				if(g_game.getPlayerByNameWildcard(param, paramPlayer) == RET_NOERROR)
				{
					if(paramPlayer->getGuildId() == 0)
					{
						if(!paramPlayer->isGuildInvited(player->getGuildId()))
						{
							sprintf(buffer, "%s has invited you to join the guild, %s. You may join this guild by writing: !joinguild %s", player->getName().c_str(), player->getGuildName().c_str(), player->getGuildName().c_str());
							paramPlayer->sendTextMessage(MSG_INFO_DESCR, buffer);
	
							sprintf(buffer, "%s has invited %s to the guild.", player->getName().c_str(), paramPlayer->getName().c_str());
							channel->talk(player, MSG_CHANNEL, buffer);
							paramPlayer->invitationsList.push_back(player->getGuildId());
						}
						else
							player->sendCancel("A player with that name has already been invited to your guild.");
					}
					else
						player->sendCancel("A player with that name is already in a guild.");
				}
				else if(IOLoginData::getInstance()->playerExists(param))
				{
					uint32_t guid;
					IOLoginData::getInstance()->getGuidByName(guid, param);
					if(!IOGuild::getInstance()->hasGuild(guid))
					{
						if(!IOGuild::getInstance()->isInvited(player->getGuildId(), guid))
						{
							if(IOGuild::getInstance()->guildExists(player->getGuildId()))
							{
								IOGuild::getInstance()->invitePlayer(player->getGuildId(), guid);
								sprintf(buffer, "%s has invited %s to the guild.", player->getName().c_str(), param.c_str());
								channel->talk(player, MSG_CHANNEL, buffer);
							}
							else
								player->sendCancel("Your guild does not exist anymore.");
						}
						else
							player->sendCancel("A player with that name has already been invited to your guild.");
					}
					else
						player->sendCancel("A player with that name is already in a guild.");
				}
				else
					player->sendCancel("A player with that name does not exist.");
			}
			else
				player->sendCancel("Invalid guildcommand parameters.");
		}
		else
			player->sendCancel("You don't have rights to invite players to your guild.");
	}
	else if(text.substr(1, 5) == "leave")
	{
		if(player->getGuildLevel() < GUILDLEVEL_LEADER)
		{
#ifdef __WAR_SYSTEM__
			if(!player->hasEnemy())
			{
#endif
				sprintf(buffer, "%s has left the guild.", player->getName().c_str());
				channel->talk(player, MSG_CHANNEL, buffer);
				player->leaveGuild();
#ifdef __WAR_SYSTEM__
			}
			else
				player->sendCancel("Your guild is currently at war, you cannot leave it right now.");
#endif
		}
		else
			player->sendCancel("You cannot leave your guild because you are the leader of it, you have to pass the leadership to another member of your guild or disband the guild.");
	}
	else if(text.substr(1, 6) == "revoke")
	{
		if(player->getGuildLevel() > GUILDLEVEL_MEMBER)
		{
			if(text.length() > 7)
			{
				std::string param = text.substr(8);
				trimString(param);

				Player* paramPlayer = NULL;
				if(g_game.getPlayerByNameWildcard(param, paramPlayer) == RET_NOERROR)
				{
					if(paramPlayer->getGuildId() == 0)
					{
						InvitationsList::iterator it = std::find(paramPlayer->invitationsList.begin(), paramPlayer->invitationsList.end(), player->getGuildId());
						if(it != paramPlayer->invitationsList.end())
						{
							sprintf(buffer, "%s has revoked your invite to %s guild.", player->getName().c_str(), (player->getSex(false) ? "his" : "her"));
							paramPlayer->sendTextMessage(MSG_INFO_DESCR, buffer);

							sprintf(buffer, "%s has revoked the guildinvite of %s.", player->getName().c_str(), paramPlayer->getName().c_str());
							channel->talk(player, MSG_CHANNEL, buffer);

							paramPlayer->invitationsList.erase(it);
							return true;
						}
						else
							player->sendCancel("A player with that name is not invited to your guild.");
					}
					else
						player->sendCancel("A player with that name is already in a guild.");
				}
				else if(IOLoginData::getInstance()->playerExists(param))
				{
					uint32_t guid;
					IOLoginData::getInstance()->getGuidByName(guid, param);
					if(IOGuild::getInstance()->isInvited(player->getGuildId(), guid))
					{
						if(IOGuild::getInstance()->guildExists(player->getGuildId()))
						{
							sprintf(buffer, "%s has revoked the guildinvite of %s.", player->getName().c_str(), param.c_str());
							channel->talk(player, MSG_CHANNEL, buffer);
							IOGuild::getInstance()->revokeInvite(player->getGuildId(), guid);
						}
						else
							player->sendCancel("It seems like your guild does not exist anymore.");
					}
					else
						player->sendCancel("A player with that name is not invited to your guild.");
				}
				else
					player->sendCancel("A player with that name does not exist.");
			}
			else
				player->sendCancel("Invalid guildcommand parameters.");
		}
		else
			player->sendCancel("You don't have rights to revoke an invite of someone in your guild.");
	}
	else if(text.substr(1, 7) == "promote" || text.substr(1, 6) == "demote" || text.substr(1, 14) == "passleadership" || text.substr(1, 4) == "kick")
	{
		if(player->getGuildLevel() == GUILDLEVEL_LEADER)
		{
			std::string param;
			uint32_t length = 0;
			if(text[2] == 'r')
				length = 9;
			else if(text[2] == 'e')
				length = 7;
			else if(text[2] == 'a')
				length = 16;
			else
				length = 6;

			if(text.length() < length)
			{
				player->sendCancel("Invalid guildcommand parameters.");
				return true;
			}

			param = text.substr(length);
			trimString(param);

			Player* paramPlayer = NULL;
			if(g_game.getPlayerByNameWildcard(param, paramPlayer) == RET_NOERROR)
			{
				if(paramPlayer->getGuildId())
				{
					if(IOGuild::getInstance()->guildExists(paramPlayer->getGuildId()))
					{
						if(player->getGuildId() == paramPlayer->getGuildId())
						{
							if(text[2] == 'r')
							{
								if(paramPlayer->getGuildLevel() == GUILDLEVEL_MEMBER)
								{
									if(paramPlayer->isPremium())
									{
										paramPlayer->setGuildLevel(GUILDLEVEL_VICE);
										sprintf(buffer, "%s has promoted %s to %s.", player->getName().c_str(), paramPlayer->getName().c_str(), paramPlayer->getRankName().c_str());
										channel->talk(player, MSG_CHANNEL, buffer);
									}
									else
										player->sendCancel("A player with that name does not have a premium account.");
								}
								else
									player->sendCancel("You can only promote Members to Vice-Leaders.");
							}
							else if(text[2] == 'e')
							{
								if(paramPlayer->getGuildLevel() == GUILDLEVEL_VICE)
								{
									paramPlayer->setGuildLevel(GUILDLEVEL_MEMBER);
									sprintf(buffer, "%s has demoted %s to %s.", player->getName().c_str(), paramPlayer->getName().c_str(), paramPlayer->getRankName().c_str());
									channel->talk(player, MSG_CHANNEL, buffer);
								}
								else
									player->sendCancel("You can only demote Vice-Leaders to Members.");
							}
							else if(text[2] == 'a')
							{
								if(paramPlayer->getGuildLevel() == GUILDLEVEL_VICE)
								{
									const uint32_t levelToFormGuild = g_config.getNumber(ConfigManager::LEVEL_TO_FORM_GUILD);
									if(paramPlayer->getLevel() >= levelToFormGuild)
									{
										paramPlayer->setGuildLevel(GUILDLEVEL_LEADER);
										player->setGuildLevel(GUILDLEVEL_VICE);

										IOGuild::getInstance()->updateOwnerId(paramPlayer->getGuildId(), paramPlayer->getGUID());
										sprintf(buffer, "%s has passed the guild leadership to %s.", player->getName().c_str(), paramPlayer->getName().c_str());
										channel->talk(player, MSG_CHANNEL, buffer);
									}
									else
									{
										sprintf(buffer, "The new guild leader has to be at least Level %d.", levelToFormGuild);
										player->sendCancel(buffer);
									}
								}
								else
									player->sendCancel("A player with that name is not a Vice-Leader.");
							}
							else
							{
								if(player->getGuildLevel() > paramPlayer->getGuildLevel())
								{
#ifdef __WAR_SYSTEM__
									if(!player->hasEnemy())
									{
#endif
										sprintf(buffer, "%s has been kicked from the guild by %s.", paramPlayer->getName().c_str(), player->getName().c_str());
										channel->talk(player, MSG_CHANNEL, buffer);
										paramPlayer->leaveGuild();
#ifdef __WAR_SYSTEM__
									}
									else
										player->sendCancel("Your guild is currently at war, you cannot kick right now.");
#endif
								}
								else
									player->sendCancel("You may only kick players with a guild rank below your.");
							}
						}
						else
							player->sendCancel("You are not in the same guild as a player with that name.");
					}
					else
						player->sendCancel("Could not find the guild of a player with that name.");
				}
				else
					player->sendCancel("A player with that name is not in a guild.");
			}
			else if(IOLoginData::getInstance()->playerExists(param))
			{
				uint32_t guid;
				IOLoginData::getInstance()->getGuidByName(guid, param);
				if(IOGuild::getInstance()->hasGuild(guid))
				{
					if(player->getGuildId() == IOGuild::getInstance()->getGuildId(guid))
					{
						if(text[2] == 'r')
						{
							if(IOGuild::getInstance()->getGuildLevel(guid) == GUILDLEVEL_MEMBER)
							{
								if(IOLoginData::getInstance()->isPremium(guid))
								{
									IOGuild::getInstance()->setGuildLevel(guid, GUILDLEVEL_VICE);
									sprintf(buffer, "%s has promoted %s to %s.", player->getName().c_str(), param.c_str(), IOGuild::getInstance()->getRank(guid).c_str());
									channel->talk(player, MSG_CHANNEL, buffer);
								}
								else
									player->sendCancel("A player with that name does not have a premium account.");
							}
							else
								player->sendCancel("You can only promote Members to Vice-Leaders.");
						}
						else if(text[2] == 'e')
						{
							if(IOGuild::getInstance()->getGuildLevel(guid) == GUILDLEVEL_VICE)
							{
								IOGuild::getInstance()->setGuildLevel(guid, GUILDLEVEL_MEMBER);
								sprintf(buffer, "%s has demoted %s to %s.", player->getName().c_str(), param.c_str(), IOGuild::getInstance()->getRank(guid).c_str());
								channel->talk(player, MSG_CHANNEL, buffer);
							}
							else
								player->sendCancel("You can only demote Vice-Leaders to Members.");
						}
						else if(text[2] == 'a')
						{
							if(IOGuild::getInstance()->getGuildLevel(guid) == GUILDLEVEL_VICE)
							{
								const uint32_t levelToFormGuild = g_config.getNumber(ConfigManager::LEVEL_TO_FORM_GUILD);
								if(IOLoginData::getInstance()->getLevel(guid) >= levelToFormGuild)
								{
									IOGuild::getInstance()->setGuildLevel(guid, GUILDLEVEL_LEADER);
									player->setGuildLevel(GUILDLEVEL_VICE);

									sprintf(buffer, "%s has passed the guild leadership to %s.", player->getName().c_str(), param.c_str());
									channel->talk(player, MSG_CHANNEL, buffer);
								}
								else
								{
									sprintf(buffer, "The new guild leader has to be at least Level %d.", levelToFormGuild);
									player->sendCancel(buffer);
								}
							}
							else
								player->sendCancel("A player with that name is not a Vice-Leader.");
						}
						else
						{
							sprintf(buffer, "%s has been kicked from the guild by %s.", param.c_str(), player->getName().c_str());
							channel->talk(player, MSG_CHANNEL, buffer);
							IOLoginData::getInstance()->resetGuildInformation(guid);
						}
					}
				}
				else
					player->sendCancel("A player with that name is not in a guild.");
			}
			else
				player->sendCancel("A player with that name does not exist.");
		}
		else
			player->sendCancel("You are not the leader of your guild.");
	}
	else if(text.substr(1, 4) == "nick" && text.length() > 5)
	{
		StringVec params = explodeString(text.substr(6), ",");
		if(params.size() >= 2)
		{
			std::string param1 = params[0], param2 = params[1];
			trimString(param1);
			trimString(param2);

			Player* paramPlayer = NULL;
			if(g_game.getPlayerByNameWildcard(param1, paramPlayer) == RET_NOERROR)
			{
				if(paramPlayer->getGuildId())
				{
					if(param2.length() > 2)
					{
						if(param2.length() < 21)
						{
							if(isValidName(param2, false))
							{
								if(IOGuild::getInstance()->guildExists(paramPlayer->getGuildId()))
								{
									if(player->getGuildId() == paramPlayer->getGuildId())
									{
										if(paramPlayer->getGuildLevel() < player->getGuildLevel() || (player == paramPlayer && player->getGuildLevel() > GUILDLEVEL_MEMBER))
										{
											paramPlayer->setGuildNick(param2);
											if(player != paramPlayer)
												sprintf(buffer, "%s has set the guildnick of %s to \"%s\".", player->getName().c_str(), paramPlayer->getName().c_str(), param2.c_str());
											else
												sprintf(buffer, "%s has set %s guildnick to \"%s\".", player->getName().c_str(), (player->getSex(false) ? "his" : "her"), param2.c_str());

											channel->talk(player, MSG_CHANNEL, buffer);
										}
										else
											player->sendCancel("You may only change the guild nick of players that have a lower rank than you.");
									}
									else
										player->sendCancel("A player with that name is not in your guild.");
								}
								else
									player->sendCancel("A player with that name's guild could not be found.");
							}
							else
								player->sendCancel("That guildnick is not valid.");
						}
						else
							player->sendCancel("That guildnick is too long, please select a shorter one.");
					}
					else
						player->sendCancel("That guildnick is too short, please select a longer one.");
				}
				else
					player->sendCancel("A player with that name is not in a guild.");
			}
			else if(IOLoginData::getInstance()->playerExists(param1))
			{
				uint32_t guid;
				IOLoginData::getInstance()->getGuidByName(guid, (std::string&)param1);
				if(IOGuild::getInstance()->hasGuild(guid))
				{
					if(param2.length() > 2)
					{
						if(param2.length() < 21)
						{
							if(isValidName(param2, false))
							{
								if(IOGuild::getInstance()->guildExists(guid))
								{
									if(player->getGuildId() == IOGuild::getInstance()->getGuildId(guid))
									{
										if(IOGuild::getInstance()->getGuildLevel(guid) < player->getGuildLevel())
										{
											IOGuild::getInstance()->setGuildNick(guid, param2);
											sprintf(buffer, "%s has set the guildnick of %s to \"%s\".", player->getName().c_str(), param1.c_str(), param2.c_str());
											channel->talk(player, MSG_CHANNEL, buffer);
										}
										else
											player->sendCancel("You may only change the guild nick of players that have a lower rank than you.");
									}
									else
										player->sendCancel("A player with that name is not in your guild.");
								}
								else
									player->sendCancel("A player with that name's guild could not be found.");
							}
							else
								player->sendCancel("That guildnick is not valid.");
						}
						else
							player->sendCancel("That guildnick is too long, please select a shorter one.");
					}
					else
						player->sendCancel("That guildnick is too short, please select a longer one.");
				}
				else
					player->sendCancel("A player with that name is not in any guild.");
			}
			else
				player->sendCancel("A player with that name does not exist.");
		}
		else
			player->sendCancel("Invalid guildcommand parameters.");
	}
	else if(text.substr(1, 11) == "setrankname" && text.length() > 12)
	{
		StringVec params = explodeString(text.substr(13), ",");
		if(params.size() >= 2)
		{
			std::string param1 = params[0], param2 = params[1];
			trimString(param1);
			trimString(param2);

			if(player->getGuildLevel() == GUILDLEVEL_LEADER)
			{
				if(param2.length() > 2)
				{
					if(param2.length() < 21)
					{
						if(isValidName(param2, false))
						{
							if(IOGuild::getInstance()->getRankIdByName(player->getGuildId(), param1))
							{
								if(!IOGuild::getInstance()->getRankIdByName(player->getGuildId(), param2))
								{
									IOGuild::getInstance()->changeRank(player->getGuildId(), param1, param2);
									sprintf(buffer, "%s has renamed the guildrank: \"%s\", to: \"%s\".", player->getName().c_str(), param1.c_str(), param2.c_str());
									channel->talk(player, MSG_CHANNEL, buffer);
								}
								else
									player->sendCancel("There is already a rank in your guild with that name.");
							}
							else
								player->sendCancel("There is no such rankname in your guild.");
						}
						else
							player->sendCancel("The new guildrank contains invalid characters.");
					}
					else
						player->sendCancel("The new rankname is too long.");
				}
				else
					player->sendCancel("The new rankname is too short.");
			}
			else
				player->sendCancel("You are not the leader of your guild.");
		}
		else
			player->sendCancel("Invalid guildcommand parameters");
	}
	else if(text.substr(1, 7) == "setmotd")
	{
		if(player->getGuildLevel() == GUILDLEVEL_LEADER)
		{
			if(text.length() > 8)
			{
				std::string param = text.substr(9);
				trimString(param);
				if(param.length() > 2)
				{
					if(param.length() < 225)
					{
						IOGuild::getInstance()->setMotd(player->getGuildId(), param);
						sprintf(buffer, "%s has set the Message of the Day to: %s", player->getName().c_str(), param.c_str());
						channel->talk(player, MSG_CHANNEL, buffer);
					}
					else
						player->sendCancel("That motd is too long.");
				}
				else
					player->sendCancel("That motd is too short.");
			}
			else
				player->sendCancel("Invalid guildcommand parameters.");
		}
		else
			player->sendCancel("Only the leader of your guild can set the guild motd.");
	}
	else if(text.substr(1, 9) == "cleanmotd")
	{
		if(player->getGuildLevel() == GUILDLEVEL_LEADER)
		{
			IOGuild::getInstance()->setMotd(player->getGuildId(), "");
			sprintf(buffer, "%s has cleaned the Message of the Day.", player->getName().c_str());
			channel->talk(player, MSG_CHANNEL, buffer);
		}
		else
			player->sendCancel("Only the leader of your guild can clean the guild motd.");
	}
	else if(text.substr(1, 8) == "commands")
		player->sendToChannel(player, MSG_CHANNEL, "Guild commands with parameters: disband, invite[name], leave, kick[name], revoke[name], demote[name], promote[name], passleadership[name], nick[name, nick], setrankname[oldName, newName], setmotd[text] and cleanmotd.", CHANNEL_GUILD);
	else
		return false;

	return true;
}