Thomas Sampson


Leave a comment

Visual Studio Post Build Events

I am currently working on a Visual Studio solution that has multiple projects each building an exe or library to a different directory. My aim was to copy some of the output files all into the same folder as the main application is dependent on the other projects residing in the same directory.

Previously, if I had updated and rebuilt one of the projects in the solution I would manually locate the output file and drag it into the right place. However today I discovered the post build events area in Visual studio (right click solution > Build events). Here you can input your own DOS commands and utilise a bunch of VS environmental macros/variables to create a simple batch script which is automatically executed every time you build/rebuild your solution. Any output from your DOS commands (echo) is printed into the ouput window inline with all the other build information Visual Studio provides during the build process.

Here is a simple example which solved my problem but there are much more advanced techniques you could use with this feature.

echo Copying pre loader application to build directory
copy "$(SolutionDir)cwpl_app\bin\Debug\CwplApp.exe" "$(OutDir)"
echo Launching pre loader tool
"$(SolutionDir)cwpl_app\bin\Debug\CwplApp.exe"


Leave a comment

Taking control of the message loop!

Intro

Today I found a neat way to access and work with the windows message loop via a class member function using a small hack/workaround. Unless you are working with a command line application you will probably have need to call RegisterClassEx() (a win api function) at some point early on in your program, to register a window with the operating system. In doing so you fill out a WNDCLASSEX structure describing your window, and also setting the message processing callback function (the part we are interested in).

The scenario

As mentioned previously, when setting up our WNDCLASSEX structure we usually pass a non-member function into the structure as a callback mechanism for system/window events (usually names something like MsgProc). This non member function gets invoked when messages are sent to our application from the OS and we can handle them appropriately.

In a lot of situations (especially when developing games applications) we have some kind of manager class responsible for initialising the window, perhaps a graphics api etc, and it would be nice for this manager class to be able to handle the message loop it’s self using a class member function. This is handy as it allows events in the message loop to directly affect the state and behaviour of the manager class.

The problem is that when registering your window, the WNDCLASSEX structure will not take a class member function as a parameter (due to it needing a handle to the class instance at runtime). I have seen and used many hacks to allow a class to handle this job (involving function pointers / static class methods etc etc) but none have been as efficient as the one which follows…

  • Give the WNDCLASSEX structure a non-member function to act as a …”middle man” message loop
  • When calling CreateWindow() pass in a pointer to the class instance (usually “this“)
  • Inside the non member message loop extract this pointer and redirect the call

Example

Here is an example of redirecting the message loop to the WndProc() method of a Manager instance…

Window Setup
//Setup the window class
WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, MainWndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL,"demo", NULL};

//Register window class with OS
RegisterClassEx(&wc);

// "this" is used to let the window know of our manager class instance
CreateWindow("demo", "demo", MODE_WINDOWED, 100, 100, 640, 480, GetDesktopWindow(), NULL, wc.hInstance, this);
Non-member Message Loop
//NON MEMBER MESSAGE LOOP
LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static Manager* app = 0;

	switch( msg )
	{
		case WM_CREATE:
		{
			// Get the pointer to the manager instance we passed
			// into CreateWindow
			CREATESTRUCT* cs = (CREATESTRUCT*)lParam;
			app = (sys::Core*)cs->lpCreateParams;
			return 0;
		}
	}

	if( app )
	{
		return app->MsgProc(msg, wParam, lParam); //Re-call the message loop on our manager instance
	}
	else
	{
		return DefWindowProc(hwnd, msg, wParam, lParam);
	}
}
Manager::MsgProc (Member Message Loop)
//MEMBER MESSAGE LOOP
LRESULT WINAPI CALLBACK Manager::MsgProc(UINT msg, WPARAM wParam,
																				   LPARAM lParam)
{
	switch (msg)
	{

	//Handle the message here inside the Manager member function

	}
}


2 Comments

Extracting data from float

Earlier this week i was presented with the simple problem of checking if floating point number was a whole number. I stumbled upon the useful function modf and thought it was worth a quick post. the modf function requires <stdio.h> and <math.h>, and allows you to separate the integral and fractional part of a floating point number.

Taking the value 5.24f as an example…

  • Integral part = 5
  • Fractional part=0.24

