Thomas Sampson


Leave a comment

Visual Studio ‘Find & Replace’ with Regex Groups

TIL; When using Visual Studio ‘Find & Replace’, regex match groups used within the search term, can be referenced numerically in the replacement term using the $ symbol. The example below adds spaces between function parameters:

Test String

SomeFunctionCall(param1,param2,param3);

Search term

,(\w)

Replacement term

, $1

Result

SomeFunctionCall(param1, param2, param3);


Leave a comment

Preventing Multiple Process Instances In C++

Here is a quick C++ class I knocked up earlier this week which can be used to ensure that only a single instance of your application is running at any given time, using a system-wide mutex object along with a unique process identifier to prevent concurrent execution. The implementation provided is Windows only but could easily be adapted for other platforms using pthread_mutex_trylock.

ProcessInstance Class

#include <windows.h>
#include <string>

class ProcessInstance
{
public:
	ProcessInstance(const std::string& processIdentifier)
		: m_bIsAlreadyRunning(false), m_hProcessInstanceLock(0)
	{
		m_hProcessInstanceLock = ::CreateMutex(0, true, processIdentifier.c_str());
		m_bIsAlreadyRunning = (::GetLastError() == ERROR_ALREADY_EXISTS);
	}

	~ProcessInstance()
	{
		if(m_hProcessInstanceLock)
		{
			::ReleaseMutex(m_hProcessInstanceLock);
		}
	}

	bool IsAlreadyRunning() const
	{
		return m_bIsAlreadyRunning;
	}

private:
	bool m_bIsAlreadyRunning;
	HANDLE m_hProcessInstanceLock;
};

Usage

ProcessInstance gProcess("my_process_guid_here");
int main(int argc, char* argv[])
{
	if(gProcess.IsAlreadyRunning())
	{
		return 0;
	}
}


Leave a comment

Linking Debug Traces to Source Code

Today I discovered a nice little feature involving the Microsoft Visual Studio output window.

When emitting debug trace information from your application (using OutputDebugString), you can format your output string in such a way that when it is double-clicked in the output window, it jumps your code editor to the spot where it originated. The format which supports this feature is as follows:

%ABSOLUTE_FILE_PATH%(%LINE_NUMBER$): %MESSAGE%

So for example:

“C:/TextureManager.cpp(50): [TextureManager] Texture loaded!”

I often find myself copying a line from the output window and using CTRL+SHIFT+F (Find In File) to locate it’s origin. This is a nice way to get around that long winded process and provide a direct link to the file and line. You can of-course use the __FILE__ and __LINE__ pre-processor macros here to automatically format all your debug traces in this way.


1 Comment

Debugging DirectX applications with PIX for Windows

Introduction

 After using Microsoft’s PIX tool numerous times over the past couple of years, on a number of projects (all Windows/DX9 based), I was surprised to find that many other students weren’t using PIX and would often spend many hours close to submission date, getting to the bottom of the most tedious graphical bugs or rendering artefacts. I’m confident that the bugs in question could often have been identified and fixed in a matter of moments given the right tools . This brings me to “PIX for Windows”, Microsoft’s graphics debugger for DirectX. Don’t get me wrong, PIX isn’t the answer to all your problems, neither will it fix anything for you automatically out of the box. The purpose of this post is to provide a quick run through the essential prerequisites required in order to get up and running with PIX, followed by a brief explanation of some of the most useful features PIX has to offer. I also demonstrate how you can configure your C++ DirectX application to be “PIX aware”, communicating with PIX to make the debugging experience a little simpler and smarter. For further reference, please see PIX for Windows documentation.

Installing PIX

PIX for Windows is a GUI tool distributed with the Microsoft DirectX SDK and can be found in the following location after install;

%DXSDK_DIR%\Utilities\bin\%ARCHITECTURE%\PIXWin.exe

Configuring Your System

Before firing up PIX, first head to the DirectX Control Panel, this is a nice GUI utility which allows you to tweak the DirectX runtime by enabling/disabling certain features and components.

The DirectX control panel is also part of the Microsoft DirectX SDK and can be found in the following location after install;

%DXSDK_DIR%\Utilities\bin\%ARCHITECTURE%\dxcpl.exe

Regardless of whether or not you choose to use PIX,  it is handy to know about this utility as it can be used to toggle between the debug/release DirectX DLLs and turn on useful compile/runtime feedback . This feedback ranges from efficiency warnings to runtime memory leak reports.

