Upgrading a function that loads config files.

Started by
13 comments, last by SeanMiddleditch 9 years, 7 months ago

Hello everyone.

This is my first thread here but that's not important. The real problem is my member function of cGame class which load config files from the same folder where the .exe files is. It works but the statements must hardcoded. Here is what I mean (behold the chaos):


void cGame::FindOption(std::string wantedTag, std::string wantedOption, std::ifstream *InputStream)
{
	//It works somehow
	char buffer[10];
	std::string tagName;
	std::string optionName;
	bool success = false;
	bool tagFound = false;
	while (!(InputStream->eof()) && (success == false)) // Keeps doing it's stuff untill EOF
	{
		while (buffer[0] != '[' && tagFound == false && !(InputStream->eof())) // looks for a tag eg. [TAG]
			InputStream->get(buffer[0]);
		if (buffer[0] == '[') // if [ sign found then it gets the word between []
		{
			InputStream->get(buffer[0]);
			while (buffer[0] != ']')
			{
				tagName += buffer[0]; // letter by letter T - A - G
				InputStream->get(buffer[0]);
			}
		}
		if (tagName == wantedTag) // if the tag matches the wanted tag it begins to search for option names
		{
			tagFound = true; // also sets the tagFound to success if the tag matches
			InputStream->get(buffer[0]); // skips to next line
			while (InputStream->get(buffer[0]) && buffer[0] != '=' && buffer[0] != ' ' && optionName != wantedOption && !(InputStream->eof())) // begins to get words untill wantedoption found
			{
				if (buffer[0] != '\n') // if not a new line then ...
					optionName += buffer[0]; // letter by letter again :D it works...
				else if (buffer[0] == '\n') // new lines mean that a word hasn't been found in the current line...
					optionName = ""; // so we clear the buffer
			}
			if (optionName == wantedOption) // checks for possible matches // TODO: find a way to make a template for this chaos ( so it doesn't have to be hardcoded this way : / )
			{
				if (wantedOption == "WINDOWED")
				{
					InputStream->get(buffer[0]); // 
					InputStream->get(buffer[0]); // skips " = "
					bool get; 
					*InputStream >> get;
					GraphicsManager->SetWindowed(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "VSYNC")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					bool get;
					*InputStream >> get;
					GraphicsManager->SetVsync(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "SCREEN_WIDTH")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					GraphicsManager->SetWidth(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "SCREEN_HEIGHT")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					GraphicsManager->SetHeight(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "FREQUENCY")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					SoundManager->SetFrequency(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "FORMAT")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					Uint16 get;
					*InputStream >> get;
					SoundManager->SetFormat(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "CHANNELS")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					SoundManager->SetChannels(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "CHUNK_SIZE")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					SoundManager->SetChunkSize(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}

				success = true; // if optionName matches wantedName it sets success to true, meaning that we can end this loop
			}
			else
				optionName = ""; // if option hasn't been found, check another line
		}
		else 
			tagName = ""; // if tag hasn't been found, check another line
	}
	InputStream->seekg(0, std::ios::beg); // if we're done with this TAG - OPTION set we shall return the bricks to original state ( get to the beginning of the file )
}
void cGame::LoadSettings()
{
	std::ifstream Input; // creates our input variable

	Input.open("game.cfg"); // open cfg file

	if (!(Input.good())) // this checks of the file has been opened and if not it creates a new cfg file with default variables from cGraphicsManager.h and cSoundManager.h
	{
		std::cout << "File doesn't exist. Creating new CFG file.\n";
		Input.close(); // we don't need input now
		std::ofstream Output;
		Output.open("game.cfg");

		SDL_Delay(2000);
		GraphicsManager->SetWindowed();
		GraphicsManager->SetVsync();
		GraphicsManager->SetWidth();
		GraphicsManager->SetHeight();
		SoundManager->SetFrequency();
		SoundManager->SetFormat();
		SoundManager->SetChannels();
		SoundManager->SetChunkSize();

		Output << "[GRAPHICS]\n";
		Output << "WINDOWED = " << GraphicsManager->GetWindowed() << "\n";
		Output << "VSYNC = " << GraphicsManager->GetVsync() << "\n";						
		Output << "SCREEN_WIDTH = " << GraphicsManager->GetWidth() << "\n";					
		Output << "SCREEN_HEIGHT = " << GraphicsManager->GetHeight() << "\n";				
																							
		Output << "[SOUND]\n";																
		Output << "FREQUENCY = " << SoundManager->GetFrequency() << '\n';					
		Output << "FORMAT = " << SoundManager->GetFormat() << '\n';							
		Output << "CHANNELS = " << SoundManager->GetChannels() << '\n';						
		Output << "CHUNNK_SIZE = " << SoundManager->GetChunkSize() << '\n';					
																							
		Output.close();

	}
	else if (Input.good()) // if file has been found then it begins to load the settings 
	{
		std::cout << "CFG file found. Loading settings.\n";

		std::cout << "GRAPHICS: \n";
		FindOption("GRAPHICS", "WINDOWED", &Input);
		FindOption("GRAPHICS", "SCREEN_WIDTH", &Input);
		FindOption("GRAPHICS", "SCREEN_HEIGHT", &Input);
		FindOption("GRAPHICS", "VSYNC", &Input);

		std::cout << "\nSOUND: \n";
		FindOption("SOUND", "FREQUENCY", &Input);
		FindOption("SOUND", "FORMAT", &Input);
		FindOption("SOUND", "CHANNELS", &Input);
		FindOption("SOUND", "CHUNK_SIZE", &Input);

		Input.close();
	}
	std::cout << "CFG file loaded.\n\n";
}

Is there any way to shorten this example:


if (optionName == wantedOption) 
{
     if (wantedOption == "WINDOWED")
     {
          InputStream->get(buffer[0]); //
          InputStream->get(buffer[0]); // skips " = "
          bool get;
          *InputStream >> get;
          GraphicsManager->SetWindowed(get);
          std::cout << wantedOption << " = " << get << std::endl;
     }
}

into something like this:


if (optionName == wantedOption)
{
       InputStream->get(buffer[0]); //
       InputStream->get(buffer[0]); // skips " = "
       type get; // type declared in function call or template?
       *InputStream >> Function() // function passed by pointer as an argument
}

So instead of making dozens of new cases I could call one which will automaticaly detect what type of variable I'd like to get from the file and pass it to a function (function pointer) that might be my FindOption function parameter.

Here's function prototype that I thought about but after all it didn't make any sense to me:

void cGame::FindOption(std::string wantedTag, std::string wantedOption, std::ifstream *InputStream, type (*function)(some type));

Function call:

FindOption("SOUND", "CHANNELS", &Input, SoundManager->SetChannels(type must be integer));

Normally I'd just keep on adding new statements until I'd end up with 30 of them and a vacation in a hospital with mental disorder but I'd like make this project clear for future developement and not waste my time in any kind of hospital.

Thanks in advance.

Advertisement

My suggestion would be to look at storing your config files using a standard type, like json. You could then use the jsoncpp lib (or jansson, or any other C/C++ compatible json API) to load the config file, and simply get the values using jsoncpp API's. Take a look at it, I think you'll like it better than creating your own config file.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

Thanks for the suggestion. I shall give it a try and respond when I find it useful or not :)

