Intercepting OpenGL Calls

To capture the OpenGL commands is fairly easy, all you need to do is link a library that implements the OpenGL function before it links the actual library.
Screen Shot 2014-04-28 at 09.46.51

Originally I had planned to use the environment variable DYLD_INSERT_LIBRARIES to achieve this, however I could not get it to work with my Cocoa application. So I decided to just compile it with it and let the user decide whether or not they want to run the executable and insert the library at runtime, or add it to their project to link first.

The next challenge is that now you have intercepted the call, you still need to forward it onto where it was going originally. To do this, I used the link library constructor to retrieve and store this pointer for later use to reduce overhead.

#include <stdio.h>
#include <dlfcn.h>
 
//
typedef void (*_fn_glViewport) (GLint x, GLint y, GLsizei width, GLsizei height);
_fn_glViewport g_glViewport = NULL;
 
//
__attribute__((constructor)) void DllMain()
{
	g_glViewport = (_fn_glViewport)dlsym(RTLD_NEXT, "glViewport");
}
 
//
void glViewport (GLint x, GLint y, GLsizei width, GLsizei height)
{
	printf("Intercepted glViewport call\n");
	g_glViewport(x, y, width, height);
}

The RTLD_NEXT parameter tells dlsym to retrieve the method from the next linked dependencies. Ideally you probably want to check the pointer to make sure it isn’t NULL before calling it, however since glViewport comes from OpenGL 1.0 and still exists in the latest version, I don’t bother.

SprintfCat

On the train to Cardiff yesterday, I was creating a fixed function shader generator for the Athena engine. I kept using strcat() with if statements, and in a lot of places I kept using sprintf() then copying that in with strcat().

So I decided to make SprintfCat(), all the wonderful joy of sprintf, with the ability to concatenate with a already existant string like strcat.

//
//
size_t ath::SprintfCat( char * inoutBuffer, const size_t inBufferSize, const char * inFormat, ... )
{
	const size_t offset = StrLen( inoutBuffer );
	size_t ret = 0;
	va_list arg;
 
	//
	va_start( arg, inFormat );
	{
		ret = VSprintf( inoutBuffer + offset, inBufferSize - offset, inFormat, arg );
	}
	va_end( arg );
 
	//
	return offset + ret;
}

I had already created my own wrappers around strlen() and vsprintf(), the reason being the fault of Microsoft. With their implementation of the standard library, they decided to deprecate non-safe versions complain at you until you either used their own _s variants, or defined a certain preprocessor.

//
//
size_t ath::VSprintf( char * outBuffer, const size_t inBufferSize, const char * inFormat, va_list inArgs )
{
#ifndef ATH_PLATFORM_WINDOWS
	return vsnprintf( outBuffer, inBufferSize, inFormat, inArgs );
#else
	return vsprintf_s( outBuffer, inBufferSize, inFormat, inArgs );
#endif
}
 
//
//
size_t ath::StrLen( const char * inString )
{
	return strlen( inString );
}

While I do prefer to have safe versions, their _s variants are not present in the standard and so it makes the code not portable.

I’m still not quite sure about my naming convention for a variable that is an input and an output. While I do like the in or out prefix, I don’t think inout looks right, being slightly too long. I wasn’t a fan of io either. I have however grown to like the truncation of Athena namespace to ath.

Assert Pointer and Delegate

While bored the other day, I made a template class that wraps around a pointer, and will assert when it is null.

//
//
#include <assert.h>
 
//
//
template<typename T>
struct AssertPointer
{
	//
	AssertPointer()
		:
		mPointer( NULL )
	{
	}
 
	//
	AssertPointer( T * inPointer )
		:
		mPointer( inPointer )
	{
	}
 
	//
	operator T * ()
	{
		assert( mPointer );
		return mPointer;
	}
 
	//
	operator T * const () const
	{
		assert( mPointer );
		return mPointer;
	}
 
	//
	T * operator -> ()
	{
		assert( mPointer );
		return mPointer;
	}
 
	//
	T * const operator -> () const
	{
		assert( mPointer );
		return mPointer;
	}
 
	//
	T * GetPointerValue()
	{
		return mPointer;
	}
 
	//
	T * const GetPointerValue() const
	{
		return mPointer;
	}
 
private:
	//
	T * mPointer;
};

When declaring your pointer, use the pointer type as the template argument. For example, if you want a pointer to an integer, AssertPointer<int>, or a pointer to an integer pointer, AssertPointer<int *>.

For class or structure pointers, the -> operator is overloaded so you can access its members as you would a normal pointer.

If you need access to the raw pointer value without the assert, just use the GetPointerValue() functions.

I may use it to replace the Delegate structure I created for callbacks in Athena.

template<typename T, class U = void>
struct Delegate
{
	//
	Delegate()
		:
		func( NULL ),
		object( NULL )
	{
	}
 
	//
	Delegate( T inFunc, U * inObject = NULL )
		:
		func( inFunc ),
		object( inObject )
	{
	}
 
	//
	T func;
	U * object;
};

It is used to store a class object and a function pointer within that class in a single structure. I can use the AssertPointer class and pass the class template type to its template argument, giving me better feedback when I get null pointers being used in my delegates.

Floating Point Comparison with Epsilon

Greek EpsilonWith my recent update of Athena’s math library to use vDSP_* functions for faster math, I decided to add a unit test to all my math functions since I have had occasions where I change it and then it breaks some code elsewhere that I do not notice.

I got to writing the unit test for my vector divided by a scalar function when it started to assert. On initial look at the values printed out into the TTY they were both correct, so I extended the precision to 9 and two slightly different values.

TTY   
Calculated: 4.059524059
 
Precomputed:  4.059523582
 
Difference: 0.000000477

The values were not that far apart, and I know floating point math can differ for the same value so when comparing usually epsilon gets involved since it is the maximum error. Printing out epsilon, I discovered that the value was just slightly bigger than it making the two numbers different enough.

TTY   
Difference: 0.000000477
 
Epsilon: 0.000000119

I could just have my own custom version of epsilon but it would become incorrect for use with smaller and larger number. Or for this case in the unit test I could just use a custom compare, but I wanted something more reusable, and the first google result found me a function.

bool AlmostEqualRelative2(float A, float B, float maxRelativeError)
{
	if( A == B )
	{
		return true;
	}
 
	float relativeError;
 
	if( fabs(B) > fabs(A) )
	{
		relativeError = fabs((A - B) / B);
	}
	else
	{
		relativeError = fabs((A - B) / A);
	}
 
	if( relativeError <= maxRelativeError )
	{
		return true;
	}
 
	return false;
}

It is a fairly simple one, rather than just comparing the difference to a larger, it determines the relative error and the user passes in a percentage of how large an error it can be.

Although they recommend on the site that you still do not use it, or now it keeps my unit test working allowing me to continue until I have read the rest of the website.