Affichage des articles dont le libellé est X-Frontier. Afficher tous les articles
Affichage des articles dont le libellé est X-Frontier. Afficher tous les articles

vendredi 6 septembre 2013

Callbacks on C++ classes methods

My problem of the day : how to designate a NON STATIC method of any class as a callback (i.e a method triggered by any event), without using Boost and others craps ?

Fortunately I was able to draw inspiration from this page (http://www.partow.net/programming/templatecallback) that offers an interesting template.

Only one problem left: to instantiate the callback object the client must still designate in the template argument type / name the class hosting the method that we wishes to designate as a callback, wich is quite annoying...


Therefore, I propose the following mod, involving inheritance on a callback interface class (BaseCallback) :

template <typename ReturnType, typename Parameter>
class BaseCallback
{
public:

    virtual ReturnType operator()(Parameter parameter) = 0;
    virtual ReturnType execute(Parameter parameter) = 0;
};


template <class Class, typename ReturnType, typename Parameter>
class CallBack : public BaseCallback<ReturnType, Parameter>
{
public:

   typedef ReturnType (Class::*Method)(Parameter);

   CallBack(Class* class_instance, Method method)
   : class_instance_(class_instance),
     method_(method)
   {}

   virtual ReturnType operator()(Parameter parameter)
   {
      return (class_instance_->*method_)(parameter);
   }

   virtual ReturnType execute(Parameter parameter)
   {
      return operator()(parameter);
   }

private:

   Class* class_instance_;
   Method method_;
};


We have now a total decoupling between owner class callback method (client) and the calling class, it does not need to know the definition of the client class :-)


Here is a little example:

class Handler
{
protected:
    CallBack<Handler, void, const std::string&>* m_cb;

public:

    Handler( void )
    {
        m_cb = new CallBack<Handler, void, const std::string&>( this, &Handler::Func );
    }


    void Func( const std::string& a )
    {
        printf( "It works : %s\n", a.c_str() );
    }

    BaseCallback<void, const std::string&>* GetCallback( void )
    {
        return m_cb;
    }

};


class EvtSource
{
protected:

    BaseCallback<void, const std::string&>* m_handler;

public:
    
    
    void RegisterHandler( BaseCallback<void, const std::string&>* p_handler )
    {
        m_handler = p_handler;
    }
    
    void DoSomething( void )
    {
        (*m_handler)( "test01" );
    }
};


int main(int argc, char *argv[])
{
    Handler e;
    
    EvtSource foo;
    foo.RegisterHandler( e.GetCallback() );

    foo.DoSomething();
}

Enjoy ! ;-)

jeudi 6 juin 2013

C++ plugin framework

In this post I'll expose a little C++ framework to manage a plugin loading system. I wrote this one some years ago for one of my IRL job projects, and now I'm using it in my 3D engine.

1/ Defining the plugin interface


plugin.h :

     class IRenderingPlugin
   {
       virtual long Init( HWND* p_hwnd ) = 0;  // init graphic engine and pass the window handle
    

       virtual void Release( void ) = 0;      // release graphic engine (unallocate all resources, ...)

       virtual void Draw2DSprite( int posx, int posy, char* image ) = 0; // draw something in 2D ...
   };


2/ Plugin side : creating an openGL plugin

the plugin specific code implement the previously defined interface:

OpenGLPlugin.h :

    #include "plugin.h"

    class OpenGLRenderingPlugin : public IRenderingPlugin
    {
       long Init( HWND* p_hwnd );
       void Release( void );

       void Draw2DSprite( int posx, int posy, char* image );
    }


OpenGLPlugin.cpp :

      #include "OpenGLPlugin.h"

      long Init( HWND* p_hwnd )
      {
            // put here OpenGL init stuff code

            return 0; // everything is OK
      }

      void Release( void )
      {
            // put here OpenGL stopping stuff code
      }


      void Draw2DSprite( int posx, int posy, char* image )
      {
            // put here specific openGL code to draw a 2D sprite on screen
      }
The final step to create our lib plugin is to export a simple function that instanciate our specific interface implementation and return a pointer on that:

on linux platform:

      #include "OpenGLPlugin.h"

      extern "C"
      {
      IRenderingPlugin* PIFactory( void )
      {
            return new OpenGLRenderingPlugin;
      }
      }