modf is fully documented here but is rather simple. modf takes two arguments, the first is the value you wish to query (in the case above this would be 5.24). The second argument is a pointer to where the integral part should be placed. The return value of the method is the fractal part. Therefore the solution to my original problem (testing if a float is infact an integer value) is as follows…

Solution

int f;

if(modf(myValue,&f)==0)
{

//myValue is a whole number

}


Understanding the virtual keyword in C++

The virtual keyword is used to allow for true polymorphism to take place in your c++ application.

A real world example

Let’s create a situation which requires both a base and specialised (derived) class architecture. We will use the real world example of Transport and Car, where Car is derived from transport (as would be a bike, or a plane for that matter). Here are the defenitions for each object

The Transport Object

class Transport

{

     private:

        int topSpeed;

     public:

        void IdentifyMyself()

        {
             cout << "I am a Transport Object";
        }

};

The Car Object

class Car : public Transport

{

     private:

     public:

     void IdentifyMyself()

     {

          cout << "I am a Car Object" ;

     }

};

Simple enough?

So, lets examine what actually goes on here

1. The Transport class is created as our base class.

2. The Transport class has one private data member.

3. The Transport class has one public method named IdentifyMyself() which outputs a message.

4. The Car object is created as our specialised/derived class.

5. The Car publicly inherits from the base class Transport, obtaining its private data member topSpeed.

6. The Car also defines a public method named IdentifyMyself() which also outputs a message.

What next?

The important part to take from above is that Car inherits from Transport, and that they both contain a defenition for the method IdentifyMyself().

So let’s use our objects! Here is a snippet of code which uses our objects and their methods…

Transport t;

Car c;

t.IdentifyMyself();

c.IdentifyMyself();

Output

I am a Transport ObjectI am a Car object

So, the Car’s method overrides the base class method and the two objects print a different message, simple. Now consider the following….

Test code

Transport* t

Car c;

t=&c;

c.IdentifyMyself();

t->IdentifyMyself();

We now have a car object as before, but this time we setup a pointer “t” (of the type Transport) to point to our Car, “c” . We are allowed to do so as “Car is a type of Transport”. However, take note of the output.

Output

I am a Car objectI am a Transport object

Even though our pointer “t” points to a Car object, we still call the IdentifyMyself() method of the base class. This is because there is no overriding, and as the pointer is of the type Transport, we simply call the Transport’s method, no longer the one overridden by Car. This is where the virtual keyword comes into play.

Let’s redefine the base class Transport to unclude a virtual method…

The New Transport Object

class Transport

{

     private:

        int topSpeed;

     public:

        virtual void IdentifyMyself()

        {
             cout << "I am a Transport Object";
        }

};

Now lets run the same code again and notice the difference in output….

Test code

Transport* t

Car c;

t=&c;

c.IdentifyMyself();

t->IdentifyMyself();

Output

I am a Car objectI am a Car object

This time when we dereference the pointer “t”,  even though our pointer is of the type Transport, due to Transport using the virtual keyword before IdentifyMyself(), it now forces the program to downcast to our inherited object Car and call the overridden IdentifyMyself() method instead.

How does this work under the hood?

Let’s think back to when our Transport class  did not employ the virtual keyword. At compile time we can collect up all Transport’s class methods and know where they will reside in memory. However, when we use the virtual keyword, when accessing a pointer to a Transport object, these methods could be anywhere in memory (depending upon the layout of the derived type which overrides them).

The way to resolve this is for each object which uses virtual methods, to keep a vtable (virtual method lookup table) which keeps a list of virtual function pointers. This vtable is always kept at memory offset 0 and can be though of as a hidden datamember for classes which use the virtual keyword or override virtual methods. This can be seen when watching a pointer to our Transport instance, using the Visual Studio Debugger as shown below as __vfptr (virtual function pointers).

This is done automatically by the compiler for any base class which employ virtual methods, and inherently for those that derive from the base class. This vtable is always kept at memory offset 0, so we can always take a pointer to a Transport object, and check its vtable and call the right method. This becomes more complex with multiple inheritence.

Summary

Imagine increasing the scale of this program to include Planes, Trains and Motorbikes. We could now keep a list, 100 items long, of transport pointers…

Transport* mylist[100];

…and iterate through this list, calling ->IdentifyMyself() on each item. Now that the base class implements the virtual keyword, true polymorphism takes place and any derived classes which choose to override this method, get their chance to output a custom message. For those classes that dont override the IdentifyMyself() method, the base class method will be called.


