ClanLib logo

ClanLib tutorial: The first steps

This is not updated yet!

The first steps

Here I will describe some simple examples of programs. Finally, code! The programs are divided into the following categories:
  • 2D Graphics
    How to work with displays, surfaces and other 2d-graphics.
  • The ResourceManager
    Working with resources, the ResourceManager and the datafile_compiler.
  • Handling input
    How to read keyboard, mouse and joystick input.
  • Sound
    How to use network support.
But first a note on compiling the code. You'll need a c++ compiler which can handle exceptions. If it starts whining about reserved words like 'catch', 'throw' and 'try' you probably need to upgrade your compiler. On Linux/Unix systems, you'll need to link the clanlib libraries. If you only use layer1 stuff from ClanLib you need to link the clan library. If you use layer2 classes, you'll also need to link clanlayer2.
The commandline I use looks like this:
      g++ -lclan -lclanlayer2 -I ../ClanLib kwirk.cpp -o kwirk
    
Use the -I to indicate where the ClanLib headerfiles reside. This way, you can use
    #include <clanlib.h>
and so make a clear distinction between your own code, and the libraries you use. Note that in the 0.3.x serie you don't need to specify the -I as the headerfiles are copied into
    /usr/local/include/ClanLib
. Remember that you need to
    #include <ClanLib/core.h>
instead of
    #include <clanlib.h>
.

When you want to use the 0.3.x serie, you'll need to change the libs you compile to and the include files. In 0.3.x you only link with what you need, so make your choice:

  • libclanCore
    Basic stuff, you'll need this one.
  • libclanGL
    OpenGL support (Windows and Unix)
  • libclanMikMod
    Soundmodules support (.xm, .mod, etc)
  • libclanPNG
    PNG files support
  • libclanLua
    Lua scripting language support
  • libclanCMPEG
    MPEG player support
All these files are by default installed in
    /usr/local/lib/
.

The include files are installed in

    /usr/local/ClanLib/
and are divided too.
  • #include <ClanLib/core.h>
    Basic stuff, you'll need this one.
  • #include <ClanLib/gl.h>
    OpenGL support (Windows and Unix)
  • #include <ClanLib/mikmod.h>
    Soundmodules support (.xm, .mod, etc)
  • #include <ClanLib/png.h>
    PNG files support
  • #include <ClanLib/lua.h>
    Lua scripting language support
  • #include <ClanLib/cmpeg.h>
    MPEG player support
  • #include <ClanLib/stl>
    Support for STL
So, if you want to compile these examples for 0.3.x you'll need to change the
     #include 
statements and pray the API hasn't changed too much ;).

If you want to compile under Windows, you'll need to link all the libraries found in the distribution. This can be done somewhere in the menu of your favourite compiler. Also see the README.TXT in the package.
Correct me if I am wrong here... I don't have a C++ compiler for windows...

ClanLib supports several display targets. If you're running under Linux/Unix than ClanLib will ask you which display target it should use. Currently the following display-targets are used: svga, mesa, x11, ggi and fbdev. You can make a ~/.clanlib file in which you can set a line containing

    target = <displaytarget>
. ClanLib will search for this file and use the target which is specified herein.
Under Windows, ClanLib will use DirectX (3 or better). In the new 0.3.x branche there is a configuration tool which allows you to choose between DirectX, PTC or OpenGL. Work is still in progress here.

2D Graphics

Showing a picture

The classic way of starting a tutorial is by saying "hello world!". Well, I assume you already know how to do this with C/C++. So, let's start with showing a picture with these famous words in it. The program: demo1.cpp, and the picture image1.tga.
As you can see, quite a lot happens here. I'll walk you through it, step by step.
    #include <clanlib.h>    
    #include <clanlayer2.h> 
    
These are the headerfiles that include the classdefinitions of ClanLib. The first describes all Layer 1 files, the second the Layer 2. In this example we use the CL_TargaProvider so we need the Layer 2 headerfile.

    class TDemo1 : public CL_ClanApplication
    {
       ...
    } app;
    