on windows platform:

       #include "OpenGLPlugin.h"

      extern "C"
      {
      __declspec(dllexport) IRenderingPlugin* PIFactory( void )
      {
            return new OpenGLRenderingPlugin;
      }
      }


If you work under MSVC, the "extern "C"" statement disable microsoft specific functions names decoration, making your DLL plugin compliant even for binaries generated with other compilers than MSVC.

On Windows, While opening your DLL binary with the tool 'Dependency walker' you can see that your plugin export only one function : PIFactory()



3/ Main program side : the plugin manager, heart of the system

The plugin manager provides method to load a plugin (LoadPlugin()), and a method to find and execute the DLL exported C function "PIFactory()" (Instanciate()). 


The LoadPlugin() method call specific API functions to load a dynamic library (.so on linux, .dll on win32) : dlopen() for linux, LoadLibraryA for windows. The Instanciate() method locate and execute the PIFactory() method exported by our plugin binary to instanciate the plugin interface specific implementation...To locate an exported function, on windows we use GetProcAddress(); on Linux we use dlsym().



Notice that the plugin manager is a template, because we don't want it to be linked with a specific interface definition. Finally, notice that this is implemented as a singleton (no need for multiple instances of plugin manager, only one is enough).


The following code is compliant for both windows and linux platforms.


pimanager.h :

      #ifndef _PIMANAGER_H_
      #define _PIMANAGER_H_


      #ifdef WIN32
      #include <windows.h>
      #else
      #include <dlfcn.h>
      #endif

      #include <string>
      #include <map>

      typedef enum
      {
        PIM_OK,
        PIM_OK_PIALREADYLOADED,
        PIM_FAIL_PILOADING,
        PIM_FAIL_PIUNLOADING,
        PIM_FAIL_UNKNOWN,
        PIM_FAIL_FACTORYFUNCNOTFOUND,
      } PluginManagerStatus;

      #define PIFACTORYSYMBOLNAME "PIFactory"

      template <typename base>
      class CPlugInManager
      {
      public:

      #ifdef WIN32
        typedef HMODULE Handle;
      #else
        typedef void*   Handle;
      #endif


      private:

        typedef struct
        {
          Handle        handle;
          std::string   path;
          long          refcount;
        } PluginInfos;

        typedef base* (* Factory)( void );

        typedef std::map<std::string, PluginInfos> LibList;

        CPlugInManager( void )  { };
        ~CPlugInManager( void ) { };

        static LibList* get_lib_list()
        {
          static LibList m_libs;
          return &m_libs;
        }

      public:
        static PluginManagerStatus LoadPlugin( const char* p_path, Handle& p_handle );
        static PluginManagerStatus UnloadPlugin( const char* p_path );
        static PluginManagerStatus Instanciate( Handle p_handle, base** p_inst );
      };

      #include "PIManager_impl.h"

      #endif

PIManager_impl.h:

      template <typename base>
      PluginManagerStatus CPlugInManager<base>::LoadPlugin( const char* p_path, Handle& p_handle )
      {

        typename LibList::iterator it = get_lib_list()->find( p_path );
        if( it == get_lib_list()->end() )
        {
      #ifdef WIN32
          HMODULE hMod = LoadLibraryA( p_path );
      #else
          void* hMod = dlopen( p_path, RTLD_LAZY );
      #endif
          if( hMod == NULL )
          {
            return PIM_FAIL_PILOADING;
          }
          else
          {
            PluginInfos pii;
            pii.refcount = 1;
            pii.handle = hMod;
            pii.path   = p_path;
            LibList* ll = get_lib_list();
            (*ll)[p_path] = pii;
            p_handle   = hMod;
            return PIM_OK;
          }
        }
        else
        {
          // plugin already loaded

          p_handle = it->second.handle;
          it->second.refcount++;

          return PIM_OK_PIALREADYLOADED;
        }

       
        return PIM_OK;
      }

      template <typename base>
      PluginManagerStatus CPlugInManager<base>::UnloadPlugin( const char* p_path )
      {

          typename LibList::iterator it = get_lib_list()->find( p_path );
          if( it == get_lib_list()->end() )
          {
            return PIM_FAIL_UNKNOWN;
          }

          else
          {
            it->second.refcount--;       
            if( it->second.refcount == 0 ) // si plus aucuns hub ne fait reference a ce plugin
            {
                PluginInfos pii = it->second;
                get_lib_list()->erase( it );
      #ifdef WIN32
                FreeLibrary( pii.handle );
      #else
                dlclose( pii.handle );
      #endif
            }
          }
            return PIM_OK;
      }

      template <typename base>
      PluginManagerStatus CPlugInManager<base>::Instanciate( Handle p_handle, base** p_inst )
      {
       
      #ifdef WIN32
        FARPROC proc = GetProcAddress( p_handle, PIFACTORYSYMBOLNAME );
      #else
        Factory proc = (Factory)dlsym( p_handle, PIFACTORYSYMBOLNAME );
      #endif

        if( proc == NULL )
        {
          return PIM_FAIL_FACTORYFUNCNOTFOUND;
        }
        else
        {
          Factory factory = (Factory)proc;
          base* inst = (*factory)();
          *p_inst = inst;
          return PIM_OK;
        }
       
        return PIM_OK;
      }