4 Comments

Shorthand IF statement in C++

The C++ conditional operator (also known as the ternary operator) provides a succinct way to select a simple operation or assignment value based on a condition, without expressing the selection with the more cumbersome if/else syntax. If the condition is true, the leftmost expression is evaluated, otherwise the rightmost. Example usage can be seen below.

int a(5), b(10);
(a > b)? std::cout << a : std::cout << b; // operation
int c = (a > b)? a : b;                   // assignment
int d = (a > b)? ((a > 10)? 10 : a) : b;  // nested


Leave a comment

C++ Inline keyword

Today I came across the inline keyword in c++. The inline keyword can be placed before a function defenition and is usually placed before functions which contain only a few lines of code.

If you have written a function which is only 3 lines of code for example, and these 3 lines of code are fairly simple and non resource-expensive, some compilers will automatically inline your function. However, the inline keyword is a way of enforcing that this happens at compile time. So what is function inlining?

Function inlining allows the compiler to substitute any calls to your function with the actual function definition it’s self. Let’s say you have a call to a function go(). Without function inlining, at runtime all sorts will go off. Register values, any paramaters and the instruction pointer will be pushed onto the stack (time consuming), the instruction pointer pointed to the location of the function, the function executes then all values are popped off of the stack!

If your function is a large complex algorithm which only gets executed a couple of times in the program, and needs keeping seperate for clarity, then this is not such a problem. However if your function is small and gets called repeatedly throughout the program, function inlining allows those few lines of code, to replace the original call to the function. For example,

Without function inlining…

void go()
{
    cout << "Hello World";
    cout << "Test function!";
}
int main()
{
    for(int i( 0);i<10;++i)
    {
        go(); // Standard call mechanism initiated
    }
}

With function inlining enforced…..

inline void go()
{
    cout << "Hello World";
    cout << "Test function!";
}
int main()
{
    for(int i( 0);i<10;++i)
    {
        cout << "Hello World"; //Gets inserted at compile time
        cout << "Test function!"; //Gets inserted at compile time
    }
}

Although many factors contribute towards the performance of a program, inlining can be used to bring about significant performance increases if used properly.


Using a QueryPerformanceTimer in C++

“Query Performance Counters” can be used to create timers within your code, usually used to capture the time it takes to carry out a given function or set of instructions. Query Performance Counters can be particularly useful when you are looking to optimise a piece of code and need to run comparisons on your optimisations.

To start using performance timers first make sure to include the following..

#include <windows.h>
#include “stdio.h”

using namespace std;

Next you need to create some variables to hold the timing data, these are of the type LARGE_INTEGER.

LARGE_INTEGER start, end, freq;

Now we are ready to set up the timer. First pick a place where you are wanting to start and stop your timer. Once you are sure insert the following pieces of code in the appropriate positions

QueryPerformanceCounter(&start); //To start the times

// Code here

QueryPerformanceCounter(&end);  //Same function stops the timer (notice different return variable)

LARGE_INTEGER numTicks=(end.LowPart – start.LowPart); // Save the number of ticks

The amount of time passed by is recorded in “ticks” rather than seconds or milliseconds, we can deal with this later. Ticks are units that relate to the processing speed of your CPU, therefore every machine will have different tick durations and tick speeds. Therefore we need a way to convert ticks into something useful. This is quite a simple calculation as we can query the processor to tell us how many ticks occur per second. This is achieved with the following code and should be placed right after the timer has finished…

QueryPerformanceFrequency(&freq);

So now we have two important numbers…

  1. numTicks
  2. freq (number of ticks per second)

A simple calculation brings us to the following result…

float elapsedTime = (float)ticks/frequency;

Where elapsedTime represents the number of Seconds the timer took!


1 Comment

Debugging full screen DirectX Applications

Today I was trying to step through some code for intialising a vertex buffer, as something was going drastically wrong along the way. However my application needed to be tested in full screen mode which made debugging through VS impossible as the application I was trying to debug takes full control of the screen.

There seem to be two solutions in this scenario;

  1. Modify your code to run in windowed mode (easy enough to do, just change your window class registration and DirectX initialisation routines)
  2. Use multiple monitors –> Goto control panel, choose DirectX, Goto DirectDraw tab, choose Advanced and enable Multiple Monitor Debugging.


6 Comments

Listing files in a directory in C++