As you can see, we create a new class derived from CL_ClanApplication and create an instance called app. This is the way you make a ClanLib program.
If you make a new application you need to supply at least two functions:
      virtual char *get_title()
      { return "Demo1: image viewing"; }
    
      virtual int main(int, char**)
      {
        ...
      }
    
The get_title() is used when your program runs under X or Windows to show in the titlebar.
The main() is exactly the same as the main() in a normal C/C++ program.

Now, on to the more interesting parts.

        CL_System::init_display();
        CL_Display::set_videomode(320, 200, 16);
    
First, a call to
    CL_System::init_display()
is done. This is needed to detect all videocards and set up some internal variables. Then, we call
    CL_Display::setvideomode(width,height,bpp)
to specify in which mode we should run. In X or Windows the width and height will specify how large the window will be. The bpp (or bits per pixel) specifies in which colormode it should run. Note that I use the CL_Display rather than CL_DisplayCard because I want to use the default (primary) videocard.
        CL_Surface *image = CL_TargaProvider::create("helloworld.tga",NULL);
    
This creates the surface which contains the image. Note that CL_TargaProvider actually is a CL_SurfaceProvider. The
    ::create()
is merely a handy function which creates a surface with a surfaceprovider of the CL_TargaProvider type. This is actually equivalent with:
      CL_Surface *image = CL_Surface::create( new CL_TargaProvider("helloworld.tga",NULL), true );
    
Note that, again, we use a static function
    ::create
. The contructor for CL_Surface (and many other classes) are not public. This is because several other things have to be done before the actual Surface can be created. Therefor the constructor is wrapped into a function. And it's easier. Now, if you are out of memory or for another reason the CL_Surface can't be created, ClanLib will assert and prevent possible NULL-pointer exceptions this way.
        image->put_screen(0,0);
        CL_Display::flip_display();
    
The first line gives the surface the command to draw itself onto the backbuffer. It is not yet shown, see "Buffering" in Basics for a brief discussion why. The second line gives the Display the order to show the surface on the backbuffer on the screen. This will actually show the picture.
        while (CL_Keyboard::get_keycode(CL_Keyboard::KEY_ESCAPE) == 0)
          CL_System::keep_alive();
    
The CL_Keyboard is here used to check if the Escape-key is pressed. It does this in a loop and doing so, it halts the entire program, not allowing ClanLib to do anything. Therefor you need to call CL_System::keep_alive() once in a while. This refreshes the keyboardbuffer and does many other things.
        delete image;
    
Yeps, just like your mammy always says. CLEAN UP AFTER YOU'RE DONE WITH IT. Ah well, has nothing to do with ClanLib. It is just good coding to clean up your own mess. (Except in Java that is ;)

So, there you have it. Your first ClanLib program. Nothing to it, is there?

Working with layers and alpha-channels

So, now let's do something more difficult. Let's work with two pictures, in two different layers moving over each other without getting mixed up. And, let's do some alpha-channeling at the same time. (See Basics for more details). The picture I used before (image1.tga) has an alphachannel. Here is the code. I'll walk you through it again.

I'll skip the things I've mentioned before. So, let's look at some of the new parts:

        cout << "Creating LayerManager" << endl;
        CL_LayerManager *layerm = new CL_LayerManager( 2 );
        layerm->put_screen( image1, 0, 0, 0, 0 );
        layerm->put_screen( image2, 100, 100, 0, 1 );
    
As you can see, the CL_LayerManager is created with two layers. Nope, no fancy
    ::create
here. I believe the LayerManager is a bit of an ugly duck in the family, as it has no high priority. Nevertheless, it is pretty usefull as it is. Now, the
    put_screen()
function loads the image into the layer. The first parameter is the image, the second and third give the image an initial position in the layer. The fourth parameter is the index of the sprite which is to be used (in this case 0, the surface has only one picture). The last indicates the number of the layer. So, image1 is loaded on layer 0, and image2 is loaded on layer 1.
        layerm->show_layers();
        layerm->select_layer( 1 );
    
The
    show_layers()
