C++11 compile time checked printf format

A few notes on how I wrote 100% compile time checked printf-style format type checker. Source code is online on GitHub.

Motivation

I recently worked again a bit on ezEngine, a beautiful Open Source game engine developed continuously by a few friends of mine in their spare time. ezEngine uses custom implemented formatting function that follows the style of (s)printf. Like printf it is C-varargs based and therefore not type safe. Example:

printf("%i", "not an int");

Continue reading

Advertisements

Microproject: OptionalScopedObject template class

(Published in similar form GitHub)

Recently I ran into a weird situation where a threading lock was either passed, or not (since locking might or might not be appropriate in a given situation). Since I am always very concerned about other people adding early out return statements and forgetting to do the cleanup (here: unlocking the lock), I wanted to use a scoped version of the lock. But having the scope optional forced me into using an allocation:

void somethingProbablyUnsafe(ThreadingLock* lock)
{
    // unrelated code
    // ...

    std::unique_ptr<ScopedLock> scopedLock;
    if(lock)
    {
        scopedLock.reset(new ScopedLock(*lock));
    }

    // Complicated code with early outs.
    // ...
}

This certainly solves the problem – the lock is still scoped and nobody needs to worry about having the lock unlocked. Way better than checking the lock variable at each return point. But it requires an allocation and no longer keeps the ScopedLock on the stack as it is intended to be, how awful! 😦

Template programming for the rescue! Using variadic templates and placement constructors we can solve this problem in no time once and for all! 🙂

// Class wrapper to provide an optional scoped object on the stack without any dynamic allocations.
template<typename ScopedObject>
class OptionalScopedObject
{
public:
	// Creates a new inactive object. The underlying ScopedObject type is not initialized!
	OptionalScopedObject() : m_active(false)
	{
	}

	// If the underlying ScopedObject was created via construct, it will be deconstructed.
	~OptionalScopedObject()
	{
		destruct();
	}

	OptionalScopedObject(OptionalScopedObject&) = delete;
	void operator = (OptionalScopedObject&) = delete;

	// Constructs the object. Will destruct the object first if there was already one.
	template<typename... Args>
	void construct(Args... args)
	{
		if (m_active)
		{
			(*this)->~ScopedObject();
		}
		new (m_memory) ScopedObject(args...);
		m_active = true;
	}

	// Destructs the underlying object if one has been previously constructed.
	void destruct()
	{
		if (m_active)
		{
			(*this)->~ScopedObject();
			m_active = false;
		}
	}


	// Access to underlying object.
	const ScopedObject* operator -> () const
	{
		return reinterpret_cast<const ScopedObject*>(m_memory);
	}
	const ScopedObject& operator * () const
	{
		return *reinterpret_cast<const ScopedObject*>(m_memory);
	}
	ScopedObject* operator -> ()
	{
		return reinterpret_cast<ScopedObject*>(m_memory);
	}
	ScopedObject& operator * ()
	{
		return *reinterpret_cast<ScopedObject*>(m_memory);
	}

	// Weather the underlying object is constructed or not.
	operator bool() const
	{
		return m_active;
	}

private:
	char m_memory[sizeof(ScopedObject)];
	bool m_active;
};

Usage:

void somethingProbablyUnsafe(ThreadingLock* lock)
{
    // unrelated code
    // ...

    OptionalScopedObject<ScopedLock> scopedLock;
    if(lock)
    {
        scopedLock.construct(*lock);
    }

    // Complicated code with early outs.
    // ...
}

Scoped thread locks are of course only an example. The template can be used with any kind of scoped object that may or may not be required.

All this almost let forget you about the simple solution: Your scoped object should take a pointer and it should handle null. (yeah, I forgot about that myself when I had this whole idea, thank you for pointing that out to me @ Christopher)

New Sideproject, C# Engine?

Motivation

Since I am now slowly getting settled down again after moving to Dublin, I have recently been thinking about starting a new side project. Doing side projects is a very natural hobby for me that allows me to play freely with ideas and gives me that cosy feeling of steady progress.
First, I thought about continuing with global illumination research (which I did in my master’s thesis) or helping out my friends at the amazing ezEngine. However, I realized that it might be fun to experiment with general infrastructure myself – something that I haven’t done for a long time. While the past showed me that I tend not to reuse code directly, there are many pieces of code in my archive that get recycled and improved in other projects – so it could be also useful for spin-offs etc.
My job involves mainly C++ coding atm, so I would rather use something else: I was tempted to use the Rust language but I am just too much in love with IDEs to try a large project with a fancy new language (note to myself: Blog about experiences with Rust). Instead I decided to go with an old friend of mine: C#

C# Pro/Cons

Personally, the biggest pros are the great IDE support (ReSharper makes it even better) and the lush standard library. Practically all engines I have seen so far have a huge Core of basic functionality for containers, threads/tasks, SIMD math, file access and so on. In .net there is already a lot of this stuff; 4.6  has even basic SIMD support, a work stealing task scheduler and the async functionalities are just a amazing! Don’t take me wrong, writing all this by hand can be a joy on its own, but I am just not in the mood for it ;).
Also, I have to admit that I just love some of the syntactical sugar of C#, e.g. properties, lambdas, events, …

On the other hand the garbage collector can strike at any time and can make it difficult to manage resource & lifetimes by hand where it is necessary (textures, buffers, but also high-level game resource management).  Another con from my point of view is that I already now quite a bit about C#/.Net stuff which makes the whole matter a bit less interesting. On the other hand, recent versions introduced some cool stuff. Cross-Platform support is getting with Microsoft’s more recent open source initiatives really good, but I am still sceptical.

Things to try

A loose list of a few interesting things to which I look especially forward to investigate and experiment with during this project:

  • Modern multi-threaded renderer abstraction
    • Support for DX12, Vulkan but also OpenGL 4.5 (to prove the concept and make it work on my laptop)
    • might be necessary to keep the lowest abstraction level relatively high
    • Molecule Matters has a great series about this topic with many super interesting ideas. Can’t wait to try all this in C# 🙂
  • Resource system/manager
  • Component Entity systems
    • Especially interesting in the context of .net reflection stuff
  • Unit-testing in .net
  • Modern Scenegraph
  • Run on Linux without Mono
  • Make a WinRT application

Of course there will be also a lot of seemingly less exiting things that still might be fun, but to which I haven’t given much thought yet. For example logging, messaging, special data structures, etc.

Next, I will have a look at existing engines and start then experimenting & planning with the general project structure. While .net offers already a lot of stuff I will probably still need some kind of base library. As always, I will make everything public on GitHub.

To be continued! 🙂