4/ How to use the plugin manager in your main program

To load a plugin and retrieve a pointer to the implemented interface proceed like that :

     // plugin handle declaration
      CPlugInManager<IRenderingPlugin>::Handle pihandle;

      // interface pointer
      IRenderingPlugin* renderer;

      PluginManagerStatus pistatus = CPlugInManager<IRenderingPlugin>::LoadPlugin( "openglpi.dll", pihandle );
      if( pistatus != PIM_OK )
      {
            // something went wrong : cannot find the file, file existe but cannot find the exported func,
            return IMFALSE;
      }

      // now we can instanciate the plugin specific interface implementation:
      if( CPlugInManager<IRenderingPlugin>::Instanciate( pihandle, &renderer ) != PIM_OK )
      {
            return IMFALSE;
      }


After this init phase, you can now call your plugin functions and do the work !

      renderer->Init( wnd ); // graphic middleware init (openGL here)

In your rendering loop (window repaint) :

      renderer->Draw2DSprite( 60, 100, sprite_img );


Enjoy ! ;)

samedi 5 janvier 2013

Foggy clouds

Today I made a small modification in the volumetric clouds shader, by adding a fog effect; here are some screens comparing clouds rendering with and without fog effect:



Without fog effect : 



With fog effect : 





This tiny fog effect on clouds should also be useful for giant gas atmosphere rendering, but we'll see that point later ;)


vendredi 28 décembre 2012

dimanche 16 décembre 2012

vendredi 14 décembre 2012

Planet renderer artifacts corrections


I Recently made 2 bugfixes concerning planets renderings artifacts:

On earth-like planets, sometimes appeared unrealistics (unnatural) linear edges between desertic textures and temperate climate zone (green texture)





The reason for that : the desertic zones repartition on the equator is controled with a fractal function, and there was a break in the fractal result continuity all over the sphere due to non taking account of the orientation of each of the 6 curved cubes faces (the unrealistic linear edge was positionned on the limit between two curved cube faces indeed). Now fixed (and that's cool).

The other bug was (again) a z-buffering conflict resulting in very eye-unpleasant artifact over coast land.





The problem was that, the ocean model meshe grid is not interrupted under the land meshe, and as coast land gradually come down to the sea level, some land meshe triangles are very near to some ocean meshe triangles, which result in zbuffer imprecision artifact







Fix of the problem is done with a small modification the planet shader; the trick is to clip all ocean meshe pixel located UNDER land meshe. Each land meshe vertex altitud is provided to the shader through an unused texture coordinate register

if( ocean_role )
{
    // input.TexCoord2.x -> altitude du terrain

    // ne pas dessiner le pixel quand l'altitude du terrain est au dessus de l'ocean ( > 0 en fait)
    // (rappel : clip quand argument negatif)

    clip( - input.TexCoord2.x );
}






And then, it works ! And that's pretty, pretty cool :)





And, to finish, a little view of clouds over some islands (just for the fun ;) ).




jeudi 6 décembre 2012

Internal architecture redesign (hopefully the last !!)


