Archive for the ‘Coding’ Category

Fun with dynamic casting

Friday, January 29th, 2010

Polymorphism allows for different function implementations to be called, depending on values only known at run time. For instance:

class BaseA {
	public:
		virtual void foo(){cout<<"Base";};
};

class A: public BaseA {
	public:
		void foo(){cout<<"Child";};
};

A a;
BaseA & base = a;
base.foo();

Will print “Child”.

“Pair polymorphism” is when you want a specific function implementation to be called based on the run time value of two different instances of a class. For instance in the case of:

class BaseA {
};

class BaseB {
	public:
		virtual void foo (BaseA & a) = 0;
};

class A: public BaseA {
};

class B: public BaseB {
	public:
		void foo (A & a);
};

You would want that somehow “void B::foo (A & a)” will be called. The code I posted does not do this.
There is a way to do this, but it requires for a class to know about the implementation classes. It is not a problem in some cases. However, sometimes you want to have an abstraction layer.
An abstraction layer is a set of classes or interfaces, that have no methods or “don’t know” anything about the classes that implement them. For instance you can have a graphics abstraction layer.
You could implement this layer with DirectX. However, this layer will make it easier to afterwards add an implementation with OpenGL without having to make a lot of changes, even if the game is already completed.

How are we going to have a “pair polymorphism” in this case? One solution is using dynamic casting. You can cast a pointer of a parent class to it’s child class(in case the run time value really points to an instance of that class).
Some code:

class BaseA {
};

class BaseB {
	public:
		virtual void foo (BaseA & a) = 0;
};

class A: public BaseA {
};

class B: public BaseB {
	public:
		void foo (BaseA & a)
		{
			foo2 (dynamic_cast<A &>(a));
		}
		void foo2 (A & a);
};

I was asked by someone how this can be done without dynamic casting, because he doesn’t like dynamic casting. I found a way, but it ain’t pretty, and I honestly can’t find any advantage of using this code instead of just using dynamic casting. But here it is:

class BaseA {
	public:
		virtual void DynamicCast() = 0;
};

class BaseB {
	public:
		virtual void foo (BaseA & base) = 0;
};

class A;

class Caster {
	public:
		A * a;
};

class A: public BaseA {
	public:
		Caster * c;
		void DynamicCast()
		{
			c->a = this;
		}
};

class B: public BaseB {
	public:
		Caster * c;
		void foo (BaseA & base)
		{
			base.DynamicCast();
			foo2 (c->a);
		}
		void foo2 (A & a);
};

Out of the box(bug)

Wednesday, January 20th, 2010

When you draw sprites you are thinking in 2D. I was using DirectX’s ID3DXSprite interface to draw sprites. I had to scale up a sprite to cover the whole screen. The sprite can be in different resolutions. If the sprite is quarter the size of the screen, then it needs to scale up by 2.
When I scaled my sprite by 2 everything worked, but when I scaled it by 4 it was not visible. What was the problem?
The sprite draw call gets a 3D position as a parameter, so I passed the x and y I needed and have put 0.5 for the z. I don’t remember why I did that.
It turned out that when I scaled the sprite by 4, it scaled the z component of the position to the value of 2. It meant that the sprite, which is actually a quad, was outside of the viewing frustum.
In the case of the sprites rendering, the viewing frustum is a box of the dimensions [0..Width]X[0..Height]X[0..1]. Anything with a z value greater than 1 will not be visible.

These kind of bugs might be difficult to figure for a beginner, and even for someone who is not a beginner it can waste time. Luckily, once you wrap the DirectX ID3DSprite with some abstraction and after you encounter this bug once, you can protect yourself from the same bug in the future.

Accessing privates without ‘friend’(c++)

Tuesday, January 5th, 2010

Here is a neat little way I found to make one class access the privates of another class, without using friend or direct inheritance. Take a look at this code:

class A {
    public:
        class Observer {
             protected:
                 int GetPrivate(A & a) {return a.ValueA;};
        };
    private:
        int ValueA;
};

class B: public A::Observer {
    public:
        void Foo (A & a) {
             cout<<GetPrivate(A);
        }
};

 

Class B cannot access the privates of class A directly, but it inherits a subclass of A that can access the privates of A given as a parameter. Since I have just tried this “pattern” recently, I am not sure what is the direct benefit of this.

I believe a benefit can be in the sense of making a programmer’s life easier. Programming languages play several parts. They provide us powerful functionality, but they also suppose to give us ease of use. You can program anything on assembly, but it would be really difficult to write a big game in assembly.
If you do not expose privates via a getter, you give the programmer one less method to think about when he need to use the class’s instance for something.

Can you think how you would use this “pattern”? Do you think there is no use for it?
Tell me what you think.

I like delegates (Input example)

Saturday, December 26th, 2009

Delegates are a very powerful design pattern, that come in a variety of forms and can solve a large variety of problems. A simple way to describe delegate would be with some code:

class Base {
	public:
		virtual void foo() = 0;
		virtual ~Base(){};
};