well, erhm shows the layers :). it draws them on the backbuffer. Remember this, all drawing occurs onto the backbuffer, so if you want to actually show something you'll have to use
    CL_Display::flip_display()
.
The
    select_layer(<i>layer</i>)
selects a default layer. It was in this demo for a reason I forgot. It is here now, because I forgot to take it out :). It is useful if you do a lot with one particular frame.
          CL_Display::clear_display( 0, 0, 0, 1 );
    
This sets the display to the color specified by the first three arguments. The first specifies the red component, the second green, third blue. The fourth value is the alpha component to use. Remember, if it is 0 it pretty much does nothing, 1 is default. If you do not set it to 1, the display is not completely cleared because the original display is mixed with the specified color. I like black for a background color, and I don't want the images to leave a track behind. So, I'll fill in 0,0,0 for the color and 1 for the alpha-component. Note that I could have left the fourth digit away, as it is the default value.
          layerm->move_layer( layer_a, d, d );
          layerm->move_layer( layer_b, -d, -d );
    
This
    move_layer( <i>layer</i>,<i>delta_x</i>,<i>delta_y</i> )
shifts the surfaces in the specified layer with (delta_x,delta_y).
            layerm->swap_layers( layer_a, layer_b );
    
    swap_layers( <i>layer1</i>, <i>layer2</i> )
swaps the surfaces in layer1 and layer2. Nothing more, nothing less.

So, that's all. All the alpha-blending is done without you having to do anything.

Working with resources

Clanlib has a very powerful toy for resourcemanagement. A game often consist of many levels, graphics and sounds and to manage these the CL_ResourceManager is created. As explained in the previous chapter, you can create a datafile which contains all information your game needs. First I'll describe an example of the scripting language, then how to use the compiled datafile in your program.
Let's take the previous program as an example. I'll put the image we use in the datafile, as well as an integer indicating how many loops it should make.
Here is the scriptfile. You can compile this with
    datafile_compiler demo3.scr demo3.dat
. The first argument is the scriptfile, the second the datafile to output. So, let's look at the scriptfile:
    // the demo3 script file
    
    // location = datafile("demo3.dat");
    
Lines starting with
    //
or
    #
are considered comment. The ResourceManager has currently two ways of reading its data. Directly from the original files, or from the compiled datafile. The location line was used to specify which datafile to use if you omitted it in the constructor for the ResourceManager. This is obsolete now, so don't use it anymore.
    section Demo3
    {
            image1  = image1.tga    (type=surface);
            image2  = image1.tga    (type=surface);
            n_loops = 100           (type=integer, base=10);
    }
    
As you can see, a scriptfile is divided into sections. Sections can be nested. Inside a section you can specify fields. Each field has a name and a value assigned to it. The name is used to identify the resource. For example: to name the image1 one should use "Demo3/image1". For nested sections: "Demo3/nested_section1/nested_section2/name".
Most of the time, the value is a filename, but for strings and integers, this is the value you want the field to have. Between the brackets you can specify options. One important option is 'type' which indicates which type of resource this field is. If you ommit the type, ClanLib will try to figure out the type itself. It is recommended to specify the type because it will not always be right... You can also specify other options, depending on the type of resource. For example: the integer-resource has a 'base' option, specifying which base the number given is based on. With a surface-resource you can specify which section of the image to use, amongst other options.
Currently the following resources are supported:
  • integer
  • string
  • boolean
  • surface
  • palette
  • font
  • sample
  • raw
Now you have a datafile, but how do you use it in a game? Quite simpel. Let's look at an example. It's almost the same as the previous demo, but now it loads the picture from a resourcefile, and a integer named n_loops which should indicate how often the demo should loop.
Some of the more interesting changes:
        cout << "Loading resources" << endl;
        CL_ResourceManager *resources = new CL_ResourceManager( "demo3.dat", true );
    
        assert( resources!=NULL );
    
