• Which the release of FS2020 we see an explosition of activity on the forun and of course we are very happy to see this. But having all questions about FS2020 in one forum becomes a bit messy. So therefore we would like to ask you all to use the following guidelines when posting your questions:

    • Tag FS2020 specific questions with the MSFS2020 tag.
    • Questions about making 3D assets can be posted in the 3D asset design forum. Either post them in the subforum of the modelling tool you use or in the general forum if they are general.
    • Questions about aircraft design can be posted in the Aircraft design forum
    • Questions about airport design can be posted in the FS2020 airport design forum. Once airport development tools have been updated for FS2020 you can post tool speciifc questions in the subforums of those tools as well of course.
    • Questions about terrain design can be posted in the FS2020 terrain design forum.
    • Questions about SimConnect can be posted in the SimConnect forum.

    Any other question that is not specific to an aspect of development or tool can be posted in the General chat forum.

    By following these guidelines we make sure that the forums remain easy to read for everybody and also that the right people can find your post to answer it.

C++ Tutorial - CFSVar: a class to access simulation variables

Messages
240
Country
switzerland
Here's a link to a sample gauge project I've made, to demonstrate some C++ OOP techniques. I hope to keep this project updated, to show more stuff in the future.

It's derived from the MS ESP GDI+ Sample (which was derived from my F/A-18 code, which was derived from the Cloud9 MB339 and F4...), but I tried to make it more similar to the original idea, and more Object-oriented.

http://www.mediafire.com/download/zidu446ar6l2awz/GDI+Gauge.zip

It's a VC++ 2013 Project, don't know if it can be opened with other versions, but should work with the free VC++ 2013 Express.

When you see the shared files on Mediafire, click the GREEN arrow on the top-right of the screen that says "Download Folder", so you will download the whole project.

There's a "Post-build" event in the Project settings, that copies the compiled gauge from its target folder (which will be named either "Debug" or "Release") into "C:\FSX\Gauges". Replace this step with your actual FSX folder, if you want to have the gauge .DLL to be automatically moved into FSX when it's done compiling.

The gauge includes both Gauges.h, Simconnect.h and Simconnect.lib in its root folder, so it *should* be ready to compile without much fiddling.
 
Last edited:
The main goal for this sample, is to demonstrate some OOP methods:

  • The CFSVar and CFSMultipleVar classes, that are used to access Simulation variables WITHOUT using Simconnect, but only through the Panels.dll interface.
  • The usage of the Singleton pattern to describe a "CSimulation" global object, that is supposed to be visible from anywhere in the project. It's basically a "box of globals".
  • The usage of Simconnect to JUST subscribe to system events (every frame, 6 times per second, once per second, etc.) and manage variable updates
  • The communication between the Simulation and the actual gauges, through a pointer to the CSimulation Singleton, so that gauges can access variables without talking directly to FSX, in order to separate the simulation update from the actual drawing based on the variable values.

Let's start a Top-down approach: in the CSimulation.h file, there's an interesting OOP concept, the "Singleton pattern":

Code:
class CSimulation : public CSingleton<CSimulation>
{
    friend class CSingleton<CSimulation>;
public:
    void Start(void) { mStarted = true; };
    void Stop(void) { mStarted = false; };
    const bool IsStarted(void) { return mStarted; };

    void Update6hz(void);
    void Update1Sec(void);
    void Update4Sec(void);
    void UpdateFrame(void);

    CFSVar<SIMVAR_PLANE_ALTITUDE, Units::feet> PlaneAltitude;
    CFSVar<SIMVAR_PLANE_LATITUDE, Units::degree_latitude> PlaneLatitude;
    CFSVar<SIMVAR_PLANE_LONGITUDE, Units::degree_longitude> PlaneLongitude;
    CMultipleVar<SIMVAR_GENERAL_ENG_THROTTLE_LEVER_POSITION, Units::percent, 1, 70> Throttle;
    CFSVarAngle<SIMVAR_PLANE_HEADING_DEGREES_MAGNETIC, Units::degree> Heading;

private:
    CSimulation()
        : mStarted(false)
    {};

    ~CSimulation()
    {};

    bool mStarted;
};

You will find the implementation of the Singleton in the Singleton.h file. It's short, but it's a bit of C++ black magic, yet very clever. The basic idea of the Singleton pattern, is to have a container of globals. We all know that globals are usually bad but, from our point of view (we are a lowly gauge in the grand scheme of things), the simulation variables ARE like a big list of global values. And, more important, it's fairly sure there's just ONE of such list. The Singleton pattern is the perfect tool for this: a box of globals that we can control, and that we can be absolutely sure we there will be only one copy of it in the program. The Singleton pattern achieve this with some OOP wizardry, by making its constructor private, the only thing visible to the outside will be the Instance() member function, that will act like the constructor, returning us either with the object (if no object was made) or with the pointer to the object it already created, if we try to declare a new instance of it. Well, it's OOP wizardry, just assume it works...