First of all I am not sure how you go about doing this in unix or linux! There is no standard, platform specific way to get all the files in a directory, however the following method works on windows making use of calls to winAPI so dont forget to include this!

#include <windows.h>

The following code then loops through a folder (in this case the starting folder of the executable) and puts the filenames into a string array.  The functions FindFirstFile and FindNextFile both work by populating a structure of the type WIN32_FIND_DATA which holds all the properties of the file in question.

UINT counter(0);
bool working(true);
string buffer;
string fileName[1000];

WIN32_FIND_DATA myimage;
HANDLE myHandle=FindFirstFile("*.jpg",&myimage);

if(myHandle!=INVALID_HANDLE_VALUE)
{
       buffer=myimage.cFileName;
       fileName[counter]=buffer;

       while(working)
       {
              FindNextFile(myHandle,&myimage);
              if(myimage.cFileName!=buffer)
              {
                     buffer=myimage.cFileName;
                     ++counter;
                     fileName[counter]=buffer;
              }
              else
              {
                      //end of files reached
                      working=false;
              }

       }
}

When the last file in the folder has been read, the FindNextFile method will keep returning the same filename over and over again in the while loop. To catch this i use a sort of swap buffer to check if the same filename is found twice, and if so exiting the loop. I am sure there is a better way to catch the last file and will look into this soon. If anyone knows a more efficient way to do this please let me know.

NOTE:- “*.jpg” could be replaced with “C:/myfolder” or “*.doc” or a combination of the two depending on how you wish to filter the files that are found.  Using “” would list all the files in the running directory of the executable.


1 Comment

A Window for your game!

WindowBefore touching any graphics API it is important that we think about how the game will run. As mentioned previously I have chosen to use the DirectX graphics library to display and render my whole application. DirectX is used for creating rich 3d visuals for both the PC and xBox. Regardless of this choice, the initial process of getting a game (or any application) to run on the PC requires using the Windows API to set up the application and window in which the game will run, hence this post would apply almost identically if you were planning on using the OpenGL library.

Before starting it is worth mentioning that I have no experience at all of getting home brew code to run on a 360 but I do understand that like the PC, it’s games use the DirectX libraries. Ofcourse, I will be compiling my c++ code for the PC but it is important to remeber that the c++ code for a PC game and a 360 will be very similar. The main difference is the system architecture of the two platforms.

When compiling for the PC we are compiling to an x86 binary file, however the xBox 360 uses the Power PC architecture so a different compiler must be used to generate the appropriate machine code. I am also sure that a number of things must also be done to your c++ code if you were planning to port it to an xBox 360, but I have no understanding of this (and you probably wont need to know this as it is usually handled by a game engine). This does not mean that this isn’t an interesting topic and I may do a post on this area at a later date. If anyone reading does know more about this please leave a comment and I will try and integrate your feedback into this post!

Starting the project

Anyway, I will now try and explain the process of setting up a window in which you will be able to host your game. At this stage no extra libraries need including, we simply make use of the “windows.h” header file. I will show code snippets step by step, the complete source code for this post can be found here.

You first need to set up a new “win32” project in visual studio (as shown below), and make sure you tick the “blank project” check box when required.

Next simply add a source code (cpp) file to your project and call this anything you like, preferably “main” or “winMain”.

Setting Up Your Window

When programming a windows application, if the application has any form of visual representation beyond command line you must register a window class. Once a window class is registered, the windows operating will send any messages necessary to your application. Messages are anything that your application needs to know about, for instance a keypress, minimising your window, or a mouse click. To start off we will include the windows header file and set up global variables to hold our application and window instances.

#include <windows.h>

HINSTANCE hInst;       //global access to application instance
HWND wndHandle;        //global access to the window instance

//function prototypes
bool initWindow( HINSTANCE hInstance);
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM);

Don’t worry too much about the function prototypes as they simply tell the compiler that we plan to use the defined functions later in our code (forward decleration). Next we need to create the program entry point, for console applications this is “int main()” however with a windows application it translates to..

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)

A quick summary of whats going on here. This is the program entry point and you can see there are 4 arguments. hInstance is the handle to your application, hPreviousInstance will always be NULL and historically was a way of identifying a previous instance of your program, lpCmdLine is a pointer to any parameters passed to your application (for instance if someone ran your program as “myApp.exe -h hi”). As far ask I know nShowCmd is the start mode of your application from the operating system (maximized, minimized etc). For now all of this is useless and we will not use any of the parameters, they just need to exist within the code.