First, we need to create the resourcemanager. This is done pretty easy, just use a constructor. Here I just the most common constructor with the datafile as the first argument, and as a second argument a bool indicating if you want to read from a datafile or scriptfile. If you don't want to recompile the datafile each time you want to test it, you'll need to tell the ResourceManager that you want it to use the scriptfile. You could use the following constructor:
        CL_ResourceManager *resources = new CL_ResourceManager( "demo3.scr", false );
    
The first argument is now the scriptfile, the second indicates that the ResourceManager should use the original sources instead of the datafile.
        CL_Surface *image1 = CL_Res_Surface::load("Demo3/image1", *resources);
        CL_Surface *image2 = CL_Res_Surface::load("Demo3/image2", *resources);
    
To load a resource from the ResourceManager, use the
    ::load
function for the appropriate resource. In this case a CL_Res_Surface. The first argument is the name of the resource, the second the resourcemanager to use. It is as simple as that.
        int n_loops = CL_Res_Integer::load("Demo3/n_loops", *resources, -1 );
    
The two resources for constants (CL_Res_Integer, CL_Res_Boolean and CL_Res_String) can accept a third argument. This is the default value. If the specified name does not exist in the resourcefile, this value is used. Ofcourse, you can leave the third parameter away. The ResourceManager then asserts if the name does not exist. In the 0.3.x branch resources are loaded using their representative classes. For example:
    CL_Res_Surface
does no longer exist. Instead, use
    CL_Surface::load(<i>name</i>)
. The
    CL_Res_Boolean
,
    CL_Res_String
and
    CL_Res_Integer
still exist though. This inconsistency is something which we need to work on...

The other changes to the file are to implement n_loops and are not very interesting (or well coded for that matter ;P ) so I'll skip them.

Handling input

Here I'll discuss how to read input from the keyboard, mouse or joystick. In the previous examples I already used the keyboard interface so you could press the escape-key to quit the program. This is pretty basic use of the CL_Keyboard class.
    if( CL_Keyboard::get_keycode(CL_Keyboard::KEY_LEFT) )
    {
      // do something intelligent here
    }
    
The
    CL_Keyboard::get_keycode(<i>key</i>)
function returns true if the key is pressed, false if not. As simple as that. Similar you can read joysticks and the mouse:
       int x = CL_Mouse::get_x();
       bool pressed = CL_Mouse::left_pressed();
    

As I described in the previous chapter, ClanLib supports abstraction from these devices. Most games support configurable keys so an abstraction from the actual keys is wished. Let's look at an example from the ClanLib-examples module: input_devices.cpp.

    
    // Abstract game input from physical input:
    CL_InputButton_Group *fire_button = new CL_InputButton_Group;
    CL_InputAxis_Group *hori_axis = new CL_InputAxis_Group;
    CL_InputAxis_Group *vert_axis = new CL_InputAxis_Group;
     
    </pre>
Here we create abstract devices for inputhandling. First, a
    fire_button
is created. In the rest of the game, if we want to know if the player wants to fire, we'll use this object. As the name already suggests, the
    CL_InputButton_Group
can handle a bunch of keys, al with the same purpose.
The same way we create a horizontal axis, and a vertical axis (
    hori_axis
and
    vert_axis
).
Although mouse support is handled a different way, the mouse can also create a CL_Axis object. This will be like the mouse-aiming in games as Quake.
    <pre>
    
    // Add keyboard input:
    fire_button->add(
            CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_ESCAPE));
    
    fire_button->add(
            CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_SPACE));
    
    </pre>
Here, we hook up the actual keys to the
    fire_button
. For each key you want
    fire_key
to react to, just call the
    add( CL_Key )
. Now, for a keyboard, these
    CL_Key
's are easy to obtain. Just use the
    get_button( <i>keyname</i> )
function.
    hori_axis->add(
            new CL_InputButtonToAxis_Analog(
                    CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_LEFT),
                    CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_RIGHT)
                    ));
    
    vert_axis->add(
            new CL_InputButtonToAxis_Analog(
                    CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_UP),
                    CL_Input::keyboards[0]->get_button(CL_Keyboard::KEY_DOWN)
                    ));
    
    