Here, we declare our CSimulation class to be derived from the Singleton class:

Code:
class CSimulation : public CSingleton<CSimulation>

The <CSimulation> is a template another cornerstone of OOP programming, and is needed because the Singleton is a generic pattern, I could use it to make singletons out of every class I declare, so I must tell the compiler (remember, this is all code generated at compile time) which "kind" of Singleton this will be, CSimulation in this case, our container of globals.

Code:
friend class CSingleton<CSimulation>;

Remember that I've said the Singleton will make its constructor private, so I can't access it anymore from the outside ? Well, here I AM CHEATING, just a little bit.

By making a class a friend of another class, I'm giving explicit permission to that class to access the private member of the class it derives from. Why ? Because I will later override the default constructor that comes with the Singleton, with my own version that initialize an additional member. With this technique, I took a "generic" class that I had ( the Singleton.h file ) and I customized it a bit for my own needs, without having to rewrite it. Of course, the friend keyword should be used with care, not to be abused.

Code:
public:
    void Start(void) { mStarted = true; };
    void Stop(void) { mStarted = false; };
    const bool IsStarted(void) { return mStarted; };

These lines declare some utility function that we might need in the future. This sample will not use them, but I'll demonstrate their utility on other tutorials. You might have some things that will need to be executed only after the simulation has entirely started (FSX is loaded and the simulation is running), and these functions are helpers for that. Let's skip them for now.

Code:
void Update6hz(void);
void Update1Sec(void);
void Update4Sec(void);
void UpdateFrame(void);

Here we declare some important functions: different UpdatesXXX, to be called at different time intervals. The basic ideas here are:

  • You NEVER, ever, read from FSX directly from your sub-gauges, the ones that "draw stuff". The sub-gauges should only talk with this "CSimulation" object, and get their data from here.
  • Divide the variable readouts by update frequency. Do you need to read the time of the day every "$£%!"$&-ing frame ??? Surely not. Depending on the kind of variable, there are different update frequencies that are needed. This way, we CENTRALIZE this strategy and make it easy to understand and modify, without touching your gauges.
Code:
CFSVar<SIMVAR_PLANE_ALTITUDE, Units::feet> PlaneAltitude;
CFSVar<SIMVAR_PLANE_LATITUDE, Units::degree_latitude> PlaneLatitude;
CFSVar<SIMVAR_PLANE_LONGITUDE, Units::degree_longitude> PlaneLongitude;
CMultipleVar<SIMVAR_GENERAL_ENG_THROTTLE_LEVER_POSITION, Units::percent, 1, 70> Throttle;
CFSVarAngle<SIMVAR_PLANE_HEADING_DEGREES_MAGNETIC, Units::degree> Heading;