In the early versions of my generic 3D engine "IMotion", this one was provided as a classic lib, with some headers and binary libs; this implies that each time I wanted to start a new test program or project based on it, it was mandatory to spend time creating the main program, with all those boring steps like creating the main window, calling renderer initalization routines, writing callback for input events from mouse, keyboards, blah blah blah... So I decided to join to my 3D lib release something that I called "framework classes"; the aim of those classes is to:
  • replace and manage the program entry point (winmain()) to make all required initialisations steps, included full-screen or windowed app.
  • provide a ready-to-use base class with all necessaries callbacks for various events hooks, like app startup, input from keyboard and mouse, closing app event... finally this class called 'cIMApp' must be inherited to implement all the app-specifics data and behaviours. Usually, I give the name 'IMAppClient' to this app-specific class 

The problem was the following: as I gradually added features to the X-Frontier prototype, all those features were managed in the custom 'cIMAppClient' class, so this one was growing and growing again, until the point that this was too swollen to continue like that, indeed cIMAppClient class was responsible of quite all and everything in the game, like :
  • game data load and init
  • player input management (keyboard, mouse)
  • 2D GUI object rendering and management
  • scenegraph rendering and management
  • game modes and states machines
  • galactic map data provider (locations of systems and planets in the galaxy, under the following form : [sector, position])
  • and more others things that I won't detail here...

I realized that it should be better to split this monolithic class in a few small and specialized services. So here is the list of the pool of 'services classes' present in the heart of the game now:

  1. GameCore service:  This service is reponsible for data loading and initialization at startup phase, game logics, game modes managements, states machines, view and camera management, scenegraph management and rendering, and so on ... This is the game nodal point, so unfortunately it's intended to became quite complex again in the future; Maybe this one should be splitted again, wait and see... Of course, because of its central position in the architecture, GameCore leans on all other services.
  2. PlanetarySystem service: This one is the galactic map data provider. This means that it take as input a sector coordinate, and it provides as output this list and description of stars, planets, station and other object located in this sector. So, the randomly-created systems and also the handly-created systems (modding) will be hosted by this service. In the future releases of X-Frontier, when the graphic galactic map will be implemented in the game, this one will strongly lean on the PlanetarySystem service...
  3. GUI service: the purpose of this service is to manage all GUI 2D objects of the game : dialog, menus, and so on...
  4. IMAppclient:This class is now the interface between OS (Windows) events and the GameCore.
  5. MODAPI: MODing API : modding entry point of the game, with a set of method (interface) to mod the game : adding systems, stars, planets, vessels models, space stations... Mainly used by the lua stack.
  6. Game events : Managing high-levels game events; mmmh this one seems to be very near to gamecore in facts. Should I merge those 2 ?
  7. Console: In-game console management : the input strings are directly transmitted to the lua stack.
  8. Lua stack: binding between lua interpreter and MODAPI calls.
Finally, better than thousands and thousands words, here is a little draw showing the new enhanced X-frontier architecture:








samedi 20 octobre 2012

vendredi 5 octobre 2012

Lost week

Last sunday my dev laptop PC crashed; I have some recovery DVD, but I loose 1 day or 2 searching for them; more than that, they dont work very well, so it needed a lot of attempts to achieve Windows installation; after that, I spent some times reinstalling all my dev softwares : MSVC, AC3D, svn Tortoise, Downloading and installing DirectX SDK, etc... Finally it took me 5 evenings to get back to the point where I was stopped last sunday. I am now ready to continue XFrontier developpment, but in brief I loose the week.

vendredi 7 septembre 2012

XFrontier progress : Dialog popups, game events, flight dynamic model and much more...


I'm very close now to achieve the 1st X-frontier prototype (PROTO1.ALPHA); however, let's make a little point of what was achieved (or started) those last weeks.


  • Dialogs boxes : jpeg format SUCKS for color keying


During holidays I added Dialog boxes display and interaction to the 2D manager interface. The dialog box frame is defined as a 2D texture, so it's stored in a .bmp or .jpg file. An inportant point to my eyes was that I wanted arbitrary 2D clipping for the dialog frame, rather than strictly rectangular. To do it, I added color keying technique in the 2D rendering shader, and let's define pure green (0,255,0) as the color key. I designed the 2D dialog box texture as following :








As I tested it for the first time, the dialog box rendering was quite wrong : the green colored-parts, supposed not to be displayed, were rendered except for some random pixels, as you can see in the following screenshot... WTF ?