Analogue, we create the axis. For an axis, we need two keys ofcourse.
    // Add joystick input (if available):
    if (CL_Input::joysticks[0] != NULL)
    {
            fire_button->add(CL_Input::joysticks[0]->get_button(0));
            fire_button->add(CL_Input::joysticks[0]->get_button(1));
    
            hori_axis->add(CL_Input::joysticks[0]->get_axis(0));
            vert_axis->add(CL_Input::joysticks[0]->get_axis(1));
    }
    
Now, let's check if any joysticks are detected. If
    CL_Input::joysticks[0]==NULL
then there aren't any joysticks. If there isn't a first, there isn't any... Ah well. It's simple :).
If you want to use a mouse like this, try the following code:
            hori_axis->add(CL_Input::pointers[0]->get_axis(0));
            veri_axis->add(CL_Input::pointers[0]->get_axis(1));
    
            CL_InputButton *l_key = CL_Input::pointers[0]->get_button(0);
            CL_InputButton *r_key = CL_Input::pointers[0]->get_button(1);
    
    <pre>
    while (fire_button->is_pressed() == false)
    {
    ...
    }
    </pre>
So, here we see how to check when one of the keys is pressed. Just use the
    is_pressed()
function.
    <pre>
    int x = CL_Display::get_width()/2 +
      (int) (hori_axis->get_pos()*CL_Display::get_width()/2);
    
    int y = CL_Display::get_height()/2 +
      (int) (vert_axis->get_pos()*CL_Display::get_height()/2);
    </pre>
Let's see how one can read an axis. The
    get_pos()
returns a float between 0 and 1. So, multiply this with the height or width of the field you're working in and you'll get the position.

Using network support

This stuff isn't tested because I haven't got time for it yet. It should work though because I ripped the examples from Magnus' network overview ;)
For network support, basically two classes are needed:
    CL_Network
, for finding and creating a game, and
    CL_NetGame
which represents an actual network game, and thus handles all data.
As I described in the
previous part, there are two ways of communicating data. First, I'll show how to set up a network game. Second, I'll describe how you can write and read to NetChannels manually. And as a third, I'll use the NetObject way. This is the easiest way because most things are done for you. (And as such, the tutorial will be shorter to write :P ).

Setting up a network game

For a network game we need a server and clients. First, the server opens a game on a certain port.
    CL_NetGame *netgame = CL_Network::create_game("MyGame", 5555);
    
The
    create_game( <i>name</i>, <i>port</i> ) 
does exactly this. The name is the game_id. Each game should use a different one so a Quakegame doesn't try to connect to ClanBomber. (Although that would be funny...)
Joining a game is just as easy. If you already know the ip or computername the game will be on, just use:
     
    CL_NetGame *netgame; 
    CL_Network::find_game_at("MyGame", "my.server.net", 5555);  
    if( CL_Network::peek_game_found() )
    	try 
    	{
      		netgame = CL_Network::receive_game_found(5000); 
    	}
    	catch (CL_Error err)
    	{
    		cout << "Join failed: " << err.message << endl;
    	}
    else
    	cout << "No games found at " << "my.server.net";
    
The network game I am going to create is
    netgame
. First we try to find a game with id
    MyGame
at a server called
    my.server.net
at portnumber
    5555
. If you don't know the servername than you can use:
      CL_Network::find_games_broadcast("MyGame", 5555);
    
Both functions setup ClanLib to do some networking. The
    CL_Network::peek_game_found()
returns true if any games are found. To actually get a CL_NetGame pointer, you need to call
    CL_Network::receive_game_found(<i>timeout</i>)
. This will get you the first game found on the specified server (or servers in the second case) or a NULL-pointer or exception if there weren't any games or some other error occured. If you (or the gamer) aren't satisfied with this one, just call
     receive_game_found(<i>timeout</i>)
again and it'll give you the next one. If you have seen all games available, and decided you actually wanted the first (*sigh*) than just call
    CL_Network::clear_games_found()
and you can start all over again.

Reading and writing to NetChannels