Aside from what BeerNutts suggested, you might also replace the whole "if" conditions with a registry-system of some kind. I don't know how familiar you are with templates, but here is a possible solution:


// base interface for handling a setting change.
class SettingHandlerBase
{
public:
	
	virtual ~SettingHandlerBase(void) = 0 {}
	
	virtual void FromString(const std::string& strValue) = 0;
}

// proxy class that offers an interface for a specific setting value type
template<typename Type>
class SettingHandlerProxy :
	public SettingHandlerBase
{
public:
	void FromString(const std::string& strValue) override final
	{
		const Type value = FromString<Type>(strValue);
		
		OnFromString(value);
	}
	
private:
	
	virtual void OnFromString(Type type) = 0;
}

// convenience class that wraps a setter call for a certain object
template<typename Type, typename ObjectType>
class SettingHandler :
	public SettingHandlerProxy<Type>
{
private:

	SettingHandler(ObjectType& object, void (ObjectType::*pFunction)(Type)) : m_pObject(&object),
		m_pFunction(pFunction)
	{
	}

	void OnFromString(Type type) override final;
	{
		m_pObject->*pFunction(type);
	}
	
	ObjectType* m_pObject;
	void (ObjectType::*m_pFunction)(Type);
}

template<typename Type>
Type fromString(const std::string& strValue)
{
	static_assert(false, "Type cannot be converted to string");
}

// overload the template function for every type you want to support like bool, int, etc..
template<>
Type fromString<bool>(const std::string& strValue)
{
	// add type specific conversion code here
}


