Home - Forums - Documentation - Gallery - Bugs

Step Two : Basic configuration handling

First, from that point we will use more and more cim-specific files, like

pictures, map files, music, sound etc. It his tutorial we load the first version

of cim’s configuration file.


The configuration handling is Crystal Space is very easy to use. All plugin has

his own configuration file, you can override the values with your own

configuration file. You can add or override many option from command line. The

manual describes this mechanism in depth, please read link this section for all details.

You can configure many thing from your configuration file.

We can load plugins from the configuration file, this is a very nice feature.

You can change dynamically the plugins, without recompile your application. For

example, the cim.cfg (config file) has this line somewhere:

System.Plugins.iConsoleOutput = crystalspace.console.output.standard

That means, Crystal Space will use the standard output plugin. When you change the line a little bit:

System.Plugins.iConsoleOutput = crystalspace.console.output.fancy

In that case the fancy console output awaits you, when you run the application

(Note, we will change the console source a little bit., now it’s s load the

standard plugin statically. When you edit the walktest.cfg file, in the

/data/config directory , you can see the effect in walktest.).


You can ovveride any settings of the official CS plugins. For example:


Video.ScreenWidth = 800
Video.ScreenHeight = 600
Video.ScreenDepth = 32
Video.FullScreen = yes


When your configuration file has this lines, your app will start at 800*600

resolution, in fullscreen. You can change any system configuration key, by

adding the name and the value in the config file.

You can mount directories at runtime. For example :

VFS.Mount.lev/cim   = $@data$/cim$/
</pre

will mount your real ''cim.exe/data/cim'' directory to ''lev/cim''    the 

virtual path. I always use this solution, it’s better, then rewrite the original 
''vfs.cfg''.


Note, ''vfs.cfg'' is just a normal configuration file, with many mounting keys. 

You can add your own configuration key. Cim will use some own key, for example:

<pre>
Cim.Settings.StartLevel = terrain
Cim.Settings.EnableConsole = true;
</pre

We have to handle this config keys from code, of course.

The whole ''cim.cfg'' will look like this:

<pre>
;mounting cim working folder
;VFS.Mount.lev/cim   = $@data$/cim$/

;cs plugins
System.Plugins.iGraphics3D = crystalspace.graphics3d.opengl
System.Plugins.iConsoleInput = crystalspace.console.input.standard
System.Plugins.iConsoleOutput = crystalspace.console.output.standard
System.Plugins.iImageIO = crystalspace.graphic.image.io.multiplexer
System.Plugins.iLoader = crystalspace.level.loader
System.Plugins.iDocumentSystem = crystalspace.documentsystem.xmlread
System.Plugins.iEngine = crystalspace.engine.3d
System.ApplicationID = Tutorial.Cim

;video settings
Video.ScreenWidth = 1024
Video.ScreenHeight = 768
Video.ScreenDepth = 32
Video.FullScreen = no

;mouse settings
MouseDriver.DoubleClickTime = 300
MouseDriver.DoubleClickDist = 2

;game specific settings
Cim.Settings.StartLevel = /lev/terrain 
Cim.Settings.EnableConsole = false

This file you have to put into your CS/config/ directory.

To load a config file, first we need a pointer to the config manager. Add the

following private member to cim class in cim.h:

/// A pointer to the configuration manager.
  csRef<iConfigManager> confman;

And in the cim.cpp, on the OnInitialize function:

if (!csInitializer::SetupConfigManager (GetObjectRegistry (),
  	"/config/cim.cfg"))
    return ReportError ("Error reading config file 'cim.cfg'!");

Your config file will be loaded and your settings will be applied. Put cim.cfg

in same directory, that your cim binary, recompile the application and run it.

Try different Video.ScreenWidth Video.ScreenHeight, etc values (i.e 800*600,

1024*768), and you can see, Crystal Space respects your changes. This the the

real power of Crystal Space configuration handling.

Our config file contents the following Cim-specific keys:

Cim.Settings.StartLevel = terrain;
Cim.Settings.EnableConsole = true;

The StartLevel defines the name of the starting map, the EnableConsole decides,

the app creates a console or not.

Let’s go to to write the code.


We make many changes. First, we introduce a variable to check, we use console or

not. This will a private member of the cimGame class, called use_console. When

this flag is false, we don’t instance and use the console class. The event

handlers first check, we have console or not, to avoid crashes :