Figure 1 (Click to enlarge)

Figure 1 shows my DirectX Control Panel configuration, which I have tweaked for personal preference. Mirroring this configuration should ensure PIX operates correctly, although not all the options I have enabled are not necessarily fundamental or related to PIX in any way. Play around with this configuration utility and find a configuration you are comfortable with. I often find myself tweaking the “Debug Output Level” slider based on the scenario, and disabling “Break on memory leaks” when I’m looking at someone else’s code and don’t care too much about memory leaks. Also, use “Software Only” mode judiciously, as this disables all hardware acceleration and forces everything to be rendered in software on the CPU (which can be painfully slow!).

Note: The “Render” and “Mesh” windows within PIX do not function correctly when “Maximum Validation” is disabled.

Next: Experiment One >>


Leave a comment

CallOnce

UPDATE: Modified the implementation to use singleton method access to CallOnce function map. Also added example of usage distributed across multiple source files.

CallOnce is a C++ technique I have picked up recently which allows code to be executed (usually to perform static initialisation or other housekeeping activities) before the program entry point (usually main). Rather than having some Init() method right at the beginning of the application which attempts to initialise all your static objects and data, the CallOnce mechanism allows each cpp file to register it’s own functions which gets called during global static initialisation (before the program entry point). This system is much cleaner and easier to manage, removing the requirement for a large central “Init()” function.

CallOnce can be implemented in various ways. In C++ global static initialisation order is undefined, for this reason additional levels of control can be added to the CallOnce implementation to define the order in which the registered functions get called (very important if there are dependencies between static objects and data). In this post I will keep things as simple as possible and use a couple of examples to demonstrate this technique.

Example 1

In this simple example a class “CallOnce” has a constructor which takes a function pointer (return type void, no parameters). In the constructor of the CallOnce class the function passed in gets called.
To use this system all that is required is to create some global instance of the CallOnce object and pass it the address of an initialisation function (in this case ::Init). The output proves that the Init function was in fact called before the program reached main.

Main.cpp

#include <stdio.h>

class CallOnce
{
	public:
		typedef void (*CallOnceFunc)(void);
		explicit CallOnce(CallOnceFunc func)
		{ func(); }
};

void Init()
{
	printf("Hello ");
}

const CallOnce gCallOnce( &Init);
int main(int argc, char* argv[])
{
	printf("World");
	return 0;
}

Output


> Hello World

Example 2

In this slightly more involved example, rather than immediately calling the function passed in the constructor, the function is inserted into a static map and stored there until CallOnce::Init() is called. When this happens, all of the registered functions get called in order of their priority (as std::map is automatically ordered by key and we store the priority value as the map key). By default all registering functions are given priority 1000 unless the overloaded constructor is used to specify a priority (in this system 0 = Highest priority). In the example shown below, even though Init1 is registered before Init2, due to the priorities specified they are executed in reverse order.

NOTE: The CallOnce instances do not all have to exist right before main, they can be scattered around your code base inside any cpp file you want.

CallOnce.h

#include <stdio.h>
#include <map>

class CallOnce
{
	public:
		typedef void (*CallOnceFunc)(void);
		typedef std::map<int, CallOnceFunc> FuncMap;

		explicit CallOnce(CallOnceFunc func)
		{
			static const unsigned int uDefaultPriority = 1000;
			GetFuncMap().insert(std::make_pair<int,CallOnceFunc>(uDefaultPriority, func));
		}
		explicit CallOnce(CallOnceFunc func, int iPriority)
		{
			GetFuncMap().insert(std::make_pair<int,CallOnceFunc>(iPriority, func));
		}
		static void Init()
		{
			FuncMap::const_iterator it(GetFuncMap().begin());
			for(; it != GetFuncMap().end(); ++it)
				(*it).second();
		}
	private:
		static FuncMap& GetFuncMap()
		{
			static FuncMap singleton;
			return singleton;
		}
};

Foo.cpp

#include "CallOnce.h"

void Init1() { printf("Init1 Called\r\n"); }
const CallOnce gCallOnce	 ( &Init1, 1);

Bar.cpp

#include "CallOnce.h"

void Init2() { printf("Init2 Called\r\n"); }
const CallOnce gCallOnceAgain( &Init2, 0);

Main.cpp

#include "CallOnce.h"

int main(int argc, char* argv[])
{
	CallOnce::Init();
	printf("Main Called");
	return 0;
}

Output


> Init2 Called