// in your code

std::map<std::wstring, SettingHandlerBase*> m_mHandler; // store this in your Loader-class

// for every setting, do:

auto pHandler = new SettingHandler(GraphicsManager, &GraphicsManager::SetWindowed); // should be able to deduce the template arguments automatically
// if not, write this:
auto pHandler = new SettingHandler<bool, GraphicsManager>(GraphicsManager, &GraphicsManager::SetWindowed);
// store it in the map

m_mHandler["WINDOWED"] = pHandler;

Instead of hard-coding the handling of the setting, you have general SettingHandlerBase-class, which has a virtual method called "FromString" (could be SetFromString, if thats more clear). Then you have a map of SettingHandlerBase-pointer associated with the name of the setting. At some point, you register all your setting to that map. Thats where the two templated classes from below come into play - you could just create a single class per setting, but its more convenient to be able to use the "SettingHandler"-class to quickly create a class that calls a specific setter on a certain object, like your GraphisManager.

As for actually using it, you can loop over the map, and see if your file has a certain tag with that name (especially easy with JSON/XML/...), and then simply call the FromString(valueString) method.

Hopefully I haven't confused you too much, since I don't really know your skills in c++. Just wanted to offer a more flexible/scalable solution. Also note that this code is not tested and probably contains a few compilation errors - which I might fix once I get home.

Sooner or later I'd have to learn to use templates and now there's an oportunity. I only covered the basics of templates so far but my current knowledge is not enought to understand what you wrote. Give me a day and I'll try fix the lack of it ^^ and of course thank you for your suggestion.

You could also use XML. It will make the code more organized and TinyXML (http://www.grinninglizard.com/tinyxml2/) is awesome for file loading in this style. Using it in my Engine and it has worked really well.

You could also use XML. It will make the code more organized and TinyXML (http://www.grinninglizard.com/tinyxml2/) is awesome for file loading in this style. Using it in my Engine and it has worked really well.

FWIW, I used to use XML before I found out about JSON, but JSON is so easy and non-verbose, while xml can be a pain in the butt.

For example:


{ "Hero" :
  {"Health": 100, "Strength": 10, "Mana": 100, "Image": "HeroImage.png", "Inventory": ["Map", "Compass", "Sword"]}
}

In json defines a hero and his inventory. To do the same in XML:


<Hero>
  <Health>100</Health>
  <Strength>10</Strength>
  <Mana>100</Mana>
  <Image>"HeroImage.png"</Image>
  <Inventory>
    <Item>"Map"</Item>
    <Item>"Compass"</Item>
    <Item>"Sword"</Item>
  </Inventory>
</Hero>

IMO, I found json to be much easier to work with, and the C++ json API's were easy to use too.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

I found TinyXML much easier to set up. It was ready to go in 20 minutes. Can't same the same thing about jsoncpp because I still haven't figured out how to get necessary header and source files.

Using CMake is really confusing. Will the header and source files copied from jsoncpp-master (raw zip file from github) work?

I found TinyXML much easier to set up. It was ready to go in 20 minutes. Can't same the same thing about jsoncpp because I still haven't figured out how to get necessary header and source files.

Using CMake is really confusing. Will the header and source files copied from jsoncpp-master (raw zip file from github) work?

Are you using visual studio? There's a makefile you can use to build it under makefiles/msvc2010 (and one for vs71 too). Otherwise, you can use python to make the amalgamated build (read the docs), but you need python 2.6+ at least.

Good luck!

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)


For example:

{ "Hero" :
{"Health": 100, "Strength": 10, "Mana": 100, "Image": "HeroImage.png", "Inventory": ["Map", "Compass", "Sword"]}
}

In json defines a hero and his inventory. To do the same in XML:


100
10
100
"HeroImage.png"

"Map"
"Compass"
"Sword"



IMO, I found json to be much easier to work with, and the C++ json API's were easy to use too.

Thats kind of a contrived example though. First of all, you can use attributes in XML, which kind of goes against "best practices", but for a private project, whatever. Also, while both XML and JSON are selles as "human readable file formats", that argument kind of falls flat for any project that uses some sort of toolchain for e.g. generating levels, but doesn't want to enroll their own file format. So the recommendation from my side was, use whatever you please. If you only intendt to read/write files from c++-code, use whatever file format/libary works the best.

This topic is closed to new replies.

Advertisement