Codesnippet: Poor man’s benchmark, or quickly timing things in C#

For a project I’m working on I had to do some quick timing. Now manually working with DateTimes and TimeSpans isn’t hard but I had to do a lot (e.g. more than 3) timings inside a bigger process and I wanted to know both the time the entire process took as the time parts of the process ate up. For this I created a handy StopWatch class which uses a stack to store different date times so you can easily do nested timing with very little code. This is nothing revolutionary but I thought I’d share it anyway. Its those little things that safe some time that are the nicest!

/// <summary>
/// Always accesible timing apparatus
/// </summary>
public static class StopWatch
{
	private static Stack<DateTime> timers;

	static StopWatch()
	{
		timers = new Stack<DateTime>(0);
	}


	/// <summary>
	/// Pushes the current DateTime onto the stack of timers
	/// </summary>
	public static void Push()
	{
		timers.Push(DateTime.Now);
	}

	/// <summary>
	/// Pops the top DateTime from the stack of timers,
	/// returns the TimeSpan between when the last Push and now
	/// </summary>        
	public static TimeSpan Pop()
	{
		if(timers.Count > 0)
		{
			DateTime start = timers.Pop();
			return DateTime.Now - start;
		}
		else
		{
			throw new Exception("Trying to pop while the stack is empty");
		}
	} 

	/// <summary>
	/// Calls Pop(), then prints the text "StopWatch: {totalSeconds} \n"
	/// directly to console.
	/// </summary>
	public static void PopAndPrint()
	{            
		Console.Out.WriteLine("StopWatch: " + Pop().TotalSeconds);
	}
	