I spent quite an hour trying to fix that problem. Finally, I founded the explanation (while seated on the beach) : The pixels supposed to be 'pure green' were not really at (0,255,0) value because I stored the dialog frame texture in a ... jpeg file. Most of the pure green pixels for color keying were degraded due to the destructive jpeg compression. Once texture stored in a bmp file, everything worked fine:




Much better like that, hey ?

  • Game start menu
I added Lua function to create what I call an 'entry point' in the game. An entry point is a place (typically, a pilot seat in the cockpit) in an instance of ship class, located somewhere in the universe. To define an entry point in the game, a modder must :

- Declare a new vessel classes; for example :

create_vessel_class( "cargo", "cargo.grb", "cargo.hie" )

The previous lua code line create the "cargo" class. The 1st argument is the name a modder wants to give to the vessel class. Modders will need to give this name for further function that offers modification on the vessel class.
The 2nd argument give the name of the "GRB" file (graphic resources base) for the cargo (containing meshes, textures, shaders and rendering effects). The 3rd argument give the name of the "hierarchy" file, wich describes how the different components of the .grb file (engines, main body of the vessel, cockpit,...) are hierarchized.

- Declare where in the ship class is located the player point of view; for example

add_vesselclass_playerzone( "cargo", "cockpit_pilot_seat", 0.0, 8.1, -17.10, "Body", 1 )

The previous lua code snippet create a zone in the "cargo" class. A zone is a physical place in the ship where the player point of view is located : for example, cockpits, passengers cabins, corridor... There will be 2 zones categories : "static", and "non-static". "Static" category is a zone where the player cannot walk, the only enabled movment for the point of view is moving the head (typically, the pilot's seat). "Non-static" category is a zone where the player can evolve as in a classic FPS game : moving the head, and walking around (typically cabins, corridors, the whole cockpit). In the previous lua example we declare a static zone in the cockpit, over the pilot's seat. 

The 1st argument is the vessel class name a modder previously created and where he wants to add a "zone".

The 2nd argument is the zone name; modders should give this name for further function that allow zone interconnections in the vessel class. The arguments 3,4 and 5 defines X,Y,Z position of the static zone point of view in the vessel 3D meshe. The argument 6 is the name of the meshe where the previous X,Y,Z position is relative. This name must correspond to an existing entry in the hierarchy file. The argument 7 declare the zone category : 1 for static, 0 for non-static. The non static zone are not currently implemented.


- Now it's time to instantiate a vessel from the previously defined class. Let's call it 'Nostromo' :)

register_vessel_from_class( "Nostromo", "cargo", -22000.0, 0.0, 65050.5, 0, 0, 0 )

The 6 last arguments are the vessel instance start location in the universe : galactic sector (0, 0, 0), position (in kilometers) from the center of this sector: -22000.0, 0.0, 65050.5.

- Now we have a vessel located somewhere in the galaxy, let's say we want a menu entry to start the game on the Nostromo's pilot seat:

add_game_entrypoint( "Nostromo", "cockpit", "Nostromo, in the Sirius system" )

The 1st argument is the vessel instance name. The 2nd argument is the zone on the vessel instance where the player point of view must be positionned. The 3rd argument is the label to display of the corresponding menu entry.

Once the game started, the start menu appears like this:

  • Collision boxes type selection from Lua
For Collision detection I use ODE capabilities. ODE allow different collision shapes on objects :

- SolidSphere
- SolidBox
- SolidCylinder
- SolidMeshe


The 'SolidMeshe' has the highest accuracy in collision detection, but it's also the one with the highest CPU cost. In early dev version of the XFrontier prototype, only this last one was available for vessel and stations. Last week I added the possibility to choose (via Lua commands) SolidSphere or SolidBox instead; here is the Lua code example :

                 -- declare cargo vessel class
create_vessel_class( "cargo", "cargo.grb", "cargo.hie" )        
                -- bounding sphere for "Body" object meshe
set_vesselclass_collision( "cargo", "Body", "sphere" )           

                -- bounding box for "Engine1" object meshe
set_vesselclass_collision( "cargo", "Engine1", "box" )         

                 -- bounding box for "Engine2" object meshe
