Brick4 in week 10
Well, the major glitches in the building creation system are finished. The graphics also look nice now. Anyway a picture says more than a thousand words in this case.

“Ordered Programming” Technique
When it comes to programming there many, many techniques. One of the techniques I tried is ordered programming. The idea behind it is that quality is assured and nothing can be forgotten. While I was rewriting Brick I decided to use this technique. What it basically does is that you write a “TODO” in the code, for example: “Load configuration file”. And when you run the application in debug mode, it will break when it arrives at that point.
As you can see this has one huge disadvantage and that is that in order to run the entire program all the “TODO” have to be resolved. There is also one huge advantage which is that after you have done something, you will change “TODO” in to “DONE”. The next time you go trough your application, you will notice that the code has now been documented. This is a huge advantage when you write large pieces of code, which you will rarely though in the near future.
However the disadvantage, having to program in the order that the program runs might be too big in some cases. For example some features will be added later as they are not needed now. For example you have written a OBJ loader that handles triangles, but not quads, in this case you might not want to write the quad loading code just yet as you have to focus on the rendering part. For that reason I have decided to add levels, the lower the level the higher the priority. You can think of it in terms as first todo, second todo, etc. If you reach a stage in your development, where you have done all first todo’s, you just increase the number and see where it breaks then.
Here is an example of how it looks when you are writing todo’s.
[cc_cpp]
#include "OrderProgramming.hpp"
int main(int argc, const char** argv)
{
ORDER_PROG_TODO("Setup Memory Checkpoint", 0);
ORDER_PROG_TODO("Initialize graphics engine", 0);
ORDER_PROG_TODO("Run the game", 0);
ORDER_PROG_TODO("Shutdown the graphics engine", 0);
ORDER_PROG_TODO("Check if there are memory leaks", 0);
}
[/cc_cpp]
And here how it looks at a later stage
[cc_cpp]
#include
#include "OrderProgramming.hpp"
class IGraphics;
IGraphics* InitGraphicsEngine();
void GameFunction(IGraphics* graphics);
int main(int argc, const char** argv)
{
_CrtMemState memstate;
_CrtMemCheckpoint(&memstate);
ORDER_PROG_DONE("Setup Memory Checkpoint", 0);
IGraphics* myGraphics = InitGraphicsEngine();
ORDER_PROG_DONE("Initialize graphics engine", 0);
GameFunction(myGraphics);
ORDER_PROG_DONE("Run the game", 0);
if(myGraphics)
delete myGraphics;
ORDER_PROG_DONE("Shutdown the graphics engine", 0);
_CrtMemDumpAllObjectsSince(&memstate);
ORDER_PROG_DONE("Check if there are memory leaks", 0);
}
[/cc_cpp]
And here is the header you will need to include:
[cc_cpp]
// OrderProgramming.hpp
// Generic functions can be defined before inclusion
// - ORDER_PROG_DEBUGBREAK: Breaks the process if possible
// - ORDER_PROG_ASSERT: Tries to assert a function
// - ORDER_PROG_OUTPUT: Debug output function
#ifndef __ORDER_PROGRAMMING_HPP__
#define __ORDER_PROGRAMMING_HPP__
#define ORDER_PROG_STRINGIFY(x) #x
#define ORDER_PROG_TOSTRING(x) ORDER_PROG_STRINGIFY(x)
#define ORDER_PROG_FILE __FILE__
#define ORDER_PROG_LINE ORDER_PROG_TOSTRING(__LINE__)
#define ORDER_PROG_HERE ORDER_PROG_FILE"("ORDER_PROG_LINE") : "
#ifndef ORDER_PROG_DUMMY
# define ORDER_PROG_DUMMY() {(void)0;}
#endif
// Lower than this level will cause the order to be taken in account
#ifndef ORDER_PROG_LEVEL
# define ORDER_PROG_LEVEL 1
#endif
#ifndef ORDER_PROG_DEBUGBREAK
# if defined(_WIN32)
# include
# define ORDER_PROG_DEBUGBREAK __debugbreak();
// # elif (???)
# else
# define ORDER_PROG_DEBUGBREAK {__asm{int 3};}
# endif
#endif
// Platform independent (most of the time)
#ifndef ORDER_PROG_ASSERT
# include
# define ORDER_PROG_ASSERT(expression) assert(expression);
#endif
// Platform dependent
#ifndef ORDER_PROG_OUTPUT
# if defined(_WIN32)
# include
# define ORDER_PROG_OUTPUT(output) OutputDebugStringA((output));
//# elif (???)
//# define ORDER_PROG_OUTPUT(output) ::std::clog << (output);
# else
# define ORDER_PROG_OUTPUT(output) ORDER_PROG_DUMMY()
# endif
#endif
#ifdef ORDER_PROG_NOBLOCK
# define ORDER_PROG_BLOCK(reason) ORDER_PROG_DUMMY();
#else
# define ORDER_PROG_BLOCK(reason) ORDER_PROG_ASSERT(0 && (reason))
#endif
#define ORDER_PROG_TODO(reason, level) { if((level) < ORDER_PROG_LEVEL){ ORDER_PROG_DEBUGBREAK; ORDER_PROG_BLOCK(reason) } }
#define ORDER_PROG_TODO0(reason) ORDER_PROG_TODO(reason, 0);
#define ORDER_PROG_DONE(reason, level) { if( (level) < ORDER_PROG_LEVEL) { static bool _once=true; if(_once) { ORDER_PROG_OUTPUT(ORDER_PROG_HERE); ORDER_PROG_OUTPUT(reason); ORDER_PROG_OUTPUT("\n"); _once = false; } } }
#define ORDER_PROG_DONE0(reason) ORDER_PROG_DONE(reason, 0)
#endif // __ORDER_PROGRAMMING_HPP__
[/cc_cpp]
Learning Java
Recently I had a small discussion with a friend about what language he should choose for a personal project of him. He was doubting between Visual Basic and C#. I believe he decided to go with C# as that would be compatible with Mono (a cross platform variant of C#) and well, an other reason was that is another language the he normally used.
Personally I don’t like working in VB as it has some, not quirks, but behavior issues that don’t match my style of programming (Comments are done different for one).
I do like C# a lot as it looks like C++ (call me shallow if you want), but I have worked in that language for quite some time at my previous job and I found that the Graphical User Interface used by Windows (.NET components) to be a little bit lacking. Now I could buy a professional components (like Devexpress) but I’m not that rich and frankly my experience with it has not yet been enjoyable, most likely because I’m still getting used working with (at my job).
Recently my interest in Linux has been rekindled thanks to Linux Mint and I decided that if I’m going to write software I don’t wish to be limited to one platform. By the way, I only share this view as a software developer and not as a game developer.
After some thinking I decided to try out Java. The criticism that I had about Java 6 years ago have all been gone, so I decided to check it out again.
I have been playing around with it that past three days (1~2 hours each day) and I’m enjoying. Eclipse is an awesome IDE and the only thing I really find lacking is the fact that I can’t drag and drop components as it is done in VS2008. Not that I mind because creating a form (a shell in Java) is quite easily done. I still have a lot of thinking to do about the application I want to write (it’s one of those applications you try to write from time to time) and see if I can actually get it to work.
The programmer IDE
Everyone in the game industry knows the console wars (also because it is a recurring war
) but not many know about the editor war. The editor war was a war that played between two major editors (mostly available on Linux) which were vi and Emacs.
When I look at how code is written I always find myself a bit annoyed as the IDE (Integrated development environment) is basically nothing more than notepad with some extra features. Nothing wrong with notepad or the many IDE’s out there.
But I have always thought that code has one major weakness: Code is always written in a linear fashion. This is not inherent to only code, but a facet of how language works. In the majority of the languages we write from left to right and then from top to bottom. Some languages write in a different order, but always in one direction and then in the other.
I have always wondered why this has to be. Ok, I admit the fact that code is often a language (Like for example C++) but most languages have features like branching (if-else for example), and sub functions.
Recently I came across “Code Bubbles” and honestly I love it, it’s because I’m not a Java programmer pure sang (I did Java a long time ago), but this wants to me to make Java my primary language. Anyway here is a screenshot which demonstrates and I think any developer would applaud this.
Brick3 has become Brick4
Brick3, my graduation project, will be no longer developed and instead I will be working on Brick4.
The reason I abandon Brick3 is because the system has become too hard to maintain and there are too many pieces of legacy code around for me to quickly improve it. On top of that Brick3 was the first incarnation of the Brick project series in 3D with some advanced features, the new way of memory management (a 37 MB instead of 2 GB). So I had expected I would need to rewrite it, even though I wanted to avoid it.
Brick4 will have unlike its predecessor cleaner code a new way to some things (XML instead of custom file formats) and it will make heavy use of the command and strategy patterns. This will allow me to developer faster and safer in the long run, although I fear that rewriting the application will have an heavy cost and that any advantage I gain will be lost to that.
The good is that this will allow me to revisit some off the old features and make some notes and see if I can improve it.
If I’m lucky everything should be rewritten at the end of this week and with even some more luck I will also have implemented a new feature. Guess time will tell.
Custom exceptions
Besides finishing my study I'm currently also working as a software developer. And yesterday I came across a problem which thought me how a lesson.
The project I was working is basically a custom import tool for a financial software. We get an CSV or an XML file and that is imported using the SDK of the financial software. Nothing hard except that the SDK is unfinished and various features are yet to be implemented. The majority does work, but it is like walking through a mine field and every time you move forward the application might blow up in your face
The application is written in Visual Basic .NET (not my choice, but it does the job) and the SDK uses exceptions to notify that a certain feature is not working or when a certain object doesn't meet certain requirements when you ask it to be saved.
Because of the huge amount of data, I used reflection so that I don't have to type as much. My system also uses exceptions, and I won't be surprised if you already where this is going, but while I was debugging I came across multiple exceptions of the SDK which meant that I either had to write a workaround for it or remove the feature until the SDK does support it. When I finally fixed the majority of the errors I suddenly got hit in the face by the following exception:
[cc_text]Unable to complete save[/cc_text]
Now the SDK did provide cryptic error messages but this one was completely new and I was doing a bare bone test. I called a coworker over to see if he knew what it meant but he also didn't know what the message meant. A few minutes later he came back to me and said that the part of the SDK did work on his side and that the error must be somewhere in my code.
To cut a long story short. The exception that I got was my own and I hadn't noticed because I had already encountered so many exceptions of the SDK that I just presumed that it was again the SDK that was throwing a fit.
Once I realized that it didn't take long to solve it (I returned a true instead of false somewhere), however I was more worried about how to prevent it in the future. After some thought that also was simple.
If any of the application code would throw a fit it would throw not the standard exception which would have been:
[cc_vb]throw new Exception("Unable to complete save")[/cc_vb] but a custom type and a search and replace later we got:
[cc_vb]throw new UtilityException("Unable to complete save")[/cc_vb] so that error message would contain a special prefix by which it would be clear that it was our own code that decided to throw an exception.
[cc_vb]
Public Class UtilityException
Inherits System.Exception
Public Sub New(ByVal str As String)
MyBase.new(str)
End Sub
Public Overrides ReadOnly Property Message() As String
Get
Return "UtilityException: " & MyBase.Message
End Get
End Property
End Class
[/cc_vb]
In the future we will know when it was our own mine to blew up. A simple solution but it would have saved us a lot of time if we had done this from the start.
Undesired template specification
Updated 10 January 2010: The download was not working, this is now fixed
Yesterday I decided to improve my math library and to make it more flexible. One of the things that I wanted to do was convert it to a template, so that I could easily make vectors of different types. However when it was finished and I started testing it I came across a lot of issues which my old math library didn't have. The reason that my old library didn't have them was because all of the structures used floats and when used with any other variable type would be automatically be casted, promoted or demoted to match the type float. However templates are more strict on that area since templates need to specialize. I know this is confusing so let me explain by example.
I will show three examples of the above problem and I will explain how to solve any of them. I hope that throughout the progress you will also understand why the problems happen.
But first let me define the class that I use. This piece of code won't change until I cover the solution of the third problem.
The Vector2 class:
[cc_cpp]
template
{
public:
T X, Y;
tVector2(T x, T y) : X(x), Y(y) {}
// Assigrnent operator
tVector2
};
// Multiplication operator
template
[/cc_cpp]
FIRST PROBLEM: ONLY A SINGLE TEMPLATE ARGUMENT
The first problem shows itself rather fast.
[cc_cpp]
int testMain1() // Think of this as a normal main
{
tVector2
Vec2 = Vec2 * 2.0f; // Does compile
Vec2 = Vec2 * 2.0; // Does not compile
return 0;
}
[/cc_cpp]
Visual Studio comes with two errors:
[ccWN_text]error C2782: 'tVector2
error C2676: binary '*' : 'tVector2
If we think about the reason for this problem is rather easy. If we would think as the compiler we would have the following two forms of multiplication:
[cc_cpp]
tVector2
tVector2
[/cc_cpp]
The first multiplication in the example does compile as it makes use of the first form, the second multiplication in the example however raises two errors. As you can see neither form can be applied on our multiplication, which has the form [cci_cpp]tVector2
The second error comes forth because the compiler still tries to solve. However it cannot convert [cci_cpp]tVector2
[cc_cpp]
void TestFunction(float v);
void TestFunction(double v);
int main()
{
TestFunction(2.0f); // Use first form
TestFunction(2.0 ); // Use second form
return 0;
}
[/cc_cpp]
FIRST SOLUTION: USE MULTIPLE TEMPLATE ARGUMENTS
The title of the first solution might feel contradicting as [cci_cpp]tVector2
[cc_cpp]
template
tVector2
return tVector2
}[/cc_cpp]
The biggest change is that because of using two template arguments, which are used for the first and second argument, is that compiler no longer have to match the types. So the compiler can generate the following:
[cc_cpp]
tVector2
tVector2
tVector2
[/cc_cpp]
And the everything works. You can even remove the old multiplication method if you want.
SECOND PROBLEM: MULTIPLYING DIFFERENT TYPES
This problem is exactly the same as the first one, but I cover it none the less as it took me a few seconds more to realize this than I wanted.
[cc_cpp]
int testMain2() // Think of it as a seperate program
{
// Second problem: Multiplying different types
tVector2
tVector2
Vec2d = Vec2d * Vec2; // tVector2
return 0;
}[/cc_cpp]
When we compile this visual studio comes two times with two different errors (total is four):
[ccWN_text]error C2784: 'tVector2
error C2677: binary '*' : no global operator found which takes type 'tVector2
The errors all take place in the solution of the previous problem as it tries to solve that function in to the following form:
[cc_cpp]tVector2
return tVector2
}[/cc_cpp]
I have added on purpose also the body of the form because that is what you should concentrate on. As you can see it tries to multiply [cci_cpp]v.X[/cci_cpp] with [cci_cpp]r[/cci_cpp]. While [cci_cpp]v.X[/cci_cpp]is a float, which is correct. [cci_cpp]r[/cci_cpp] is of the type [cci_cpp]tVector2
SECOND SOLUTION: USE MULTIPLE TEMPLATE ARGUMENTS WITH TYPES
Similar to the first problem we add the following function:
[cc_cpp]template
tVector2
return tVector2
}[/cc_cpp]
There is however one down side to this solution and that is that type returned is the same as the first template argument, even if the second template argument would be bigger. For example the first template argument is a float and the second is of the type double. In that case we would lose precision.
THIRD PROBLEM: CONVERTING FROM ONE TYPE TO ANOTHER TYPE
The test case is similar to that of the second problem, but with a little change.
[cc_cpp]int testMain3() // Think of it as a seperate program
{
// Third problem: Storing different types
tVector2
tVector2
Vec2d = Vec2 * Vec2d; // tVector2
return 0;
}[/cc_cpp]
As you can see the result of the multiplication is now [cci_cpp]tVector2
However unlike the solutions of the first two problems, this operator needs to be a member function. So we should store a tVector of a unknown type in a tVector of a specialized type (which is actually also unknown, but the compiler specializes this so it is known to him, but not to us).
THIRD SOLUTION: TEMPLATE FUNCTION INSIDE A TEMPLATE CLASS
To be honest, I didn't think this was at all possible but since I had solved the previous two problems I was intended to find a solution for this one as well. In retrospect the solution was just as simple as the previous one, but then again everything seems easy in retrospect.
The new class looks as followed:
[cc_cpp]template
{
public:
T X, Y;
tVector2(T x, T y) : X(x), Y(y) {}
// Assigment operator (didn't solve the third problem)
tVector2
// Assigment operator which allows other types (solved third problem)
template
X = v.X, Y=v.Y; return *this; }
};[/cc_cpp]
As you can see a new function has been added, which is a template function. Quite a simple and elegant solution once you accept the fact that you are allowed to create template functions inside a class as well.
FINAL WORDS
Although the title of the article is "Undesired template specification" it was only how I felt when I encountered all these problems. Afterwards I think it was not undesired at all, because this is how the language should work. If it wouldn't work like this we would barely have control what some of the functions would and then it would really become undesired.
I hope that the all of the above was easy enough to follow (assuming you are familiar with templates) and helped you understand in what went wrong and how to solve it.
As usual I have added the full source code at the bottom of the article. All the functions are in it, however in a production environment I would recommend you remove the old versions of some of the functions since the new functions also cover the functionality of the old ones.
Source code: templatetest_0.zip (2 kb)
Donuts! (Procedural Torus in C++)