	/// <summary>
	/// Returns the TimeSpan between the last Push and now
	/// without popping the TimeSpan from the stack of timers
	/// </summary>        
	public static TimeSpan Peek()
	{
		if(timers.Count > 0)
		{
			DateTime start = timers.Peek();
			return DateTime.Now - start;
		}
		else
		{
			throw new Exception("Trying to peek while the stack is empty");
		}
	}

Usage

static void Main(string[] args)
{
	// Measure the entire process
	StopWatch.Push();
	{
		// Measure subtask            
		StopWatch.Push();
		
		// Subtask took:
		StopWatch.PopAndPrint();
	}
	// Entire process took:
	StopWatch.PopAndPrint();
}

Output

StopWatch: 0.0010001
StopWatch: 0.0020001
04
Jun 2014
COMMENTS No Comments

2D Lighting and Shadows Preview

While I’m finishing up my master’s degree studying Navigational Meshes and Path Finding I spent some of my free time with a friend developing a prototype for a game. Because we’ve been working on this for a while I thought it would be time to spice up the graphics a bit. During the last two weeks I developed a cool looking 2D lighting and shadowing technique that is much akin to deferred rendering.

I hope I can find the time to convert my test-code into a tutorial but for now you’ll just have to make due with this awesome videos, a few references and the source code (C# / XNA)

(Or follow this link for the 720p version)

References:

Red BloB Games on 2D Visibility

Catalin Zima on 2D lighting and smooth shadows

Source Code:

Available here

27
Feb 2014
CATEGORY

Blog, Programming, XNA

COMMENTS 1 Comment

Building SDL on Windows for use with Haskell / Cabal

If, like me, you wish to perform graphical operations with Haskell you need a library like SDL. Unfortunately most of the Haskell world resides in Linux so it is pretty hard to find good guides for Windows. This guide describes my endeavor to get things working.

I’ll assume that you have nothing installed yet, so you might be able to skip some of these steps.

1. Install the Haskell Platform

You can get it from http://www.haskell.org/platform/ and it will include most of what you will need to work with Haskell on Windows (or any other platform). Installation is as easy as double clicking the installer.

2. Install the MinGW-MSYS tool chain

In order for Cabal (a distribution-manager like apt-get but then just for Haskell) to be able to build packages that have no native Windows libraries we need a Linux like tool chain for Windows.

  • Download the MinGW installer from http://www.mingw.org/wiki/Getting_Started (in the middle of the page there is a blue link to  mingw-get-setup.exe)
  • Run the installer, for legacy reasons install it in a path that does not contain spaces. I’ll asume for now that you’ve installed it in C:\MinGW
  • During the end of the installation a package manager will show. Install the meta package MSYS and click apply changes in the menu.
  • Add C:\MinGW\bin\, C:\MinGW\, and C:\MinGW\msys\1.0\bin\ to the PATH environment variable

3. Install the SDL development libraries

Now we need to install the SDL development libraries and add them to the PATH variable so that the Haskell implementation can link and build.

  • Download the SDL-devel-1.2.15-mingw32.tar.gz archive from http://www.libsdl.org/download-1.2.php and extract. I’ll assume it is located in C:\SDL
  • Add C:\SDL\, and C:\SDL\bin to the PATH environment variable

4. Build Haskell’s SDL implementation

Ok final steps!

  • Open a command prompt
  • Run  cabal install SDL –extra-include-dirs=C:\SDL\include –extra-lib-dirs=C:\SDL\lib
  • This operation should complete with the message ‘Installed SDL-0.6.5′

5. In Conclusion

Building things with Cabal is quite a hassle especially since it uses both the PATH variable and explicitly given paths to find all dependencies, error messages are not to clear either. I hope this guide helps you and saves you some time as it took me two days to get this exactly right. If you wish to see if all really works why not try building and running this little program, it is the reason why I went trough all the steps to get SDL working. (Just left-click and drag to create a rectange, middle click to change the color, and right click to finish the rectangle).

Note: I am aware that the Haskell Platform includes its own version of MinGW but it does not include the MSYS library which is vital under Windows. It is also not easy to modify the built in version of MinGW and according to the docs the build in version can live happily together with the stand alone version.

16
Jan 2014
CATEGORY

Programming

COMMENTS 5 Comments

LUA Syntax highlighting in Visual Studio 2012 and Visual Studio 2013 (Preview)

Lately I’ve been working a lot with LUA and C++ code. As usual I’ve been using Visual Studio and it hindered me that there was no syntax high-lighting and that on Google I couldn’t find any up to plug-in that worked in VS 2012/2013 (yeah I’m working on the cutting edge at the moment.

After a lot of searching I found this post, I then figured out that VSIX files are just plain zip files with XML and other data stored inside. After some tweaking I present you 2 Visual Studio plugins. One for 2012 and one for 2013 (preview) that adds proper syntax high-lighting.

Download the Visual Studio 2012 and 2013 Version (zipped)

(Update 2: Some users were still not able to download the files because the VSIX files were interpreted as XML, so I’ve uploaded a zip file instead that contains both files)

04
Sep 2013
CATEGORY

Blog, Programming

COMMENTS 8 Comments

Internship at Abbey Games

The next couple of months I will be interning at Abbey Games the creators of the highly successful game REUS. I’ll be working on technology for their ‘next big thing’ which I can’t talk about yet because even I don’t know what it is going to be :). I hope to be able to do an ‘internship post-mortem’ after I’m done where I can at least showcase a bit of what I’ve worked on.

REUS

12
Aug 2013
CATEGORY

Blog

COMMENTS 1 Comment

Darkest of Games

So a friend of mine, let’s call him Red, has been bugging me to create a Let’s Play series together. Two weeks ago we finally decided on a game. The very mediocre shooter ‘Darkest of Days’ (though it really has some potential). The first two episodes are up, and we’re trying to keep a schedule where we upload a video every Thursday and Sunday. As this is our very first youtube series we had no idea how to do a lot of things. For example we wished we started with a game that’s more fun :P! Anyway let us know what you think of it, and please subscribe to stay up to date!

Channel: http://www.youtube.com/channel/UCrFTsO-Z-gKRvdvD1Eb0y9w

Episode 1

Episode 2

Can you guess which voice is mine ;)

09
Jul 2013
CATEGORY

Blog, Personal

COMMENTS 4 Comments

A Self Balancing Creature

I’ve been finishing up the last few courses for my MSc degree (next year I will fully devote to research). This means that I didn’t have time to create original content for this blog. But for one of the courses (Master Level Game Physics) by Nicolas Pronost I created a self balancing creature. This was quite a cool project so I’d like to share the video with you guys.

The creature keeps balance by trying to keep the center of mass above the center of support. This is done by feeding the joint errors into PID-Controllers. The gains for the PID-Controllers were found using a self-learning algorithm (based on Simulated Annealing). The simulation also contained a muscle-actuated version (not shown in the video).

We used the Bullet Physics Engine to make this all work, however I cannot really recommend it. The documentation is horrid and we encountered a few very nasty bugs regarding joint constraints and motors.

29
Jun 2013
CATEGORY

Blog

COMMENTS No Comments
TAGS

Post-Complement Color Grading

A friend of mine was having problems implementing NVIDIA’s Post-Complement example. The example code was littered with unnecessary garbage, probably created by a cross-platform shader generator/compiler. So to make it more clear what the method does I quickly rewrote it and I thought I would share it. It took much more debugging than expected since apparently not all RGB2HSV converter code is equal. Luckily, in the end, everything seems to work.

So basically just dump the below code in a shader and call PostComplement before you return from the pixel shader to apply a form of colour grading that makes the guide colour pop-out by shifting colours that are close to the guide colour closer to it and colours that are far away from the guide colour to the complement of the guide colours. (Remember those Blue-Orangy movie posters, that’s basically what you can do with this effect if you make the guide colour orange).

Color Grading - Steve Mata
(Image by Total Commitment Games Effect at a not too subtle setting to clearly show the difference)

Note, the code is now tested and seems to work correctly, a previous version which was up for about 2 hours contained a nasty bug.

// Post Complement method
// http://developer.download.nvidia.com/shaderlibrary/webpages/shader_library.html#post_complements

// RGB to HSV and HSV to RGB methods
// from http://www.chilliant.com/rgb2hsv.html
float RGBCVtoHUE(in float3 RGB, in float C, in float V)
{
    float3 Delta = (V - RGB) / C;
    Delta.rgb -= Delta.brg;
    Delta.rgb += float3(2,4,6);
    // NOTE 1
    Delta.brg = step(V, RGB) * Delta.brg;
    float H;
    H = max(Delta.r, max(Delta.g, Delta.b));
    return frac(H / 6);
}

float3 RGBtoHSV(in float3 RGB)
{
    float3 HSV = 0;
    HSV.z = max(RGB.r, max(RGB.g, RGB.b));
    float M = min(RGB.r, min(RGB.g, RGB.b));
    float C = HSV.z - M;
    if (C != 0)
    {
        HSV.x = RGBCVtoHUE(RGB, C, HSV.z);
        HSV.y = C / HSV.z;
    }
    return HSV;
}

float3 HUEtoRGB(in float H)
{
    float R = abs(H * 6 - 3) - 1;
    float G = 2 - abs(H * 6 - 2);
    float B = 2 - abs(H * 6 - 4);
    return saturate(float3(R,G,B));
}

float3 HSVtoRGB(float3 HSV)
{
    float3 RGB = HUEtoRGB(HSV.x);
    return ((RGB - 1) * HSV.y + 1) * HSV.z;
}

float3 HSVComplement(float3 HSV)
{
    // X = Hue, so rotate it for the complement
    float3 complement = HSV;
    complement.x -= 0.5;
    if (complement.x < 0.0) { complement.x += 1.0; }
    return(complement);
}

// Lerps 2 hue values, since they are on a circle
// in HSV we need some weird code for that
float HueLerp(float h1, float h2, float v)
{
    float d = abs(h1 - h2);
    if(d <= 0.5)
    {
        return lerp(h1, h2, v);
    }
    else if(h1 < h2)
    {
        return frac(lerp((h1 + 1.0), h2, v));
    }
    else
    {
        return frac(lerp(h1, (h2 + 1.0), v));
    }
}

float3 PostComplement(float3 input)
{
    // Tweakable values
    float3 guide = float3(1.0f, 0.5f, 0.0f); // the RGB colour that you want to 'bring out'

    float amount = 0.5f; // influence how much a colour gets lerped toward the guide or complement

    // Correlation and Concentration together define a curve along which the colour grading is done
    // tweak these values to see the effects, I think correlation should be < 0.5f and concentration should     // be > 1.0f, but I havent double checked that math
    float correlation = 0.5f;
    float concentration = 2.0f;

    // Convert everything to HSV
    float3 input_hsv = RGBtoHSV(input);
    float3 hue_pole1 = RGBtoHSV(guide);
    float3 hue_pole2 = HSVComplement(hue_pole1);

    // Find the difference in hue, again hue is circular so keep it in a circle
    float dist1 = abs(input_hsv.x - hue_pole1.x); if (dist1 > 0.5) dist1 = 1.0 - dist1;
    float dist2 = abs(input_hsv.x - hue_pole2.x); if (dist2 > 0.5) dist2 = 1.0 - dist2;

    float descent = smoothstep(0, correlation, input_hsv.y);

    // *there was a version here that forced it 100% but I skipped implementing that*

    float3 output_hsv = input_hsv;
    // Check if we are closer to the guide or to the complement and color grade according
    if(dist1 < dist2)
    {
        // Bring the colour closer to the guide
        float c = descent * amount * (1.0 - pow((dist1 * 2.0), 1.0 / concentration));
        output_hsv.x = HueLerp(input_hsv.x, hue_pole1.x, c);
        output_hsv.y = lerp(input_hsv.y, hue_pole1.y, c);
    }
    else
    {
        // Bring the colour closer to the complement
        float c = descent * amount * (1.0 - pow((dist2 * 2.0), 1.0 / concentration));
        output_hsv.x = HueLerp(input_hsv.x, hue_pole2.x, c);
        output_hsv.y = lerp(input_hsv.y, hue_pole2.y, c);
    }

    float3 output_rgb = HSVtoRGB(output_hsv);
    return output_rgb;
}

GPU Based Path Tracer

Introduction

As some of you might have seen I’ve been working on a Path Tracer on the GPU. Path Tracing is ray tracing like technique that is (when done right) a physically correct simulation of light. Usually it is done on the CPU but since the work can be easily parallelized and GPUs are getting more powerful, and more programmable it is now feasible to let the GPU do the bulk of the work. I didn’t use Cuda or OpenCL just plain ‘simple’ DirectX 11 with pixel shaders written in HLSL doing most of the work.

Since it is an assignment (which is due in 40 minutes) I can’t share any source code with you. But I would like to show the video and tell you where you can find the resources to build your own.

Video

(Be sure to select the 720P version, but even then the compression has a hard time with the grainyness that path tracing produces. The actually generated image are grainy but look a lot better.)

Image Gallery

Images are clickable.

The Cornell Box Scene

The Cornell Box Scene

Reflectance show-case #1

Reflectance show-case #1

Reflectance show-case #2

Reflectance show-case #2

Reflectance show-case #3

Reflectance show-case #3

Different levels of reflectance

Different levels of reflectance

Depth of Field

Depth of Field

References

The Direct3D 11 Reference
http://msdn.microsoft.com/en-us/library/windows/desktop/ff476079(v=vs.85).aspx