NOW the fun begins! These are the actual variable declarations inside the CSimulation object (don't forget, we are are STILL in the declaration phase here, our gauge code is still loading and objects are still being created at this stage). They are, of course, using templates, which looks a bit magic, but we might explain them in better detail when we go a bit more low-level. For now on, a very brief description:

Code:
CFSVar<SIMVAR_PLANE_ALTITUDE, Units::feet> PlaneAltitude;

This declares the PlaneAltitude member variable, to be of the CFSVar type, but customized ( using the template ), to be initialized with the token of the "PLANE ALTITUDE" variable, using the Units::feet unit of measure. Units:: is used because those units of measure are declared inside a namespace, in order to eliminate the risk of those names conflicting with same names that might be elsewhere in your code. I won't comment the other two for PlaneLatitude and PlaneLongitude, because they are very obvious, the next one is different:

Code:
CMultipleVar<SIMVAR_GENERAL_ENG_THROTTLE_LEVER_POSITION, Units::percent, 1, 70> Throttle;

This CMultipleVar is a more high-level variation of the base CFSVar class, which is used for everything that is "multi", the engines in this case. This sample was for the C172, so it's just 1 engine ( the 1 parameter ), but I could declare it for a 4-engine airplane but putting a 4. The difference is that, a CFSVar variable will be read from FSX like this:

Code:
PlaneAltitude.Update();
PlaneLatitude.Update();
PlaneLongitude.Update();

but a CMultipleVar will be read like this:

Code:
Throttle.Update( 1 ) // engine 1
Throttle.Update( 2 ) // engine 2
Throttle.Update( 3 ) // engine 3
Throttle.Update( 4 ) // engine 4

or, maybe, like this:

Code:
for( int i = 1; i <= 4; ++i )
  Throttle.Update( i );


Now, let's see how this starts and interacts with FSX, by checking the GaugeDeclarations.cpp file, I'll post only the interesting parts here:

Code:
CSimulation* Sim = NULL;

Towards the start of the file, we declare Sim to be a global pointer to the CSimulation class. This is the "remote control" of our simulation. It's a pointer to a class so, it does behave within all its constraints, first and foremost the ones imposed by the Singleton pattern. If I tried to outsmart it, and declared another object of the same kind, doing something like CSimulation* AnotherSim = NULL; I would only have created *another* "remote" to the SAME object, not two big simulations running in parallel. That's why we used the Singleton...

The bulk of the code are more or less standard Gauge SDK declarations, the interesting part comes here:

Code:
void FSAPI module_init(void)
{
    // Initialize the Singleton class that holds the Sim data
    Sim = CSimulation::Instance();

    // Init units of measure
    Units::InitUnitsOfMeasure();

    hr = SimConnect_Open(&hSimConnect, "GDI+Sample Gauge", NULL, 0, 0, 0);

    if (hr == S_OK)
        hr = SimConnect_CallDispatch(hSimConnect, SampleGauge_DispatchProcDLL, NULL);
}

Here, in the module_init() function, which is executed ONLY ONCE, and ONLY when the airplane that contains the Gauge is loaded (regardless if the panel is open or not or if the flight was saved in the outside view). As long as the panel.cfg contains a reference to that Gauge .DLL/.GAU file, the module_init() WILL be called, once and not more than once. That's why it's a perfect place to initialize our objects:

Code:
    Sim = CSimulation::Instance();

Here, the Sim pointer (our global "remote") is initialized with the only function our Singleton allows to see, the Instance(). This is the trick that makes the Singleton work, no need to by more specific for the time being.

Code:
    Units::InitUnitsOfMeasure();

Here, we initialize all our units of measure, by calling for each one the FSX function that links the *name* of the unit of measure, to its enum index. Our Units::namespace will now fill its internal array with all the correct values, taken from FSX using the get_units_enum() function from the Gauges SDK, so we can retrieve them when needed, without a costly text-based lookup, which would have happened if we used the get_units_enum to translate the name of the unit of measure, to its enum index each time we need to read a variable. This is happening in the module_init(), so it's happening only once, who cares if the airplane takes a couple milliseconds more to load, but you don't want to lose *any* milliseconds while you are inside your gauge loop!

Code:
void FSAPI module_deinit(void)
{
    hr = SimConnect_Close(hSimConnect);
    Sim->DestroyInstance();
};

This is very straightforward, in the module_deinit() function, we close Simconnect and we destroy the instance of the CSimulation Singleton. Well, maybe I should have put a Sim = 0; line in the end, since it's good practice zeroing a pointer after you destroy the object it was pointing to!

Next, we have the Simconnect Callback procedure:

Code:
void CALLBACK SampleGauge_DispatchProcDLL(SIMCONNECT_RECV* pData, DWORD cbData, void *pContext)
{
    switch( pData->dwID )
    {
        case SIMCONNECT_RECV_ID_EVENT_FRAME:
        {
            SIMCONNECT_RECV_EVENT_FRAME *evt = (SIMCONNECT_RECV_EVENT_FRAME*)pData;
            switch(evt->uEventID)
            {
                case EVENT_FRAME_TIMER:
                    Sim->UpdateFrame();
                    break;
            }
        }
        break;
        case SIMCONNECT_RECV_ID_EVENT:
        {
            SIMCONNECT_RECV_EVENT *evt = (SIMCONNECT_RECV_EVENT*)pData;
            switch(evt->uEventID)
            {
                case EVENT_6HZ_TIMER:
                    Sim->Update6hz();
                    break;
                case EVENT_1S_TIMER:
                    Sim->Update1Sec();
                    break;
                case EVENT_4S_TIMER:
                    Sim->Update4Sec();
                    break;
                case EVENT_SIM_STOP:
                    Sim->Stop();
                    break;
                case EVENT_SIM_START:
                    Sim->Start();
                    break;
            }
        }
        break;
        case SIMCONNECT_RECV_ID_OPEN:
        {
            // Subscribe to the simulation events
            hr = SimConnect_SubscribeToSystemEvent(hSimConnect, EVENT_1S_TIMER, "1sec");
            hr = SimConnect_SubscribeToSystemEvent(hSimConnect, EVENT_4S_TIMER, "4sec");
            hr = SimConnect_SubscribeToSystemEvent(hSimConnect, EVENT_6HZ_TIMER, "6Hz");
            hr = SimConnect_SubscribeToSystemEvent(hSimConnect, EVENT_FRAME_TIMER, "Frame");
            hr = SimConnect_SubscribeToSystemEvent(hSimConnect, EVENT_SIM_START, "SimStart");
            hr = SimConnect_SubscribeToSystemEvent(hSimConnect, EVENT_SIM_STOP, "SimStop");
        }
        break;
        case SIMCONNECT_RECV_ID_EXCEPTION:
        {
            SIMCONNECT_RECV_EXCEPTION* except = (SIMCONNECT_RECV_EXCEPTION*) pData;
            switch( except->dwException )
            {
            case 0:
                // Handle exceptions.
                break;
            default:
                break;
            }
        }
        break;
    }
}

Note how we used Simconnect here: JUST to subscribe to system events! Since this sample is only reading airplane simulation variables through the panels interface, we don't need Simconnect to read them, but we use it to subscribe to the different events, and link the members functions in the CSimulation class to those events. I think the code is very easy to follow: just take note how we use the Sim "remote" control: since it's a pointer to a class, we use the Sim-> notation to access its public members. As we saw before, the members we need are the different UpdateXXXX() functions, each one called when the related Simconnect event happens.

Finally, we DO THINGS, let's check the Simulation.cpp file now:

Code:
void CSimulation::Update6hz(void)
{
    Sim->PlaneLatitude.Update();
    Sim->PlaneLongitude.Update();
    Sim->PlaneAltitude.Update();
    Sim->Throttle.Update(1);
}

void CSimulation::Update1Sec(void)
{
}

void CSimulation::UpdateFrame(void)
{
    Sim->Heading.Update();
}

void CSimulation::Update4Sec(void)
{
}

Now things start to make some sense and fall back in place: we finally define what the UpdateXXXX() functions will do in our CSimulation class. The CSimulation:: notation here is used to indicate this is the actual implementation for a function which was defined in the class declaration, in the CSimulation.H file.

As you can see, we only do stuff in the Update6hz() and UpdateFrame() functions. In the context of this sample, we don't need to read the Lat/Lon/Altitude of the airplane every frame, because it will printed on screen with some rounding anyway, so there's absolutely no need to update it constantly, it's possible that it would have looked just the same if we updated it every second.

For the same reason, the Throttle.Update() is read at 6hz, doesn't make any sense to read it faster, because the keyboard/joystick ARE read at 6hz by the sim so, no reason to update the throttle any faster than that.

We reserved the privilege to use UpdateFrame() just to the Heading.Update(), because we wanted to have the maximum smoothness for the heading arrow, so we update it from FSX at every frame. Update at every frame only if you REALLY need it! But using this method, is extremely easy to change, re-order and re-optimize, because everything it's there!

This concludes the "simulation" aspect. Right now, ONLY the CSimulation class has "talked" to FSX, but with this class, we ensured that the content of the CSimulation class is kept updated under OUR OWN specifications. But how we draw stuff on screen ?

Let's have a look at the GDIPlus_Gauge.cpp file, this is the actual drawing code. There's a lot of GDI+ here, which I would rather not discuss in this tutorial. The most important point I wanted to make, was the SEPARATION between drawing gauges and the interaction with the sim. The crucial part is here:

Code:
// Draw the heading indicator, an arrow, on the background (either transparent or an image)
if(NULL != mArrowBitmap)
  {
   mGraphics->TranslateTransform((REAL)(mGaugeWidth/4 * 3), (REAL)(mGaugeHeight/4));
   mGraphics->RotateTransform((REAL)(Sim->Heading.Get()));

Just ignore the GDI+ stuff, the main point here is that I've used Heading.Get() instead of Heading.Update(). Why ? Because I've already called the Heading->Update() in the UpdateFrame() function which (by means of having subscribed to the Simconnect "Frame" event), I'm fairly sure it HAS been called this visual frame, so I'm sure the value IS current. Update() TALKS with FSX.

So, now that I need to use that value to draw something, I just call Get(), which DOESN'T TALK WITH FSX, it simply returns me the last value read, since the last time it was taken from FSX. Of course, reading a pure C++ variable with the Get() function is probably *hundreds* of times faster than asking to FSX AGAIN.

Now, we are doing a simple thing but, what about if you had 20 gauges on screen EACH ONE displaying the same variable ? It wouldn't make any sense to have each one asking to FSX for the same thing. Much better to ask ONCE, in one of the UpdateXXXX() functions of the CSimulation class, and only use the considerably faster Get() inside of the gauges.

Same here:

Code:
StringCbPrintf(mpszDest, mcbDest, L"LAT: %6.3f∞\nLON: %6.3f∞\nALT: %8.0f ft.\n\nHeading: %6.3f∞",
    Sim->PlaneLatitude.Get(),
    Sim->PlaneLongitude.Get(),
    Sim->PlaneAltitude.Get(),
    Sim->Heading.Get()
    );

We print the text, and again we use only the Get() functions, because we know they have been updated (at different rates, but it's not something we should be worried of *here*) so, our reuse of the Heading in this case won't slow down the sim even a bit, compared to re-asking FSX for it, which would have happened if we called the Gauge SDK function directly.

Yes, of course, you could have achieved this in plain C without OOP, by using global variables, updating outside the gauges, and use them in the gauges. But this is WAY more cleaner, safer, easy to understand and with less chances of bugs. For example, with a global variable, you might reuse it elsewhere, perhaps trying to modify it, losing the sync between FSX and the variable, possibly displaying the wrong value to the user. Not this way: by using classes, with accessor functions like Get() and Update(), you can only use the variable as it was supposed to be: in a read-only mode. And, with all globals packed in a single container, the CSimulation object, accessible from everywhere using the Sim pointer, which is the only thing really "global", in a traditional C-way, but still under control, because it's a pointer to a Singleton, not just any global.

This concludes the first tutorial. I know that it might sound complex for a gauge that just draw 4 numbers and an arrow on screen, but I needed to start with something as simple as possible and already familiar to many people (that's why I started form the GDI+ sample in the SDK), and just add the new concepts.

There's a lot more coming, please be free to ask any questions about this.
 
Last edited:
Thanks for posting this stuff Umberto. I'm sure it will prove helpful to any number of people.

Doug
 
May I add an "Amen" to the above? I've been occupied with modeling "stuff" for the last few years, so I've honestly forgotten much of the "old-fashioned, traditional gauge methods," to the point at least that I actually understood most of what you wrote Umberto! You are an excellent teacher. :teacher:
 
Excellent, really excellent. A good example of good OOP programming practice, and patterns clever use too.
I had the same problem to do not duplicate FSIM vars but forgot the old 'singleton' friend :-(
Thanks a lot, i will try to compile it on VC 2010.
 
Last edited:
Reading your code i saw some CFSVar "damping" vars templates. Damping not mentioned in your tutorial.
May you explain better the concept and purpose of "damping" ?
TIA
/Mario
 
Reading your code i saw some CFSVar "damping" vars templates. Damping not mentioned in your tutorial.
May you explain better the concept and purpose of "damping" ?

It's an optional low pass filter, which can be used to simulate intertia, for example for needles but works with anything. In the constructor, it's an optional parameter that goes from 0 to 100, with 100 meaning the most damped value, and 0 equals no damping. There are two variations of damped classes, the regular one, and the one needed for values that are supposed to be angles from 0 to 360 degrees. If you are damping something that relates to an heading value, you should use the CFsVarAngle class.
 
How do the timer event's work? I can't figure out how the Sim knows to send the event every second, 6hz etc because I can't find those as eventids anywhere?
 
How do the timer event's work? I can't figure out how the Sim knows to send the event every second, 6hz etc because I can't find those as eventids anywhere?

This is standard Simconnect stuff.

After you initialize Simconnect, you indicate your dispatch procedure, this is done in the module_init() function of the GaugeDeclaration.cpp file in my example.

In the dispatch procedure, after you receive the SIMCONNECT_RECV_ID_OPEN event, you subscribe to all the system events you need, using the
SimConnect_SubscribeToSystemEvent, this is done in lines 166-171 of the same file in the example.

Those event ids are declared at the start of the CSimulation.H file, they are just 0, 1, 2, 3, etc. enums, as long as they are different from each other, everything will work, what counts (for FSX) is not the event id, but the event names like "1sec", "6hz", "Frame", etc. When you call SimConnect_SubscribeToSystemEvent, you are telling to FSX "call me back with the number 4 when the 6hz event happens", number 4 because it happened to be declared in that order in the EVENT_ID enum, but it could have been any other value.

The same dispatch routine intercepts those events, and call the various Updatexx() members of the CSimulation class, this is done in lines 145-159 in the example.
 
Hello, it is very helpfull.
But the download link was failed by login expired.

I hope you can give advice on my question:
I want to use the 'gauge DLL' in the other program, not P3D. Whether it is feasible in technology?
Because I want to use a third party program to set/get the L:variables.
 
Back
Top