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:
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.