  • Main resource

Wolfram Math World
http://mathworld.wolfram.com/SpherePointPicking.html

  • Sphere Point Picking algorithm #2

GPU Gems 3
http://http.developer.nvidia.com/GPUGems3/gpugems3_ch37.html

  • GPU random number generation

Colors, Effects, Code
http://www.colorseffectscode.com/Projects/GPUPathTracer.html

  • ‘Jitter’ idea for depth of field

The FW1 DirectX 11 Font Wrapper
http://fw1.codeplex.com/

  • This library is used for font rendering

Rastertek.com
http://www.rastertek.com/dx11tut22.html

  • Render Targets
  • Best practices (I recommend the entire tutorial series)

Fundamentals of Computer Graphics, 3rd edition, Peter Shirley & Steve Marschner, 2009
http://www.amazon.com/Fundamentals-Computer-Graphics-Peter-Shirley/dp/1568814690/

  • Miscellaneous math
  • View/Projection/Perspective transformations
  • Inverse transformations
21
Apr 2013
CATEGORY

Blog, Programming

COMMENTS No Comments

Presentation, High Quality Adaptive Soft Shadow Mapping

So I’ve been extremely busy following courses in Advanced Graphics and Multi-modal Interaction. So I haven’t had time to produce content especially for this blog. I would like to write somewhat of a closer/best off for XNA, a tribute for the good times and fun I had with it. But as I said, time is a rare commodity these days. Soon I hope to show you advanced shader voodoo to do path tracing on the GPU. (You might have seen some screen shots on twitter) but since that is also part of an assignment for a course I can’t share it yet.

For now I will just leave you here with a presentation on soft shadow mapping, which uses back projection onto the light source. A very interesting notion I thought.

The presentation can be found here

The original paper can be found here

 

Image by Gaël Guennebaud

Image by Gaël Guennebaud

12
Apr 2013
COMMENTS No Comments