Пример #1
0
void EnteredWorldState::runCommand(const std::string &command, const std::string &args)
{
	if (Say == command) {
		mAdapter.say(args);
	} else if (SayTo == command) {
		Tokeniser tokeniser(args);
		std::string entityIdsString = tokeniser.nextToken();
		std::vector<std::string> entityIds = Tokeniser::split(entityIdsString, ",");
		std::string message = tokeniser.remainingTokens();

		mAdapter.sayTo(message, entityIds);
	} else if (Emote == command) {
		mAdapter.emote(args);
	} else if (Delete == command) {
		Tokeniser tokeniser(args);
		std::string entityId = tokeniser.nextToken();
		if (!entityId.empty()) {
			Eris::Entity* entity = getView().getEntity(entityId);
			if (entity) {
				mAdapter.deleteEntity(entity);
			}
		}

		/*		// Touch Command
		 } else if (command==TOUCH) {
		 // TODO: make this switch call the touch method
		 // TODO: polish this rough check
		 S_LOG_VERBOSE("Touching");
		 if(!mAvatar) {
		 S_LOG_WARNING("No avatar.");
		 return;
		 }

		 Atlas::Objects::Operation::Touch touch;
		 Atlas::Message::MapType opargs;

		 opargs["id"] = args;
		 touch->setFrom(mAvatar->getId());
		 touch->setArgsAsList(Atlas::Message::ListType(1, opargs));

		 mConn->send(touch);*/
	} else if (AdminTell == command) {
		Tokeniser tokeniser(args);
		std::string entityId = tokeniser.nextToken();
		if (!entityId.empty()) {
			std::string key = tokeniser.nextToken();
			if (!key.empty()) {
				std::string value = tokeniser.nextToken();
				if (!value.empty()) {
					mAdapter.adminTell(entityId, key, value);
				}
			}
		}
	}
}
Пример #2
0
malValuePtr readStr(const String& input)
{
    Tokeniser tokeniser(input);
    if (tokeniser.eof()) {
        throw malEmptyInputException();
    }
    return readForm(tokeniser);
}
Пример #3
0
/* Parses through the shader file and processes the tokens delivered by
 * DefTokeniser.
 */