Recently I got a mail through the contact form of my website about texture mapping on torus (a donut) who said that [cci_cpp]D3DXCreateTorus[/cci_cpp] didn't not provide texture coordinates. The reason why DirectX and OpenGL (and GLUT) don't provide texture coordinates with these function is best seen when you generate a cube. A cube has 8 vertices, however when you add texture coordinates it will increase because otherwise they will share the same texture coordinate. With normals it is no problem (in fact you would prefer that) but if you have a dice (from 1 to 6) than each vertex would use a single texture coordinate for three sides. Just draw an unfolded dice on paper where each edge is connected, but does not cross another edge. It is simply not possible. These complexities are the reason why those procedural mesh functions are so simple. Adding these functionalities would increase complexity of the function and requires you to explain it. On top of that the developers have no idea how you are going to use that function. Maybe you don't want to use the legal texture range [0...1] but [0...3].
Anyway I have decided to take it on and here is the result. You can download the source code here: TorusDX.zip.I have not commented it, but it is pretty straight forward. The texture that I used is from Dilbert.
Random distribution
One of the special effects I recently worked one was cellular noise (original made by Steve Worley) and the book that I read used Poisson distribution. The Poisson distribution is a table which holds random values that guarantees certain conditions (like an average mean). However I’m not going to talk about Poisson distribution, it just remembered me of some old error I made and how I finally solved it. Besides there are better sources than me who can explain the math behind it.
But first a talk of a prehistoric me talking about some game that I worked on.
One of the games that I worked on as a student was a shooter like Tyrian but then in 3D. You would race around in hovering car through a fixed path in a 3D city and you would shoot down enemy cars. Since the path was a circle, you would go around and around until you were death, you could jump from one car to another and that was pretty cool to see (and made the game quite easy if you knew the timing). However some cars would be rare to encounter because they had better armor or better weapons and we needed fact in the spawning code. I made up some kind of obscure code for it that based on random number and a “common” value would spawn one of the cars. Before I started on it I thought it wouldn’t be too hard. But this is one of the times I was actually wrong. It worked to some degree but I noticed that some cars were rarely spanned, even though they had a high “common” value. The problem was obvious in the code I had written but at that time I couldn’t think of an algorithm that would solve this issue.
Ok, enough history, let’s go back to the future.
By now I have worked on a lot more of code and when I read how Poisson distribution is used, which is properly how more distribution work, I noticed it was similar to what I once invented.
So to illustrate the problem I will try and remember and describe what I used for that game.
We could use [cci_cpp]rand() % MAX_CAR_ID[/cci_cpp] to generate a lot of random numbers so that we have a list of cars that we use for the game. Using [cci_cpp]std::vector
A better method is using two lists. The first list contains all the values we want to have like for every Saab there are five Fords, then we would add the ID of a Saab once and then we add the ID of a Ford five times. Problem with this list is that the numbers are ordered or are in a way ordered. We could still use [cci_cpp]CarSpawnList[rand()%ListSize][/cci_cpp] but if we have a bad seed we could still have three Saabs before we encounter a ford.
So let’s introduce the second list. The second list will start empty and we move every item in the initial list to the second least. So we remove it in the first list and add it to the second list. The item chosen in the first list is random and because it is removed we will make certain that the Saabs and Fords balance each other. In code it would look something like:
[cc_cpp]
#define CAR_SAAB_ID 1
#define CAR_SAAB_MAX 1
#define CAR_FORD_ID 2
#define CAR_FORD_MAX 5
#define CAR_MAX_ORDER 1
void FullListRandom()
{
std::vector
std::vector
for(int i = 0; i < CAR_SAAB_MAX * CAR_MAX_ORDER; i++)
lInitialList.push_back(CAR_SAAB_ID);
for(int i = 0; i < CAR_FORD_MAX * CAR_MAX_ORDER; i++)
lInitialList.push_back(CAR_FORD_ID);
// now create the final list
while(lInitialList.size())
{
int CurId = rand() % lInitialList.size();
lFinalList.push_back( lInitialList[CurId] );
lInitialList.erase( lInitialList.begin() + CurId );
}
};
[/cc_cpp]
Of course you have to put [cci_cpp]lFinalList[/cci_cpp] somewhere more global, I just wrote this code for this post, but if you increase [cci_cpp]CAR_MAX_ORDER[/cci_cpp] then you can prevent a repeating pattern. If you would think of [cci_cpp]lFinalList[/cci_cpp] as circular list (meaning, once you reach the end you start over) this will provide a quite good and consistent distrubution.
By now the above method is common knowledge for me and it is rather simply once you know how to do it.
References
CrayonToon Shader WIP
Just showing off some work in progress
| Normal toon shader | Normal toon shader with cross hatching |
|---|---|
| ![]() |
Click on either image to see a large scale version of it.
The right picture is the same as the left image, but before I apply outlining I have (ab-)used my own cross-hatching algorithm.