set_vesselclass_collision( "cargo", "Engine2", "box" )           

                -- bounding box for "Engine3" object meshe
set_vesselclass_collision( "cargo", "Engine3", "box" )  


  • Game events manager

I started to implement management of what I called "High-level Game events"; In XFrontier, the only 'moving' objects (at least in the earlier version)  should be the vessels. So the main high-level game events will be :

- a vessel colliding another vessel
- a vessel accosting a station
- a vessel colliding a station
- a vessel colliding a planet ground
- a vessel landing on a planet ground
- a vessel near a gas giant or a star (!!!!)

I want a callback system triggering a function in the game core for each of those events, in the aim to launch appriopriate actions; for example, when a vessel collide a station, taking into account velocities and directions at the collision instant, the core game can put the incriminated vessel in one of those states:

- only giving some minor/major failures in vessel's equipements and/or giving this one a quite incontrolable trajectory/rotation.
- Vessel explosion/destruction (and game over if it's the player's vessel)



So, it seems that there is three main event type :

EVT_APPROACH : the vessel is quite near another object
EVT_ACCOST   : the vessel landed on planet ground or is connected to station airlock
EVT_COLLIDE  : collision with another object
             
Here is a sheet giving some examples of consequences/reaction of game core for each case of event:




Maybe later, in practice it will appears that I need more events type, or maybe I'm totally wrong, who can say ? Wait and see. But I feel there's a lot of advantages in such architecture : making code more clean and easy to modify, and in the modding aspect, mission creation through Lua scripting should be more easy with those high-level game events.


  • Flight dynamic model for space ships

Flight of behaviour of vessels in planet atmosphere should be quite realistic, but this can be hard to implement. After some research on the web I found JSBSim, an open source dynamic flight model, written in C++; this one is used by the open source flight simulator FlightGear. I'm currently reading the documentation (excellent), so for the moment I can't tell yet if this one could be integrated in XFrontier, but I hope so... Anyway, this will not be in the XFrontier PROTO1.ALPHA release, because I want to release this last one as soon as possible, so player vessel flight behaviour will be (for the moment) a very basic and unrealistic flight model.



mercredi 6 juin 2012

3D modelisation for X-Frontier


After some holidays, back to bizness ;) 


 For X-Frontier I need some models of stations and space ships. 3D modeling is a task I dont like very much, I'm not very good in it, so I dont want to spend a lot of time to learn how to use complex 3D modelisation software like Blender or GMax (a free version of 3DS Max). I need SIMPLES and efficients tools.


 In 2003 I discovered a small and simple 3D modeler called AC3D. 30 minutes only are necessary to learn how to use it !!
 One other interesting feature of the software is the texture mapping tool, quite intuitive and easy to use ! And finally, AC3D allow to save model on disk through a human readable text file format; I writed a parser for the AC3D files in my homegrown 3D engine to import all 3D models created with this software.


 In the other hand, the main inconvenience is, while the 2003 version (3.6) is a simple modeler, you cannot create very complex objects !


 Recently I choose to use Google Sketchup to create complex 3D objects. The problem is that google sketchup only allow object export in the collada format (an xml format for 3D meshes), quite complexe to parse, and as I didnt want to spent time to write a new parser for my 3D engine, I started researches for a tool that allow conversion from collada format to a file format compliant with my old AC3D version (3.6). 


 I visited the AC3D web site (http://www.inivis.com) and I noticed that the last version (6.8.14) was compliant with the collada format.
 Furthermore, 6.8.14 version bring some interesting improvements, like boolean operations, extrusion, enhanced texture mapping, triangle selection directly in the 3D view, and more !!! 


 So I finaly decided to buy the license (this is not a free software !) for the 6.8.14 AC3D version ! (around 120 $)


 3D models production chain for X-Frontier is the following :



  • Starting the rough complex meshe under Sketchup. Exporting in the collada format
  • Importing the collada format under AC3D.
  • With AC3D : adjusting the model (moving/correcting some vertex/face, adding details), and setting texture mapping coordinates.
  • Saving the model in the AC3D file format.
  • Importing the AC3D file format in my 3D engine framework, converting the model to my 3D engine data format.




 Some models yet created:




       Space city :












       Space station (texture mapping not finished !) :











       Ship : a small commercial cargo (work in progress)