void ShaderFileLoader::parseShaderFile(std::istream& inStr,
									   const std::string& filename)
{
	// Parse the file with a blocktokeniser, the actual block contents
	// will be parsed separately.
	parser::BasicDefBlockTokeniser<std::istream> tokeniser(inStr);

	while (tokeniser.hasMoreBlocks())
	{
		// Get the next block
		parser::BlockTokeniser::Block block = tokeniser.nextBlock();

		// Skip tables
		if (block.name.substr(0, 5) == "table")
		{
			std::string tableName = block.name.substr(6);

			if (tableName.empty())
			{
				rError() << "[shaders] " << filename << ": Missing table name." << std::endl;
				continue;
			}

			TableDefinitionPtr table(new TableDefinition(tableName, block.contents));

			if (!GetShaderSystem()->addTableDefinition(table))
			{
				rError() << "[shaders] " << filename
					<< ": table " << tableName << " already defined." << std::endl;
			}

			continue;
		}
		else if (block.name.substr(0, 5) == "skin ")
		{
			continue; // skip skin definition
		}
		else if (block.name.substr(0, 9) == "particle ")
		{
			continue; // skip particle definition
		}

		boost::algorithm::replace_all(block.name, "\\", "/"); // use forward slashes

		ShaderTemplatePtr shaderTemplate(new ShaderTemplate(block.name, block.contents));

		// Construct the ShaderDefinition wrapper class
		ShaderDefinition def(shaderTemplate, filename);

		// Insert into the definitions map, if not already present
		if (!GetShaderLibrary().addDefinition(block.name, def))
		{
    		rError() << "[shaders] " << filename
				<< ": shader " << block.name << " already defined." << std::endl;
		}
	}
}
Пример #4
0
void CaelumSky::Config_CloudSpeed(const std::string& section, const std::string& key, varconf::Variable& variable)
{
  if (variable.is_string() && mCaelumSystem->getCloudSystem()) {
    Ogre::Vector2 vector;
    Tokeniser tokeniser(variable);
    vector.x = atof(tokeniser.nextToken().c_str());
    vector.y = atof(tokeniser.nextToken().c_str());
    mCaelumSystem->getCloudSystem()->getLayer(0)->setCloudSpeed(vector);
  }
}
Пример #5
0
bool CaelumSun::parse(varconf::Variable& variable, Ogre::ColourValue& colour)
{
	if (variable.is_string()) {
		Tokeniser tokeniser(variable);
		colour.r = atof(tokeniser.nextToken().c_str());
		colour.g = atof(tokeniser.nextToken().c_str());
		colour.b = atof(tokeniser.nextToken().c_str());
		colour.a = atof(tokeniser.nextToken().c_str());
		return true;
	}
	return false;
}
Пример #6
0
std::string MaterialSystem::getBlock (const std::string& texture)
{
	if (texture.empty())
		return "";

	const std::string textureDir = GlobalTexturePrefix_get();
	std::string skippedTextureDirectory = texture.substr(textureDir.length());

	if (skippedTextureDirectory.empty())
		return "";

	MaterialBlockMap::iterator i = _blocks.find(skippedTextureDirectory);
	if (i != _blocks.end())
		return i->second;

	if (!_materialLoaded)
		loadMaterials();

	if (!_materialLoaded)
		return "";

	StringOutputStream outputStream;

	StringInputStream inputStream(_material);
	AutoPtr<Tokeniser> tokeniser(GlobalScriptLibrary().createSimpleTokeniser(inputStream));
	int depth = 0;
	bool found = false;
	std::string token = tokeniser->getToken();
	while (token.length()) {
		if (token == "{") {
			depth++;
		} else if (token == "}") {
			depth--;
		}
		if (depth >= 1) {
			if (depth == 1 && token == "material") {
				token = tokeniser->getToken();
				if (token == skippedTextureDirectory) {
					found = true;
					outputStream << "{ material ";
				}
			}
			if (found)
				outputStream << token << " ";
		} else if (found) {
			outputStream << "}";
			break;
		}
		token = tokeniser->getToken();
	}
	return outputStream.toString();
}
Пример #7
0
void ShadowCameraSetup::Config_ShadowOptimalAdjustFactors(const std::string& section, const std::string& key, varconf::Variable& variable)
{
	try {
		if (variable.is_string()) {
			S_LOG_VERBOSE("Setting shadow optimal adjust factor: " << static_cast<std::string>(variable));
			Tokeniser tokeniser(variable);
			mPssmSetup->setOptimalAdjustFactor(0, atof(tokeniser.nextToken().c_str()));
			mPssmSetup->setOptimalAdjustFactor(1, atof(tokeniser.nextToken().c_str()));
			mPssmSetup->setOptimalAdjustFactor(2, atof(tokeniser.nextToken().c_str()));
		}
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when setting shadow optimal adjust factors." << ex);
	}
}
Пример #8
0
FixupMap::Result FixupMap::perform()
{
	UndoableCommand cmd("performFixup");

	// Load contents
	loadFixupFile();

	// Load deprecated entities
	loadDeprecatedEntities();

	// Instantiate a line tokeniser
	parser::BasicStringTokeniser tokeniser(_contents, "\n\r");

	_curLineNumber = 0;
	std::size_t parsedSize = 0;

	while (tokeniser.hasMoreTokens())
	{
		_curLineNumber++;

		std::string line = tokeniser.nextToken();

		performFixup(line);

		// Approximate the progress
		parsedSize += line.size();

		try
		{
			double fraction = static_cast<double>(parsedSize) / _contents.size();
			_progress.setTextAndFraction(
				(boost::format(_("Processing line %d...")) % _curLineNumber).str(),
				fraction);
		}
		catch (gtkutil::ModalProgressDialog::OperationAbortedException& ex)
		{
			gtkutil::MessageBox box(_("Fixup cancelled"), ex.what(), ui::IDialog::MESSAGE_ERROR);
			box.run();
			return _result;
		}
	}

	_progress.setTextAndFraction(_("Completed"), 1.0);

	return _result;
}
Пример #9
0
void ShadowCameraSetup::Config_ShadowSplitPoints(const std::string& section, const std::string& key, varconf::Variable& variable)
{
	try {
		if (variable.is_string()) {
			Ogre::PSSMShadowCameraSetup::SplitPointList splitPointList = mPssmSetup->getSplitPoints();
			Tokeniser tokeniser(variable);
			splitPointList[0] = atof(tokeniser.nextToken().c_str());
			splitPointList[1] = atof(tokeniser.nextToken().c_str());
			splitPointList[2] = atof(tokeniser.nextToken().c_str());
			splitPointList[3] = atof(tokeniser.nextToken().c_str());
			S_LOG_VERBOSE("Setting shadow split points: " << splitPointList[0] << " " << splitPointList[1] << " " << splitPointList[2] << " " << splitPointList[3]);
			mPssmSetup->setSplitPoints(splitPointList);
		}
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when setting shadow split points." << ex);
	}
}
Пример #10
0
void LicenseParser::openLicenseFile (const std::string& filename)
{
	clearLicenses();

	std::string fullpath;
	if (os::isAbsolute(filename)) {
		fullpath = filename;
	} else {
		const std::string& appPath = GlobalRegistry().get(RKEY_APP_PATH);
		fullpath = appPath + filename;
	}

	AutoPtr<ArchiveTextFile> file(GlobalFileSystem().openTextFile(fullpath));
	if (file) {
		AutoPtr<Tokeniser> tokeniser(GlobalScriptLibrary().createScriptTokeniser(file->getInputStream()));
		parseLicensesFile(*tokeniser, fullpath);
	}
}
Пример #11
0
model::IModelPtr MD5ModelLoader::loadModelFromPath(const std::string& name)
{
	// Open an ArchiveFile to load
	ArchiveFilePtr file = GlobalFileSystem().openFile(name);

	if (file != NULL)
	{
		// Construct a new MD5Model container
		MD5ModelPtr model(new MD5Model);

		// Store the VFS path in this model
		model->setModelPath(name);
		// Set the filename this model was loaded from
		model->setFilename(os::getFilename(file->getName()));

		// greebo: Get the Inputstream from the given file
		BinaryToTextInputStream<InputStream> inputStream(file->getInputStream());

		// Construct a Tokeniser object and start reading the file
		try
		{
			std::istream is(&inputStream);
			parser::BasicDefTokeniser<std::istream> tokeniser(is);

			// Invoke the parser routine (might throw)
			model->parseFromTokens(tokeniser);
		}
		catch (parser::ParseException& e)
		{
			rError() << "[md5model] Parse failure. Exception was:" << std::endl
								<< e.what() << std::endl;
			// Return an empty model on error
			return model::IModelPtr();
		}

		// Load was successful, return the model
		return model;
	}
	else
	{
		rError() << "Failed to load model " << name << std::endl;
		return model::IModelPtr(); // delete the model
	}
}
Пример #12
0
GuiPtr GuiManager::loadGui(const std::string& guiPath)
{
	// Insert a new entry in the map, if necessary
	std::pair<GuiInfoMap::iterator, bool> result = _guis.insert(
		GuiInfoMap::value_type(guiPath, GuiInfo())
	);

	GuiInfo& info = result.first->second;

	ArchiveTextFilePtr file = GlobalFileSystem().openTextFile(guiPath);

	if (file == NULL)
	{
		std::string errMSG = "Could not open file: " + guiPath + "\n";

		_errorList.push_back(errMSG);
		rError() << errMSG;

		info.type = FILE_NOT_FOUND;

		return GuiPtr();
	}

	// Construct a Code Tokeniser, which is able to handle #includes
	try
	{
		std::string whiteSpace = std::string(parser::WHITESPACE) + ",";
		parser::CodeTokeniser tokeniser(file, whiteSpace.c_str(), "{}(),;");

		info.gui = Gui::createFromTokens(tokeniser);
		info.type = UNDETERMINED;

		return info.gui;
	}
	catch (parser::ParseException& p)
	{
		std::string errMSG = "Error while parsing " + guiPath + ": " + p.what() + "\n";
		_errorList.push_back(errMSG);
		rError() << errMSG;

		info.type = IMPORT_FAILURE;
		return GuiPtr();
	}
}
Пример #13
0
void EntityMaker::runCommand(const std::string& command, const std::string& args) {
	if (CreateEntity == command || Make == command || MakeMe == command) {
		Tokeniser tokeniser(args);
		if (tokeniser.hasRemainingTokens()) {
			std::string typeName = tokeniser.nextToken();
			Eris::TypeService* typeService = mConnection.getTypeService();
			Eris::TypeInfo* typeinfo = typeService->getTypeByName(typeName);
			if (typeinfo) {
				std::string parentEntityId = mAvatar.getEntity()->getLocation()->getId();
				if (MakeMe == command) {
					parentEntityId = mAvatar.getEntity()->getId();
				} else {
					if (tokeniser.hasRemainingTokens()) {
						parentEntityId = tokeniser.nextToken();
					}
				}
				createEntityOfType(typeinfo, parentEntityId);
			}
		}
	}
}
Пример #14
0
void MainCamera::Config_ClipDistances(const std::string& section, const std::string& key, varconf::Variable& variable)
{
	Tokeniser tokeniser(variable);
	float nearDistance = atof(tokeniser.nextToken().c_str());
	float farDistance = atof(tokeniser.nextToken().c_str());

	S_LOG_INFO("Setting main camera clip distances to near: " << nearDistance << " far: " << farDistance);

	mCamera.setNearClipDistance(nearDistance);

	//set the far clip distance high to make sure that the sky is completely shown
	if (Ogre::Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(Ogre::RSC_INFINITE_FAR_PLANE))
	{
/*		//NOTE: this won't currently work with the sky
		mCamera.setFarClipDistance(0);*/

		mCamera.setFarClipDistance(farDistance);
	} else {
		mCamera.setFarClipDistance(farDistance);
	}
}
Пример #15
0
// Parse the provided stream containing the contents of a single .def file.
// Extract all entitydefs and create objects accordingly.
void EClassManager::parse(TextInputStream& inStr, const std::string& modDir)
{
	// Construct a tokeniser for the stream
	std::istream is(&inStr);
    parser::BasicDefTokeniser<std::istream> tokeniser(is);

    while (tokeniser.hasMoreTokens())
	{
        std::string blockType = tokeniser.nextToken();
        boost::algorithm::to_lower(blockType);

        if (blockType == "entitydef")
		{
			// Get the (lowercase) entity name
			const std::string sName =
    			boost::algorithm::to_lower_copy(tokeniser.nextToken());

			// Ensure that an Entity class with this name already exists
			// When reloading entityDef declarations, most names will already be registered
			EntityClasses::iterator i = _entityClasses.find(sName);

			if (i == _entityClasses.end())
			{
				// Not existing yet, allocate a new class
        		Doom3EntityClassPtr entityClass(new eclass::Doom3EntityClass(sName));

				std::pair<EntityClasses::iterator, bool> result = _entityClasses.insert(
					EntityClasses::value_type(sName, entityClass)
				);

				i = result.first;
			}
			else
			{
				// EntityDef already exists, compare the parse stamp
				if (i->second->getParseStamp() == _curParseStamp)
				{
					rWarning() << "[eclassmgr]: EntityDef "
						<< sName << " redefined" << std::endl;
				}
			}

			// At this point, i is pointing to a valid entityclass

			i->second->setParseStamp(_curParseStamp);

        	// Parse the contents of the eclass (excluding name)
			i->second->parseFromTokens(tokeniser);

			// Set the mod directory
        	i->second->setModName(modDir);
        }
        else if (blockType == "model")
		{
			// Read the name
			std::string modelDefName = tokeniser.nextToken();

			// Ensure that an Entity class with this name already exists
			// When reloading entityDef declarations, most names will already be registered
			Models::iterator i = _models.find(modelDefName);

			if (i == _models.end())
			{
				// Does not exist yet, allocate a new one

				// Allocate an empty ModelDef
        		Doom3ModelDefPtr model(new Doom3ModelDef(modelDefName));

				std::pair<Models::iterator, bool> result = _models.insert(
					Models::value_type(modelDefName, model)
				);

				i = result.first;
			}
			else
			{
				// Model already exists, compare the parse stamp
				if (i->second->getParseStamp() == _curParseStamp)
				{
					rWarning() << "[eclassmgr]: Model "
						<< modelDefName << " redefined" << std::endl;
				}
			}

			// Model structure is allocated and in the map,
            // invoke the parser routine
			i->second->setParseStamp(_curParseStamp);

        	i->second->parseFromTokens(tokeniser);
			i->second->setModName(modDir);
        }
    }
}
Пример #16
0
int main(int argc, char **argv)
{
	int exitStatus(0);
	bool exit_program = false;
	std::string prefix("");
	std::string homeDir("");
	Ember::Application::ConfigMap configMap;
#ifndef __WIN32__
	if (argc > 1)
	{
		(argv)++;
		argc--;
		while (argc > 0)
		{
			std::string arg = std::string((char *) argv[0]);
			argv++;
			argc--;
			if (arg == "-v" || arg == "--version")
			{
				std::cout << "Ember version: " << VERSION << std::endl;
				exit_program = true;
			}
			else if (arg == "-h" || arg == "--help")
			{
				std::cout << "-h, --help    - display this message" << std::endl;
				std::cout << "-v, --version - display version info" << std::endl;
				std::cout << "--home <path> - sets the home directory to something different than the default (~/.ember on *NIX systems, $APPDATA\\Ember on win32 systems)" << std::endl;
				std::cout << "-p <path>, --prefix <path> - sets the prefix to something else than the one set at compilation (only valid on *NIX systems)" << std::endl;
				std::cout << "--config <section>:<key> <value> - allows you to override config file settings. See the ember.conf file for examples. (~/.ember/ember.conf on *NIX systems)" << std::endl;
				exit_program = true;
				break;
			}
			else if (arg == "-p" || arg == "--prefix")
			{
				if (!argc)
				{
					std::cout << "You didn't supply a prefix.";
					exit_program = true;
				}
				else
				{
					prefix = std::string((char *) argv[0]);
					argv++;
					argc--;
				}

			}
			else if (arg == "--home")
			{
				if (!argc)
				{
					std::cout << "You didn't supply a home directory.";
					exit_program = true;
				}
				else
				{
					homeDir = std::string((char *) argv[0]);
					argv++;
					argc--;
				}

			}
			else if (arg == "--config")
			{
				if (argc < 2)
				{
					std::cout << "You didn't supply any config arguments.";
				}
				else
				{
					std::string fullkey(argv[0]);
					std::string value(argv[1]);
					Ember::Tokeniser tokeniser(fullkey, ":");
					if (tokeniser.remainingTokens() != "")
					{
						std::string category(tokeniser.nextToken());
						if (tokeniser.remainingTokens() != "")
						{
							std::string key(tokeniser.nextToken());
							configMap[category][key] = value;
						}
					}
				}
			}
		}
	}

#if !defined(__WIN32__) && !defined(__APPLE__)
	if (exit_program)
	{
		return 0;
	}
#endif

#ifdef ENABLE_BINRELOC
	if (prefix == "")
	{
		BrInitError error;

		if (br_init (&error) == 0 && error != BR_INIT_ERROR_DISABLED)
		{
			printf ("Warning: BinReloc failed to initialize (error code %d)\n", error);
			printf ("Will fallback to hardcoded default path.\n");
		}

		char* br_prefixdir = br_find_prefix(PREFIX);
		const std::string prefixDir(br_prefixdir);
		free(br_prefixdir);
		prefix = prefixDir;
	}

#endif
	// 	if (prefix == "") {
	// 		prefix = PREFIX;
	// 	}

#else
	//  char tmp[64];

	//  unsigned int floatSetting = _controlfp( 0, 0 );
	//sprintf(tmp, "Original: 0x%.4x\n", floatSetting );
	//   MessageBox( 0, tmp, "floating point control", MB_OK | MB_ICONERROR | MB_TASKMODAL);
	//_fpreset();
	//_controlfp(_PC_64, _MCW_PC);
	//_controlfp(_RC_NEAR , _MCW_RC);
	//floatSetting = _controlfp( 0, 0 );
	//sprintf(tmp, "New: 0x%.4x\n", floatSetting );
	//   MessageBox( 0, tmp, "floating point control", MB_OK | MB_ICONERROR | MB_TASKMODAL);

#endif

	try
	{
	//put the application object in its own scope so it gets destroyed before we signal all clear
		{
			// Create application object
			Ember::Application app(prefix, homeDir, configMap);
			//Ember::OgreView::EmberOgre app;

			std::cout << "Starting Ember version " << VERSION << std::endl;

			app.registerComponents();

			// Initialize all Ember services needed for this application
			app.prepareComponents();
			app.initializeServices();

			app.start();
		}
	} catch (const std::exception& ex)
	{
		std::cerr << "Unexpected error, aborting.\n\r\t" << ex.what() << std::endl;
		exitStatus = 1;
	}
    std::cout << "Ember shut down successfully." << std::endl;

	return exitStatus;
}
Пример #17
0
void TableDefinition::parseDefinition()
{
	// consider ourselves parsed from now on
	_parsed = true; 

	try
	{
		// Use a tokeniser to read the values
		parser::BasicDefTokeniser<std::string> tokeniser(_blockContents, " \n\t\r,");

		std::size_t level = 0;

		while (tokeniser.hasMoreTokens())
		{
			std::string token = tokeniser.nextToken();

			if (token == "{")
			{
				++level;

				if (level > 1)
				{
					throw parser::ParseException("Too many opening braces.");
				}
			}
			else if (token == "}")
			{
				if (level == 0)
				{
					throw parser::ParseException("Too many closing braces.");
				}

				--level;
			}
			else if (token == "clamp")
			{
				if (level != 0)
				{
					throw parser::ParseException("The 'clamp' keyword cannot be used at this scope/position.");
				}

				_clamp = true;
			}
			else if (token == "snap")
			{
				if (level != 0)
				{
					throw parser::ParseException("The 'snap' keyword cannot be used at this scope/position.");
				}

				_snap = true;
			}
			else
			{
				// Expect a numeric value at this point
				try
				{
					_values.push_back(boost::lexical_cast<float>(token));
				}
				catch (boost::bad_lexical_cast& ex)
				{
					throw parser::ParseException("Invalid token '" + token + 
						"' encountered: " + ex.what());
				}
			}
		}
	}
	catch (parser::ParseException& ex)
	{
		rError() << "[shaders] Error parsing table '" << _name << "': " << ex.what() << std::endl;
	}
}
Пример #18
0
	void TextField2::parseRawText()
	{
		TextTokeniser tokeniser(mRawText.c_str());
		const char *token = tokeniser.nextToken();
		mText = "";
		mNewLinePositions.clear();
		mNewLinePositions.push_back(0);
		mNewLineDirty = true;
		bool firstLine = true;

		enum ParseState {
			BASE, START_FORMAT, END_FORMAT, IN_FORMAT_ATTR, IN_FORMAT_OP, IN_FORMAT_VALUE, POP_FORMAT
		};
		ParseState state = BASE;
		
		Handle<Node> currentNode = mRootNode;
		mRootNode->clear();

		mTextHitboxes->clear();

		string attrName = "";

		while (token != NULL)
		{
			if (state == BASE && token[0] == '<')
			{
				state = START_FORMAT;
			}
			else if (state != BASE && token[0] == '>')
			{
				state = BASE;
			}
			else if (state == START_FORMAT)
			{
				if (token[0] == '/')
				{
					state = POP_FORMAT;
				}
				else 
				{
					string lower = Utils::toLowerCase(token);
					Node *newNode = new Node(lower.c_str());
					currentNode->addChild(newNode);
					currentNode = newNode;
					state = IN_FORMAT_ATTR;
				}
			}
			else if (state == IN_FORMAT_ATTR)
			{
				if (token[0] == '>')
				{
					state = END_FORMAT;
				}
				attrName = Utils::toLowerCase(token);
				state = IN_FORMAT_OP;
			}
			else if (state == IN_FORMAT_OP)
			{
				if (token[0] == '>')
				{
					state = END_FORMAT;
				}
				else if (token[0] != '=')
				{
					currentNode->setAttribute(attrName.c_str(), "true");
					state = IN_FORMAT_ATTR;
				}
				else
				{
					state = IN_FORMAT_VALUE;
				}
			}
			else if (state == IN_FORMAT_VALUE)
			{
				if (token[0] == '>')
				{
					stringstream ss;
					ss << "Error parsing node '" << attrName << "', = operator had not value";
					am_log("TEXT", ss);
				}
				else
				{
					currentNode->setAttribute(attrName.c_str(), token);
					state = IN_FORMAT_ATTR;
				}
			}
			else if (state == END_FORMAT)
			{
				while (token != NULL && token[0] != '>')
				{
					token = tokeniser.nextToken();
				}
				state = BASE;
			}
			else if (state == POP_FORMAT)
			{
				string lower = Utils::toLowerCase(token);
				if (currentNode->getParent() == NULL)
				{
					am_log("NODE", "Pop format to NULL parent");
				}
				else
				{
					currentNode = currentNode->getParent();
				}
				state = END_FORMAT;
			}
			else if (state == BASE)
			{
				currentNode->appendText(token);
				mText += token;
			}
			if (state != END_FORMAT)
			{
				token = tokeniser.nextToken();
			}
		}

		setTextDirty(false);
	}