> Init1 Called

> Main Called


Leave a comment

Clamping Values

Using the Pre-processor

“Macros like this have so many drawbacks, just thinking about them is painful” – Scott Meyers.

#define min(a,b)                      (((a) < (b)) ? (a) : (b))
#define max(a,b)                      (((a) > (b)) ? (a) : (b))
#define clamp(value, lb, ub)          max( lb, min( ub, value ))

Using Templates (Inline)

A much safer and elegant approach, relies on T::operator< and T::operator> to perform the evaluation.

template<typename T>
inline T Min(const T& a, const T& b) { return (a < b)? a : b; }

template<typename T>
inline T Max(const T& a, const T& b) { return (a > b)? a : b; }

template<typename T>
inline T Clamp(const T& value, const T& lb, const T& ub) { return Max<T>(lb, Min<T>(ub, value)); }


Leave a comment

“Smart Pointers”

Smart pointers are objects used to manage resources which were created on the heap, and allow such resources to be deleted automatically whenever their parent smart pointer would normally go out of scope. This avoids the common problem of calling new to allocate some space on the stack for an object (returning a pointer to the object), using that pointer, and then never calling delete (causing a memory leak to occur).

Another benefit of using smart pointers is the ability to have references to heap resources counted (using reference counting). This is useful when you have a particular resource on the heap, let’s call this object x. There are n number of objects around your program which all carry a pointer to object x to use its data and functions. In this case when should object x be destroyed and the memory freed? The answer to this is typically “When n =0”. So, when the last object containing a reference to object x is removed, the reference count of object x reaches 0 and the smart pointer can then de-allocate any memory consumed by object x on the heap.

Implementation
Smart pointers have two key components. Firstly they have a pointer onto the resource being managed (in the example below this is m_data). Secondly they have a pointer to a reference counting object which allows them to keep a track of how many references there are to the managed resource, in this case rc). The reason a pointer to the reference counter is used rather than a pure data member, is that all references to the managed resource (that is, all copies of an instance of a smart pointer) need to share the same reference count as there can only be one reference count per managed object.

The example below shows a quick smart pointer implementation I wrote. There are much better tested implementations found in the stl and boost libraries but my example below just demonstrates simply what is going off.

The smart pointer object is a template class, allowing it to manage a pointer to any type of resource (but not arrays!). When the smart pointer is constructed it is given a pointer to the heap allocated object and it also creates a unique reference count for this object (From this point on, all copies of the smart pointer for the managed object share a pointer to the reference count so they can all communicate). After the first initialisation, whenever a “copy” of the resource is needed by other methods or objects (I say copy because it is only a copy of the reference they require, not a physical copy of the object) the copy constructor of the smart pointer object is called, incrementing the reference count. Whenever the smart pointer object gets destructed, the reference count for the underlying object is decremented. This way the destructor of the smart pointer can always check to see if no more references remain, and free the resources.


#include <iostream>
#include <vector>

class ref_count
{
    public:
        unsigned int count;
        ref_count() : count( 1) {}
};

template<class T>
class smart_ptr
{
    public:
        T* m_data;
        ref_count* rc;

        smart_ptr(T* data) : m_data( data), rc( new ref_count())
        {
            std::cout << "Smart pointer constructed for object "<<m_data<< "\n";
        }
        smart_ptr(const smart_ptr& source)
        {
            m_data=source.m_data;
            rc=source.rc;
            ++rc->count;
            std::cout << "Reference added for object " << m_data << "\n Ref Count = "<<rc->count<<"\n";
        }
        ~smart_ptr()
        {
            if( rc->count==1) //if last one
            {
                std::cout << "Smart pointer destructed for object "<<m_data<< "\n OBJECT RELEASED AT "<<m_data<<"\n";
                delete m_data;
            }
            else
            {
                --rc->count;
                std::cout << "Reference removed for object " << m_data << "\n Ref Count = "<<rc->count<<"\n";
            }
        }
};

class Car
{
    public:
        Car() { std::cout << "car constructed at " << this << "\n"; }
        ~Car() { std::cout << "car destructed at " << this << "\n"; }
};

void foo()
{
    std::vector<smart_ptr<Car>> garage1, garage2;
    smart_ptr<Car> car_ptr( new Car());
    garage1.push_back(car_ptr);
    garage2.push_back(car_ptr);
}

int main(int argc, char* argv[])
{
    foo();
    std::cin.get();
    return 0;
}


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

	}
}