class A: public Base {
	public:
		void foo() {...};
};

class B: public Base {
	public:
		void Initialize (Base & d) { this->d = &d; };
		void foo() {...; this->d->foo(); };
	private:
		Base * d;
};

 

As you can see, class B can use class A’s functionality by pointing to it. But what is it good for? Here is a more concrete example.

class BaseTextKeyboard: virtual public BaseClass {
	public:
		virtual void Enable() = 0;
		virtual void Disable() = 0;
		virtual void ClearText() = 0;
		virtual std::string GetText() = 0;
};

class WindowsKeyboard: public BaseWindowsKeyboard, public BaseTextKeyboard {
	public:
		void Enable();
		void Disable();
		void TranslateMessage (WPARAM wParam, LPARAM lParam);
		void ClearText();
		std::string GetText();
		WindowsKeyboard();
};

class TextKeyboard: public BaseTextKeyboard {
	public:
		void Enable();
		void Disable();
		void Initialize (GetKeyKeyboard & A_Keyboard);
		void ClearText();
		void Handle();
		std::string GetText();
		TextKeyboard();
};

class TextKeyboardFeeder: public BaseTextKeyboard {
	public:
		void Initialize (BaseTextKeyboard & A_Delegate);
		void Enable();
		void Disable();
		void ClearText();
		std::string GetText();
		void Handle();
		TextKeyboardFeeder();
	private:
		bool IsEnable;
		std::string Text;
		BaseTextKeyboard * Delegate;
};

I needed to have text input in TRG’s GUI. A line which you can type text, like in a text field in a web form. At first I thought to use direct input for the job. Since I already had some code for direct input and keyboard. I created a class called TextKeyboard, and I had another class for the text field that used it. I quickly found out that reading keyboard is not trivial. You need to deal with shift being pressed, with keys being held down. All this is already dealt with when you process a window message called WM_CHAR, which makes it pointless to achieve the same functionality using direct input.

Since I already wrote the text field class, I wanted to write the “windows keyboard” in a way I could just send it to the text field class and it would work. I then created a base class(BaseTextKeyboard), or an interface for the TextKeyboard which contained virtual methods and only those that are used with the text field.
I then created a class called WindowsKeyboard which implemented BaseTextKeyboard. However, there was a problem. TextKeyboard was created once for every text field, but WindowsKeyboard could only be created once for all the text fields. Every text field was pointing to the same WindowsKeyboard, which made things not to work properly.

The solution? Have a TextKeyboardFeeder class. This class will both implement the BaseTextKeyboard interface and will point to a WindowsKeyboard class. TextKeyboardFeeder will be created once for every text field, and will have it’s own std:string. Only when the text field is in focus, the corresponding TextKeyboardFeeder will read from the WindowsKeyboard class.
We have another layer of feeders that point to the actual WindowsKeyboard. Each text field has it’s own copy of TextKeyboardFeeder. Each feeder copy has it’s own std:string that contains keyboard input, but all the feeders point to the same WindowsKeyboard and read the text input from it.
By the way, since TextKeyboardFeeder point to BaseTextKeyboard, it could also point to TextKeyboard instead of WindowsKeyboard and it would also work. That is the power of delegates.

Is it clear what I was doing? Do you wish to see more code? More detailed explanation? Please reply and tell me what you think.

Recursive Development

Tuesday, December 22nd, 2009

I have been working on a little language to represent GUI objects placement for the TRG project.
This allows me to write a text file with a certain format and syntax, so the game will be able to parse it and place the GUI objects on the screen. It allows changing the GUI without recompilation and removes the need to hard code some of the GUI logic inside the C++ project. I also plan to build a tool that will allow me to drag and drop GUI objects on the screen, and to save it into such text file.
Here is an example of an early stage of the parsed GUI, first the result and then the GUI text file:

GUI Example

GUI Example

Draw4Text (x, y, dy, n)
{
	Text (x, y, "Text "+n+".1");
	Text (x, y+dy, "Text "+n+".2");
	Text (x, y+dy+dy, "Text "+n+".3");
	Text (x, y+dy+dy+dy, "Text "+n+".4");
}

Error1 ()
{
	Draw4Batch (512, 384, 30);
}

Draw4Batch (x, y, dy)
{
	Draw4Text (x, y, dy, 1);
	Draw4Text (x, y+dy+dy+dy+dy, dy, 2);
}

Error2 (a)
{
	Error ("Testing error number 2");
}

The problem? I don’t know what I want to have in TRG’s GUI yet. I believe it’s better to develop code around “real life situations”, rather than guessing what features I will need. My solution is to use the tool as an example of the requirements from the little language. With the tool I will be able to build GUIs, but the tool itself need to have a GUI. I will build the GUI of the tool with a text file, and after I will have the first version of the tool, I will build the next version of the tool’s GUI with the earlier version. Sort of a recursive development. The tool will be used as both an example of what I need and both as the tool to create the next iteration.
It is a sort of a compromise, but I think it’s better than just guessing.