Пример #19
0
void CSoftUninstall::GetPinYin(const std::wstring &name, std::wstring &whole, std::wstring &acronym)
{
	typedef list<string>					str_list;
	typedef str_list::iterator				str_iter;
	typedef string_tokeniser<string, char>	string_tokeniser_a;

	typedef void (string::*PFPushback)(char);
	typedef string& (string::*PFAppend)(const char*);

	PFAppend pfAppend = &string::append;
	PFPushback pfPushback = &string::push_back;

	char mbcs[5];
	str_list wholeList, acronymList;
	wholeList.push_back(string());
	acronymList.push_back(string());

	for(wstring::size_type i = 0; i < name.size(); ++i)
	{
		if(iswascii(name[i]) == 0)
		{	// 非ASCII码
			int ret;
			if(wctomb_s(&ret, mbcs, sizeof(mbcs), name[i]) != 0) continue;
			mbcs[ret] = '\0';

			PinYinCIter itPinYin = _hashPinYin.find(mbcs);
			if(itPinYin != _hashPinYin.end())
			{
				const PinYin &pinyin = itPinYin->second;

				// M X N组合
				{
					string_tokeniser_a tokeniser(pinyin._whole, ' ');

					str_list resultList;
					string_tokeniser_a::const_iterator end = tokeniser.end();
					for(string_tokeniser_a::const_iterator it = tokeniser.begin(); it != end; ++it)
					{
						str_iter endList = wholeList.end();
						for(str_iter itList = wholeList.begin(); itList != endList; ++itList)
							resultList.push_back(*itList + *it);
					}
					wholeList.swap(resultList);
				}
				{
					string_tokeniser_a tokeniser(pinyin._acronym, ' ');

					str_list resultList;
					string_tokeniser_a::const_iterator end = tokeniser.end();
					for(string_tokeniser_a::const_iterator it = tokeniser.begin(); it != end; ++it)
					{
						str_iter endList = acronymList.end();
						for(str_iter itList = acronymList.begin(); itList != endList; ++itList)
							resultList.push_back(*itList + *it);
					}
					acronymList.swap(resultList);
				}
			}
			else
			{
				for_each(wholeList.begin(), wholeList.end(), bind2nd(mem_fun1_ref(pfAppend), mbcs));
				for_each(acronymList.begin(), acronymList.end(), bind2nd(mem_fun1_ref(pfAppend), mbcs));
			}
		}
		else
		{
			// ASCII码直接组合
			for_each(wholeList.begin(), wholeList.end(), bind2nd(mem_fun1_ref(pfPushback), (char)towlower(name[i])));
			for_each(acronymList.begin(), acronymList.end(), bind2nd(mem_fun1_ref(pfPushback), (char)tolower(name[i])));
		}
	}

	// 合并结果
	{
		ostringstream os;
		copy(wholeList.begin(), wholeList.end(), ostream_iterator<string>(os, " "));

		whole = CA2W(os.str().c_str());
		trim_right(whole);
	}

	{
		ostringstream os;
		copy(acronymList.begin(), acronymList.end(), ostream_iterator<string>(os, " "));

		acronym = CA2W(os.str().c_str());
		trim_right(acronym);
	}
}
int CPUstats::getCpuStats(int cpu_no, trio *previous, int *usage)
{
    int pos = 0;
    int busy = 0;
    int idle = 0;
    int total = 0;

    // Init file stream
    *usage = -1;
    std::ifstream stat("/proc/stat");
    if (stat.fail()) return FAILURE;

    // See procps/proc/sysinfo.c for inspiration (or comparison)...
    char buf[BUFFSIZE];
    buf[BUFFSIZE-1] = 0;
    stat.read(buf, BUFFSIZE-1);

    // Convenient Containers(TM)
    std::string content(buf);
    std::istringstream tokeniser(content);

    // Look for CPU entry
    while ((pos < content.length()) && tokeniser.good()) {
        pos = content.find("cpu", pos);

        // Check for potential match
        if ((pos + 5) < content.length()) {
            pos = pos + 3;

            // Check for CPU number as opposed to whitespace
            if (content[pos] != ' ') {
                int CPU = atoi(content.substr(pos, 2).c_str());
                pos = pos + 2;

                // Check for CPU number match
                if (CPU == cpu_no) {
                    if (content[pos] == ' ') pos++;
                    tokeniser.seekg(pos);

                    // Extract user, nice and system times
                    for (int i = 0; i < 3; i++) {
                        tokeniser >> total;
                        busy = busy + total;
                    }
                    // Extract idle time
                    tokeniser >> idle;
                    // Extract other times for total busy time
                    for (int i = 0; i < 3; i++) {
                        tokeniser >> total;
                        busy = busy + total;
                    }
                    total = busy + idle;

                    // Convert to percentage, save ticks
                    *usage = 100 * (busy - previous->busy) / (total - previous->total);
                    previous->busy = busy;
                    previous->idle = idle;
                    previous->total = total;

                    return SUCCESS;
                }
            }
        }
Пример #21
0
Ogre::Root* OgreSetup::createOgreSystem()
{
	ConfigService& configSrv(EmberServices::getSingleton().getConfigService());

	if (configSrv.getPrefix() != "") {
		//We need to set the current directory to the prefix before trying to load Ogre.
		//The reason for this is that Ogre loads a lot of dynamic modules, and in some build configuration
		//(like AppImage) the lookup path for some of these are based on the installation directory of Ember.
		if (chdir(configSrv.getPrefix().c_str())) {
			S_LOG_WARNING("Failed to change to the prefix directory '" << configSrv.getPrefix() << "'. Ogre loading might fail.");
		}
	}

	std::string pluginExtension = ".so";
	mRoot = new Ogre::Root("", "ogre.cfg", "");

	//we will try to load the plugins from series of different location, with the hope of getting at least one right
	std::vector<std::string> pluginLocations;

	if (configSrv.itemExists("ogre", "plugins")) {
		std::string plugins(configSrv.getValue("ogre", "plugins"));
		//if it's defined in the config, use that location first
		if (configSrv.itemExists("ogre", "plugindir")) {
			std::string pluginDir(configSrv.getValue("ogre", "plugindir"));
			pluginLocations.push_back(pluginDir);
		}
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		pluginExtension = ".dll";
		pluginLocations.push_back("."); //on windows we'll bundle the dll files in the same directory as the executable
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
		pluginExtension = ".so";
		std::string pluginDir = configSrv.getPrefix();
		pluginDir += "/lib/OGRE";
		pluginLocations.push_back(pluginDir);

#ifdef ENABLE_BINRELOC
		//binreloc might be used
		char* br_libdir = br_find_lib_dir(br_strcat(PREFIX, "/lib"));
		std::string libDir(br_libdir);
		free(br_libdir);
		pluginLocations.push_back(libDir + "/OGRE");
#endif
#ifdef OGRE_PLUGINDIR
		//also try with the plugindir defined for Ogre
		pluginLocations.push_back(OGRE_PLUGINDIR);
#endif
		//enter the usual locations if Ogre is installed system wide, with local installations taking precedence
		pluginLocations.push_back("/usr/local/lib/OGRE");
		pluginLocations.push_back("/usr/lib/OGRE");
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
		// On Mac, plugins are found in Resources in the Main (Application) bundle, then in the Ogre framework bundle
		pluginExtension = "";
		std::string pluginDir = configSrv.getSharedDataDirectory();
		pluginLocations.push_back(pluginDir);
		pluginDir += "/../Plugins";
		pluginLocations.push_back(pluginDir);
		pluginLocations.push_back("");
#endif
		Tokeniser tokeniser(plugins, ",");
		std::string token = tokeniser.nextToken();
		while (token != "") {
			std::string pluginPath;
			bool pluginLoaded = false;
			for (std::vector<std::string>::iterator I = pluginLocations.begin(); I != pluginLocations.end(); ++I) {
				pluginPath = (*I) + "/" + token + pluginExtension;
				S_LOG_INFO("Trying to load the plugin '" << pluginPath << "'.");
				try {
					mRoot->loadPlugin(pluginPath);
					pluginLoaded = true;
					break;
				} catch (...) {
					pluginPath = (*I) + "/" + token + "_d" + pluginExtension;
					S_LOG_INFO("Trying to load the plugin '" << pluginPath << "'.");
					try {
						mRoot->loadPlugin(pluginPath);
						pluginLoaded = true;
						break;
					} catch (...) {
					}
				}
			}
			if (pluginLoaded) {
				S_LOG_INFO("Successfully loaded the plugin '" << token << "' from '" << pluginPath << "'.");
			} else {
				S_LOG_FAILURE("Failed to load the plugin '" << token << "'!");
			}
			token = tokeniser.nextToken();
		}
	}

	if (chdir(configSrv.getEmberDataDirectory().c_str())) {
		S_LOG_WARNING("Failed to change to the data directory '" << configSrv.getEmberDataDirectory() << "'.");
	}

	return mRoot;
}
Пример #22
0
/*
  This is the main method which is invoked to assemble an IMPS assembly file. 
  This method carries sets up the tables and then carries out the two pass 
  assembly and then writes the 32-bit binary representations of the instructions
  into the file specified.
  @param argc : specifies the number of arguments providied to the program at 
                run time
  @param argv : specifes the arguments provided to the program to the run time
  @return     : returns 1 when the program suceeds without a failure.
*/
int main(int argc, char **argv) {
  assert("Wrong Number of arguments" && argc==3);
  struct Data *data = malloc(sizeof(struct Data));
  memset(data->b_instruction,0 , 65536);
  struct Table *opcodeTable = malloc(sizeof(struct Table));
  opcodeTable = initialiseOpcodeTable();
  struct Table *labelTable = malloc(sizeof(struct Table));
  labelTable = initialiseEmptyTable();
  uint32_t address = 0;
  data->number_of_instructions = 0;  
  char *readFP = argv[1];
  char *writeFP = argv[2];

  FILE *fRead = fopen(readFP,"r");
  if (fRead==NULL) {
    perror("Error is reading from file");
    exit(EXIT_FAILURE);
  }
  
  do {    
    data->a_instruction = NULL;
    readFromFile(fRead,data);
    if (strlen(data->a_instruction)==1) goto endOfPass1While;
    pass1(data->a_instruction,address,labelTable);
    address += 4;
    data->number_of_instructions++;
    endOfPass1While: ;
    free(data->a_instruction);
  } while(feof(fRead)==0);

  rewind(fRead);
  int i = 0;
  address = 0;
  while(feof(fRead)==0) {
    data->a_instruction = NULL;
    readFromFile(fRead,data);
    if (strlen(data->a_instruction)==1) goto endOfWhilePass2;
    char *tokens[5];
    tokeniser(data->a_instruction,tokens);
    if (strcmp(".skip",tokens[1])==0) {
      printBits(0);
      printf("\t%s", data->a_instruction);
      int j = atoi(tokens[2]) - 1;
      while (j>=1) {
        printBits(0);
        printf("\n");
        --j;
      }
      i += atoi(tokens[2]);
      address = i*4;
    } else {
      data->b_instruction[i] = pass2(tokens,labelTable,opcodeTable,address); 
      printBits(data->b_instruction[i]);
      printf("\t%s\n", data->a_instruction);    
      address += 4;
      i++;
    }
    endOfWhilePass2: ;
    free(data->a_instruction);
  }
  data->number_of_instructions = i;
  writeToFile(writeFP,data);
  fclose(fRead);
}
Пример #23
0
uint32_t transfer(char **arguments, assembler *instState,table_t *t){
 int P_Bit;
 char *Rd = arguments[0];
 char *address = arguments[1];
 uint32_t rd = getConst(Rd);
 int addrlen = strlen(address);

 if(*address == '='){
  //numeric constant;
  int val = getConst(address);

  if(val <= 0xFF){
   //mov instruction;
   isMov = 1;
   char **inst = malloc(sizeof(char*)*3);
   for(int i=0; i<3; i++){
	inst[i] = malloc(sizeof(char)*20);
   }
   strcpy(inst[0],"mov");
   strcpy(inst[1],Rd);
   strcpy(inst[2],(address+1));
   inst[2] = prepend(inst[2],'#');
   return ass_data_process(inst,t);

  }else{
   strip(arguments[1]);
   insertExpression(instState->BigVals,arguments[1],val,instState->counter);
   rd <<= 12;
   uint32_t val_mask = 0xE59F0000;
   return val_mask | rd;

  }
 }
 char **splitAddress = tokeniser(address,",");

 if(address[0] == '[' && address[4] != ']' && address[3] != ']'){
  //PRE instruction;
  P_Bit = 1;
  char *pre_address = removeBrackets(address);
  char **expression = tokeniser(pre_address,".");
  uint32_t rn = getConst(expression[0]);
  uint32_t transfer_mask1 = 0xE5900000;
  uint32_t incVal = getConst(expression[1]);
  uint32_t offset = incVal; //TODO: ONCE MOV is fixed replace this with the val generated by mov
  rn <<= 16;
  rd <<= 12;
  return transfer_mask1 | rn | rd | offset;

 }else if(addrlen <= 5){
  //PRE instruction;
  P_Bit = 1;
  char *Rn = removeBrackets(splitAddress[0]);
  uint32_t rn = getConst(Rn);
  uint32_t transfer_mask2 = 0xE5900000;
  rn <<= 16;
  rd <<= 12;
  return transfer_mask2 | rn | rd;

 }else{
  //Post instruction;
  P_Bit = 0;
  uint32_t transfer_mask3 = 0xE6900000;
  char **expression = tokeniser(address,".");
  uint32_t rn = getConst(removeBrackets(expression[0]));
  uint32_t offset = getConst(expression[1]);
  rn <<= 16;
  rd <<= 12;
  return transfer_mask3 | rn | rd | offset;
 }
}
Пример #24
0
void EnteredWorldState::runCommand(const std::string &command, const std::string &args)
{
  if (Say == command) {
    mAdapter.say(args);
  } else if (SayTo == command) {
    Tokeniser tokeniser(args);
    std::string entityIdsString = tokeniser.nextToken();
    std::vector < std::string > entityIds = Tokeniser::split(entityIdsString, ",");
    std::vector<const Eris::Entity*> entities;
    for (std::vector<std::string>::const_iterator I = entityIds.begin(); I != entityIds.end(); ++I) {
      Eris::Entity* entity = getView().getEntity(*I);
      if (entity) {
        entities.push_back(entity);
      } else {
        S_LOG_WARNING("Tried to send message addressed to entity with id " << *I <<" which doesn't exist.");
      }
    }
    std::string message = tokeniser.remainingTokens();

    mAdapter.sayTo(message, entities);
  } else if (Emote == command) {
    mAdapter.emote(args);
  } else if (Delete == command) {
    Tokeniser tokeniser(args);
    std::string entityId = tokeniser.nextToken();
    if (entityId != "") {
      Eris::Entity* entity = getView().getEntity(entityId);
      if (entity) {
        mAdapter.deleteEntity(entity);
      }
    }

    /*		// Touch Command
     } else if (command==TOUCH) {
     // TODO: make this switch call the touch method
     // TODO: polish this rough check
     S_LOG_VERBOSE("Touching");
     if(!mAvatar) {
     S_LOG_WARNING("No avatar.");
     return;
     }

     Atlas::Objects::Operation::Touch touch;
     Atlas::Message::MapType opargs;

     opargs["id"] = args;
     touch->setFrom(mAvatar->getId());
     touch->setArgsAsList(Atlas::Message::ListType(1, opargs));

     mConn->send(touch);*/
  } else if (AdminTell == command) {
    Tokeniser tokeniser(args);
    std::string entityId = tokeniser.nextToken();
    if (entityId != "") {
      std::string key = tokeniser.nextToken();
      if (key != "") {
        std::string value = tokeniser.nextToken();
        if (value != "") {
          mAdapter.adminTell(entityId, key, value);
        }
      }
    }
  }
}