The Main Program Code

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
    //Initialize the main window
    if(!initWindow( hInstance))
    {
        return false; //If initialisation fails, exit program
    }

    MSG msg;                             //New message object
    ZeroMemory( &msg, sizeof( msg) );    //Clear memory

    //Main Message Loop
    while( msg.message!=WM_QUIT)
    {
        // Check the message queue
        while( GetMessage(&msg, wndHandle, 0, 0) )
        {
            TranslateMessage( &msg);
            DispatchMessage( &msg);
        }
    }

    return (int) msg.wParam; //Return with exit code
}

This is basically what is going off here…

  1. Attempt to initialise the window (using the yet to be defined “initWIndow” method)
  2. Check the success of the window creation, quitting immediately if anything failed
  3. Create and clear a message object which will be used when processing window messages
  4. While ever the QUIT message (the user clicks close) isn’t on the message queue, check for the next message
  5. Translate and dispatch messages to be interpreted and handled by the (yet to be defined) “wndProc” callback method.

Click here for more information on ZeroMemory() – (popup window)

This should be pretty self explantory although you might wonder how the program knows to use the wndProc callback method? Well this is set up and configured when we set up our window in the initWIndow function to follow.

initiWindow

Here is the code for the initWindow function previously declared

bool initWindow( HINSTANCE hInstance)
{
    WNDCLASSEX wcex;

    wcex.hInstance=hInstance;                      //link this window with the application instance
    wcex.cbSize= sizeof(WNDCLASSEX);               //size of the structure
    wcex.style= CS_HREDRAW | CS_VREDRAW;           //style
    wcex.lpfnWndProc = (WNDPROC)WndProc;           //the window procedure callback mechanism
    wcex.cbClsExtra = 0;                           //Extra bytpe allocation (not required)
    wcex.cbWndExtra = 0;                           //Extra bytpe allocation (not required)
    wcex.hIcon = 0;                                //icon to use for the window
    wcex.hIconSm = 0;                              //Set small icon
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);    //choose the cursor for the window
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); //Choose background colour
    wcex.lpszMenuName = NULL;                       //Not using
    wcex.lpszClassName = (LPCSTR)"WindowExample";   //Name of the class
    RegisterClassEx(&wcex);                         //Register window class with system

    wndHandle=CreateWindow((LPCSTR)"WindowExample",
                           (LPCSTR)"Title bar text here",
                           WS_OVERLAPPEDWINDOW,
                           CW_USEDEFAULT, CW_USEDEFAULT,
                           640,480,NULL,NULL,hInstance,NULL);

    //Check success of window creation
    if(!wndHandle)
    {
        return false;
    }
    //Show successful window
    ShowWindow(wndHandle,SW_SHOW);
    UpdateWindow(wndHandle);
    return true;
}

Again this should be fairly self explanitory. We make a new instance of a window class and set all its attributes (the long wcex. list! ) Most of these attributes you dont need to know and others are self explantory, however it is important you are specific with your lpszClassName as this exact value is required a little further down as the first parameter of CreateWindow.

Here is a summary of this function…

  1. Make an instance of a WNDCLASSEX object and set all its attribute including its “lpszClassName”, and “lpfnWndProc” to set up the callback method (for handling messages)
  2. Register this class object with the system
  3. Create a window based upon the registered window class, assigning this to out window handle (wndHandle)
  4. Check to ensure the window creation was a success (returning false if it fails)
  5. Show and update the window.

Finally…

All that remains to do now is define our callback mechnism which will handle all the messages that our window recieves while it is open. Remember, this was defined at the very top as “LRESULT CALLBACK WndProc”. Here is the code for this function..

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    }
    return DefWindowProc(hWnd,message,wParam,lParam);
}

Pretty simple really..

  1. Check the contents of the message (we are only currently listening out for a quit message)
  2. If a quit message is fired run PostQuitMessage to quit tidily
  3. At this point (the user has quitted) , the while loop condition in the main program is broken, and the code will exit and return the user to the desktop.

All together now!

Here is a link to the complete cpp file

At this stage i would recommend making sure your code works and displays a white blank window, and put it in a safe place. You never really want to write this code again and should just adapt it to any project you start in future.