void Doom3FileSystem::initialise()
{
    rMessage() << "filesystem initialised" << std::endl;

    std::string extensions = GlobalGameManager().currentGame()->getKeyValue("archivetypes");
    boost::algorithm::split(_allowedExtensions, extensions, boost::algorithm::is_any_of(" "));

    // Build list of dir extensions, e.g. pk4 -> pk4dir
    for (std::set<std::string>::const_iterator i = _allowedExtensions.begin();
         i != _allowedExtensions.end();
         ++i)
    {
        std::string extDir = *i + "dir";
        _allowedExtensionsDir.insert(extDir);
    }

    // Get the VFS search paths from the game manager
    const game::IGameManager::PathList& paths =
        GlobalGameManager().getVFSSearchPaths();

    // Initialise the paths, in the given order
    for (game::IGameManager::PathList::const_iterator i = paths.begin();
         i != paths.end(); i++)
    {
        initDirectory(*i);
    }

    for (ObserverList::iterator i = _observers.begin(); i != _observers.end(); ++i)
    {
        (*i)->onFileSystemInitialise();
    }
}
void Doom3ShaderSystem::loadMaterialFiles()
{
	// Get the shaders path and extension from the XML game file
	xml::NodeList nlShaderPath =
		GlobalGameManager().currentGame()->getLocalXPath("/filesystem/shaders/basepath");
	if (nlShaderPath.empty())
		throw xml::MissingXMLNodeException(MISSING_BASEPATH_NODE);

	xml::NodeList nlShaderExt =
		GlobalGameManager().currentGame()->getLocalXPath("/filesystem/shaders/extension");
	if (nlShaderExt.empty())
		throw xml::MissingXMLNodeException(MISSING_EXTENSION_NODE);

	// Load the shader files from the VFS
	std::string sPath = nlShaderPath[0].getContent();
	if (!boost::algorithm::ends_with(sPath, "/"))
		sPath += "/";

	std::string extension = nlShaderExt[0].getContent();

	// Load each file from the global filesystem
	ShaderFileLoader loader(sPath, _currentOperation);
	{
		ScopedDebugTimer timer("ShaderFiles parsed: ");
        GlobalFileSystem().forEachFile(sPath, extension, [&](const std::string& filename)
        {
            loader.addFile(filename);
        }, 0);
		loader.parseFiles();
	}

	rMessage() << _library->getNumShaders() << " shaders found." << std::endl;
}
Exemple #3
0
void StimTypes::reload()
{
	_stimTypes.clear();
	_listStore->Clear();

	// Find all the relevant nodes
	xml::NodeList stimNodes = GlobalGameManager().currentGame()->getLocalXPath(RKEY_STIM_DEFINITIONS);

	for (std::size_t i = 0; i < stimNodes.size(); ++i)
	{
		// Add the new stim type
		add(string::convert<int>(stimNodes[i].getAttributeValue("id")),
			stimNodes[i].getAttributeValue("name"),
			stimNodes[i].getAttributeValue("caption"),
			stimNodes[i].getAttributeValue("description"),
			stimNodes[i].getAttributeValue("icon"),
			false	// non-custom stim
		);
	}

	// Load the custom stims from the storage entity
	std::string storageEClass = game::current::getValue<std::string>(GKEY_STORAGE_ECLASS);
	Entity* storageEntity = findEntityByClass(storageEClass);

	if (storageEntity != NULL)
	{
		// Visit each keyvalue with the <self> class as visitor
		storageEntity->forEachKeyValue(*this);
	}
}
Exemple #4
0
void GameManager::constructPreferencePage (PreferenceGroup& group)
{
	// Add a page to the given group
	PreferencesPage* page(group.createPage(_("Path"), _("Path Preferences")));

	// Add the sliders for the movement and angle speed and connect them to the observer
	page->appendPathEntry(GlobalGameManager().getKeyValue("name") + " " + std::string(_("Installation Path")), RKEY_ENGINE_PATH, true);
}
Exemple #5
0
MapFormatPtr Map::getFormatForFile(const std::string& filename)
{
    // Look up the module name which loads the given extension
    std::string gameType = GlobalGameManager().currentGame()->getKeyValue("type");

    MapFormatPtr mapFormat = GlobalMapFormatManager().getMapFormatForGameType(
        gameType, path_get_extension(filename.c_str()));

    ASSERT_MESSAGE(mapFormat != NULL, "map format not found for file " + filename);

    return mapFormat;
}
void MapExporter::construct()
{
	if (_totalNodeCount > 0 && GlobalMainFrame().isActiveApp())
	{
		enableProgressDialog();
	}

	// Prepare the output stream
	game::IGamePtr curGame = GlobalGameManager().currentGame();
	assert(curGame != NULL);

	xml::NodeList nodes = curGame->getLocalXPath(RKEY_FLOAT_PRECISION);
	assert(!nodes.empty());

	int precision = string::convert<int>(nodes[0].getAttributeValue("value"));
	_mapStream.precision(precision);

	// Add origin to func_* children before writing
	prepareScene();
}
// Populate tree view
void AddPropertyDialog::populateTreeView()
{
	wxIcon folderIcon;
	folderIcon.CopyFromBitmap(wxArtProvider::GetBitmap(GlobalUIManager().ArtIdPrefix() + FOLDER_ICON));

	// DEF-DEFINED PROPERTIES
	{
		// First add a top-level category named after the entity class, and populate
		// it with custom keyvals defined in the DEF for that class
		std::string cName = _entity->getEntityClass()->getName();

		wxutil::TreeModel::Row defRoot = _treeStore->AddItem();

		wxDataViewItemAttr blueBold;
		blueBold.SetColour(wxColor(0,0,255));
		blueBold.SetBold(true);

		defRoot[_columns.displayName] = wxVariant(wxDataViewIconText(cName, folderIcon));
		defRoot[_columns.displayName] = blueBold;
		defRoot[_columns.propertyName] = "";
		defRoot[_columns.description] = _(CUSTOM_PROPERTY_TEXT);

		defRoot.SendItemAdded();

		// Use a CustomPropertyAdder class to visit the entityclass and add all
		// custom properties from it
		CustomPropertyAdder adder(_entity, _treeStore, _columns, defRoot.getItem());
		_entity->getEntityClass()->forEachClassAttribute(boost::ref(adder));
	}

	// REGISTRY (GAME FILE) DEFINED PROPERTIES 

	// Ask the XML registry for the list of properties
    game::IGamePtr currentGame = GlobalGameManager().currentGame();
    xml::NodeList propNodes = currentGame->getLocalXPath(PROPERTIES_XPATH);

	// Cache of property categories to GtkTreeIters, to allow properties
	// to be parented to top-level categories
	typedef std::map<std::string, wxDataViewItem> CategoryMap;
	CategoryMap categories;

	// Add each .game-specified property to the tree view
	for (xml::NodeList::const_iterator iter = propNodes.begin();
		 iter != propNodes.end();
		 ++iter)
	{
		// Skip hidden properties
		if (iter->getAttributeValue("hidden") == "1")
		{
			continue;
		}

		wxDataViewItem item;

		// If this property has a category, look up the top-level parent iter
		// or add it if necessary.
		std::string category = iter->getAttributeValue("category");

		if (!category.empty())
		{
			CategoryMap::iterator mIter = categories.find(category);

			if (mIter == categories.end())
			{
				// Not found, add to treestore
				wxutil::TreeModel::Row catRow = _treeStore->AddItem();

				catRow[_columns.displayName] = wxVariant(wxDataViewIconText(category, folderIcon));;
				catRow[_columns.propertyName] = "";
				catRow[_columns.description] = "";

				// Add to map
				mIter = categories.insert(CategoryMap::value_type(category, catRow.getItem())).first;

				catRow.SendItemAdded();
			}

			// Category sorted, add this property below it
			item = _treeStore->AddItem(mIter->second).getItem();

			_treeStore->ItemAdded(mIter->second, item);
		}
		else
		{
			// No category, add at toplevel
			item = _treeStore->AddItem().getItem();

			_treeStore->ItemAdded(_treeStore->GetRoot(), item);
		}

		// Obtain information from the XML node and add it to the treeview
		std::string name = iter->getAttributeValue("match");
		std::string type = iter->getAttributeValue("type");
		std::string description = iter->getContent();

		wxutil::TreeModel::Row row(item, *_treeStore);

		wxIcon icon;
		icon.CopyFromBitmap(PropertyEditorFactory::getBitmapFor(type));

		row[_columns.displayName] = wxVariant(wxDataViewIconText(name, icon));
		row[_columns.propertyName] = name;
		row[_columns.description] = description;

		_treeStore->ItemChanged(item);
	}
}
Exemple #8
0
// Try to create a CM from the selected entity
void createCMFromSelection(const cmd::ArgumentList& args) {
	// Check the current selection state
	const SelectionInfo& info = GlobalSelectionSystem().getSelectionInfo();
	
	if (info.totalCount == info.entityCount && info.totalCount == 1) {
		// Retrieve the node, instance and entity
		const scene::INodePtr& entityNode = GlobalSelectionSystem().ultimateSelected();
		
		// Try to retrieve the group node
		scene::GroupNodePtr groupNode = Node_getGroupNode(entityNode);
		
		// Remove the entity origin from the brushes
		if (groupNode != NULL) {
			groupNode->removeOriginFromChildren();
			
			// Deselect the node
			Node_setSelected(entityNode, false);
			
			// Select all the child nodes
			NodeSelector visitor;
			entityNode->traverse(visitor);
			
			BrushPtrVector brushes = algorithm::getSelectedBrushes();
		
			// Create a new collisionmodel on the heap using a shared_ptr
			cmutil::CollisionModelPtr cm(new cmutil::CollisionModel());
		
			// Add all the brushes to the collision model
			for (std::size_t i = 0; i < brushes.size(); i++) {
				cm->addBrush(brushes[i]->getBrush());
			}
			
			ui::ModelSelectorResult modelAndSkin = ui::ModelSelector::chooseModel("", false, false);
			std::string basePath = GlobalGameManager().getModPath();
			
			std::string modelPath = basePath + modelAndSkin.model;
			
			std::string newExtension = "." + GlobalRegistry().get(RKEY_CM_EXT);
			
			// Set the model string to correctly associate the clipmodel
			cm->setModel(modelAndSkin.model);
			
			try {
				// create the new autosave filename by changing the extension
				Path cmPath = boost::filesystem::change_extension(
						Path(modelPath, boost::filesystem::native), 
						newExtension
					);
				
				// Open the stream to the output file
				std::ofstream outfile(cmPath.string().c_str());
				
				if (outfile.is_open()) {
					// Insert the CollisionModel into the stream
					outfile << *cm;
					// Close the file
					outfile.close();
					
					globalOutputStream() << "CollisionModel saved to " << cmPath.string() << std::endl;
				}
				else {
					gtkutil::errorDialog(
						(boost::format("Couldn't save to file: %s") % cmPath.string()).str(),
						 GlobalMainFrame().getTopLevelWindow());
				}
			}
			catch (boost::filesystem::filesystem_error f) {
				globalErrorStream() << "CollisionModel: " << f.what() << std::endl;
			}
			
			// De-select the child brushes
			GlobalSelectionSystem().setSelectedAll(false);
			
			// Re-add the origin to the brushes
			groupNode->addOriginToChildren();
		
			// Re-select the node
			Node_setSelected(entityNode, true);
		}
	}
	else {
		gtkutil::errorDialog(
			_(ERRSTR_WRONG_SELECTION.c_str()), 
			GlobalMainFrame().getTopLevelWindow());
	}
}
void ParticlesManager::saveParticleDef(const std::string& particleName)
{
	ParticleDefMap::const_iterator found = _particleDefs.find(particleName);

	if (found == _particleDefs.end())
	{
		throw std::runtime_error(_("Cannot save particle, it has not been registered yet."));
	}

	ParticleDefPtr particle = found->second;

	std::string relativePath = PARTICLES_DIR + particle->getFilename();

	fs::path particlesModPath = GlobalGameManager().getModPath();
	particlesModPath /= PARTICLES_DIR;

	// Ensure the particles folder exists
	fs::create_directories(particlesModPath);

	fs::path targetFile = particlesModPath / particle->getFilename();

	// If the file doesn't exist yet, let's check if we need to inherit stuff first from the VFS
	if (!fs::exists(targetFile))
	{
		ArchiveTextFilePtr inheritFile = GlobalFileSystem().openTextFile(relativePath);

		if (inheritFile != NULL)
		{
			// There is a file with that name already in the VFS, copy it to the target file
			TextInputStream& inheritStream = inheritFile->getInputStream();

			std::ofstream outFile(targetFile.string().c_str());

			if (!outFile.is_open())
			{
				throw std::runtime_error(
					(boost::format(_("Cannot open file for writing: %s")) % targetFile.string()).str());
			}

			char buf[16384];
			std::size_t bytesRead = inheritStream.read(buf, sizeof(buf));

			while (bytesRead > 0)
			{
				outFile.write(buf, bytesRead);

				bytesRead = inheritStream.read(buf, sizeof(buf));
			}

			outFile.close();
		}
	}

	// Open a temporary file
	fs::path tempFile = targetFile;

	tempFile.remove_filename();
	tempFile /= "_" + os::filename_from_path(targetFile);

	std::ofstream tempStream(tempFile.string().c_str());

	if (!tempStream.is_open())
	{
		throw std::runtime_error(
				(boost::format(_("Cannot open file for writing: %s")) % tempFile.string()).str());
	}

	std::string tempString;

	// If a previous file exists, open it for reading and filter out the particle def we'll be writing
	if (fs::exists(targetFile))
	{
		std::ifstream inheritStream(targetFile.string().c_str());

		if (!inheritStream.is_open())
		{
			throw std::runtime_error(
					(boost::format(_("Cannot open file for reading: %s")) % targetFile.string()).str());
		}

		// Write the file to the output stream, up to the point the particle def should be written to
		stripParticleDefFromStream(inheritStream, tempStream, particleName);

		if (inheritStream.eof())
		{
			// Particle def was not found in the inherited stream, write our comment
			tempStream << std::endl << std::endl;

			writeParticleCommentHeader(tempStream);
		}

		// We're at the insertion point (which might as well be EOF of the inheritStream)

		// Write the particle declaration
		tempStream << *particle << std::endl;

		tempStream << inheritStream.rdbuf();

		inheritStream.close();
	}
	else
	{
		// Just put the particle def into the file and that's it, leave a comment at the head of the decl
		writeParticleCommentHeader(tempStream);

		// Write the particle declaration
		tempStream << *particle << std::endl;
	}

	tempStream.close();

	// Move the temporary stream over the actual file, removing the target first
	if (fs::exists(targetFile))
	{
		try
		{
			fs::remove(targetFile);
		}
		catch (fs::filesystem_error& e)
		{
			rError() << "Could not remove the file " << targetFile.string() << std::endl
				<< e.what() << std::endl;

			throw std::runtime_error(
				(boost::format(_("Could not remove the file %s")) % targetFile.string()).str());
		}
	}

	try
	{
		fs::rename(tempFile, targetFile);
	}
	catch (fs::filesystem_error& e)
	{
		rError() << "Could not rename the temporary file " << tempFile.string() << std::endl
			<< e.what() << std::endl;

		throw std::runtime_error(
			(boost::format(_("Could not rename the temporary file %s")) % tempFile.string()).str());
	}
}