bool cimGame::OnKeyboard(iEvent& ev)
{
	
  // We got a keyboard event.
  csKeyEventType eventtype = csKeyEventHelper::GetEventType(&ev);
  if (eventtype == csKeyEventTypeDown)
  {
    // The user pressed a key (as opposed to releasing it).
    utf32_char code = csKeyEventHelper::GetCookedCode(&ev);
	

	//The user pressed tab to toggle console, when we have any console
	if (use_console)
	{
	if (code == CSKEY_TAB)
		{
			console->Toggle();
			return false;
		}
//more code of course 

(This is a very simple solution,. Cs provides us a better way to event handling,

we will deal with this problem later. )

On the cimGame::Setup, we do the following changes:


We have to change the ProcessFrame function from same reason:

void cimGame::ProcessFrame ()
{
  // First get elapsed time from the virtual clock.
  csTicks elapsed_time = vc->GetElapsedTicks ();

  csVector3 obj_move (0);
  csVector3 obj_rotate (0);

  if (use_console)
	  if(console->IsVisible() )
		  return;
// more code

We change the our console class a little bit. First, we change the plugin

loading method, we don’t use concrete plugin name, since we give the used

plugins from the configuration file:

bool cimConsole::Initialize(iObjectRegistry* obj_reg)
{
	object_reg = obj_reg;

	conout = CS_QUERY_REGISTRY(obj_reg, iConsoleOutput);
  if (!conout)
  {
    csReport (object_reg,
	    	CS_REPORTER_SEVERITY_ERROR, "cim.console",
		"Can't load the output console!");
    return false;
  }

  conin = CS_QUERY_REGISTRY(obj_reg,iConsoleInput);
  if (!conin)
  {
    csReport (object_reg,
	    	CS_REPORTER_SEVERITY_ERROR, "cim.console",
		"Can't load the input console!");
    return false;
  }

//more code

In the cimGame class, we introduce a new private function, called LoadConfig.

This function parse the application’s special konfiguration keys, and makes the

desired settings.


The configuration manger has some GetSomeType function to get the key values,

these are GetInt. GetStr, GetBool, GetFloat. This functions look up in the

configuration file, and return with the given key’s value (first parameter). You

can give a default value, when the key was not found, in the second parameter.

bool cimGame::LoadConfig()
{
	csRef<iConfigManager> confman (CS_QUERY_REGISTRY (GetObjectRegistry(), iConfigManager));
	use_console = confman->GetBool("Cim.Settings.EnableConsole ", true);
	startmap = confman->GetStr("Cim.Settings.StartLevel","terrain");
}


Finally, we learn the basics of the command line handling in CS. Cystal Space

uses heavily command lines and provides an easy way to process it by a CS based

application. The iCommandLineParser helps to do it. So we extend the

cimGame::Setup function:

csRef<iCommandLineParser> cmdline(CS_QUERY_REGISTRY (object_reg,
  	iCommandLineParser));

	 if (!cmdline) 
		 return ReportError("Failed to set up command line parser!");

Then we look up for the option enable-python-console. When the user runs the

application with this option, we set up the console anyway:

if( cmdline->GetOption("enable-python-console")) use_console=true;

Many more is possible with the command line parser, but probably this function


will you use most often.

And finally, we organize the map loading and collosion detection init code to a

new LoadMap (const char* mapname) function. This function can load any CS map

file by name:

bool cimGame::LoadMap (const char* mapname)
{
	//Delete the engine's content.
	engine->DeleteAll();

  // Set VFS current directory to the level we want to load.
  csRef<iVFS> VFS (CS_QUERY_REGISTRY (GetObjectRegistry (), iVFS));
  VFS->ChDir (mapname);
  // Load the level file which is called 'world'.
  if (!loader->LoadMapFile ("world"))
    ReportError("Error couldn't load level!");

  
   // Initialize collision objects for all loaded objects.
  csColliderHelper::InitializeCollisionWrappers (cdsys, engine);

		
  // Let the engine prepare all lightmaps for use and also free all images 
  // that were loaded for the texture manager.
  engine->Prepare ();

  // Find the starting position in this level.
  csVector3 pos (0);
  if (engine->GetCameraPositions ()->GetCount () > 0)
  {
    // There is a valid starting position defined in the level file.
    iCameraPosition* campos = engine->GetCameraPositions ()->Get (0);
    room = engine->GetSectors ()->FindByName (campos->GetSector ());
    pos = campos->GetPosition ();
  }
  else
  {
    // We didn't find a valid starting position. So we default
    // to going to room called 'room' at position (0,0,0).
    room = engine->GetSectors ()->FindByName ("room");
    pos = csVector3 (0, 0, 0);
  }
  if (!room)
    ReportError("Can't find a valid starting position!");

  // Now we need to position the camera in our world.
  view->GetCamera ()->SetSector (room);
  view->GetCamera ()->GetTransform ().SetOrigin (pos);

  // Initialize our collider actor.
  collider_actor.SetCollideSystem (cdsys);
  collider_actor.SetEngine (engine);
  csVector3 legs (.2f, .3f, .2f);
  csVector3 body (.2f, 1.2f, .2f);
  csVector3 shift (0, -1, 0);
  collider_actor.InitializeColliders (view->GetCamera (),
  	legs, body, shift);

  return true;
}

Look at the source for all changes.

Thats it. We can configure CS engine and we can add more cim-specific option

later. In the next step we will create the basement of our window handling solution.

| Article | Discussion | View source | History |