Data is transferred as a CL_(Out/In)putSource_Memory object. If you write or read to a NetChannel you must use this class. In it, you can store whatever you want, see the documentation of the CL_InputSource en CL_OutputSource classes how these work. (Or read the tutorial about these common classes when I come around to those). You probably want to build a function that checks if the netgame has any data for you. Remember that it should be called in time, or you'll get a queue of messages waiting for you, and your game will fall behind.
To find out if the server has any data waiting, use:
    if (netgame->peek(channel_nr)) 
    {
      ... // read the data from the netgame here
    }
    
Here,
    netgame
is the CL_NetGame pointer to the networkgame you joined. Remember, we are working on the client side. The
    channel_nr
is the number of the NetChannel you want to read from.
Now, actually read the data:
    CL_InputSource_Memory updates = netgame->receive(channel_nr);
    
As I said before, all data is written and read using CL_(In/Out)putSource_Memory. A brief example how to extract data from the CL_InputSource_Memory class:
    
    int n_monsters = updates.read_int32();
    for( int i=0; i<n_monsters; i++ )
      {
      monster[i].x = updates.read_int32();
      monster[i].y = updates.read_int32();
      }
    
Now, let's see how to write to a channel. You can send a message to the server, to a specific computer, or to a group of computers. I'll explain later how to create a group of computers.
First, we create a datablock to send:
    CL_OutputSource_Memory msg;
    msg.write_float32( myself.manapoints);
    msg.write_float32( myself.hitpoints );
    
And now, we send the data to the server:
    netgame->send( channel_nr, netgame->server, msg);
    
The first and the last argument should be clear. These are the NetChannel to which the message is sent, and the message itself. The second might need some explaining. ClanLib has an easy way of creating NetGroups, a group of computers (for example: in a team). The second argument is the group you wish to send to. In this case this is the server and we get the server's NetGroup using the pointer
    server
in the netgame object.

Using NetObjects

If you have a rather complicated game, you probably don't want each network-aware to keep track of the networktraffic. An object should not be aware when it's data is send or received. For this, ClanLib has created the CL_NetObject class. This class has two abstract functions (
    virtual void serialize_load(CL_InputSource *input)=0;
and
    virtual void serialize_save(CL_OutputSource *output)=0;
) which you have to inherit to create the data-packages. Tha's all you need for a network aware object. When the actual data is sent through the network is not decided by the object, but by the game (or perhaps a CL_NetObjectController). Another advantage is that there is no distinction if the object is controlled local or on another computer.
An example:
    class Monster: public CL_NetObject
    {
      private:
        int x,y,hp;
    
      public:
        virtual void serialize_load(CL_InputSource *input)
        {
          x = input->read_int32();      
          y = input->read_int32();      
          hp = input->read_int32();      
        }
        virtual void serialize_save(CL_OutputSource *output)
        {
          output->write_int32(x);      
          output->write_int32(y);      
          output->write_int32(hp);      
        }
    };
    
If you have very simple objects which has a constant amount of variables (like only coordinates and hitpoints) it is easier to use a derived class of CL_NetObject called CL_NetObject_Simple. This class has already inherited the serialize functions for you. Now you only have to indicate which variables you wish to be communicated and you're ready to go. This can be done in the constructor using the supplied add_xxx() functions.
    class Monster: public CL_NetObject_Simple
    {
      private:
        int x,y,hp;
    
      public:
        Monster() 
        {
          add_int32( &x );
          add_int32( &y );
          add_int32( &hp );
        }
    };
    
Now, when does the actual data get sent? The NetObjects won't know. They don't need to know. ClanLib supplies a CL_NetObjectController which does most of the work. To this class you can
    add()
a NetObject. The CL_NetObjectController automatically creates a mirror-NetObject on every client so each participating computer can see it. Furthermore, you only have to call the
    update(<i>game</i>,<i>channel_nr</i>)
and everything else is handled for you. Erhm... Some code here would be nice :) Problem is, I don't know yet how to get a list of all CL_NetObjects... Will find out soon, just be patient.



Questions or comments, write to the ClanLib mailing list.