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);
Advertisements


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