<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Pompi Pompi - A Gamers and Developers blog for indie games &#187; Coding</title>
	<atom:link href="http://www.pompidev.net/category/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.pompidev.net</link>
	<description>A blog about indie game development for both gamers and developers</description>
	<lastBuildDate>Fri, 05 Mar 2010 18:27:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fun with dynamic casting</title>
		<link>http://www.pompidev.net/2010/01/29/fun-with-dynamic-casting/</link>
		<comments>http://www.pompidev.net/2010/01/29/fun-with-dynamic-casting/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 19:10:13 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=467</guid>
		<description><![CDATA[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&#60;&#60;"Base";};
};

class A: public BaseA {
	public:
		void foo(){cout&#60;&#60;"Child";};
};

A a;
BaseA &#38; base = a;
base.foo();
Will print &#8220;Child&#8221;.
&#8220;Pair polymorphism&#8221; is when you want a specific function implementation to be called based on the run time value of two [...]]]></description>
			<content:encoded><![CDATA[<p>Polymorphism allows for different function implementations to be called, depending on values only known at run time. For instance:</p>
<pre>class BaseA {
	public:
		virtual void foo(){cout&lt;&lt;"Base";};
};

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

A a;
BaseA &amp; base = a;
base.foo();</pre>
<p>Will print &#8220;Child&#8221;.</p>
<p>&#8220;Pair polymorphism&#8221; 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:</p>
<pre>class BaseA {
};

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

class A: public BaseA {
};

class B: public BaseB {
	public:
		void foo (A &amp; a);
};</pre>
<p>You would want that somehow &#8220;void B::foo (A &amp; a)&#8221; will be called. The code I posted does not do this.<br />
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.<br />
An abstraction layer is a set of classes or interfaces, that have no methods or &#8220;don&#8217;t know&#8221; anything about the classes that implement them. For instance you can have a graphics abstraction layer.<br />
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.</p>
<p>How are we going to have a &#8220;pair polymorphism&#8221; in this case? One solution is using dynamic casting. You can cast a pointer of a parent class to it&#8217;s child class(in case the run time value really points to an instance of that class).<br />
Some code:</p>
<pre>class BaseA {
};

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

class A: public BaseA {
};

class B: public BaseB {
	public:
		void foo (BaseA &amp; a)
		{
			foo2 (dynamic_cast&lt;A &amp;&gt;(a));
		}
		void foo2 (A &amp; a);
};</pre>
<p>I was asked by someone how this can be done without dynamic casting, because he doesn&#8217;t like dynamic casting. I found a way, but it ain&#8217;t pretty, and I honestly can&#8217;t find any advantage of using this code instead of just using dynamic casting. But here it is:</p>
<pre>class BaseA {
	public:
		virtual void DynamicCast() = 0;
};

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

class A;

class Caster {
	public:
		A * a;
};

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

class B: public BaseB {
	public:
		Caster * c;
		void foo (BaseA &amp; base)
		{
			base.DynamicCast();
			foo2 (c-&gt;a);
		}
		void foo2 (A &amp; a);
};</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2010/01/29/fun-with-dynamic-casting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Out of the box(bug)</title>
		<link>http://www.pompidev.net/2010/01/20/out-of-the-boxbug/</link>
		<comments>http://www.pompidev.net/2010/01/20/out-of-the-boxbug/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 19:02:48 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=458</guid>
		<description><![CDATA[When you draw sprites you are thinking in 2D. I was using DirectX&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>When you draw sprites you are thinking in 2D. I was using DirectX&#8217;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.<br />
When I scaled my sprite by 2 everything worked, but when I scaled it by 4 it was not visible. What was the problem?<br />
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&#8217;t remember why I did that.<br />
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.<br />
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.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2010/01/20/out-of-the-boxbug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Accessing privates without &#8216;friend&#8217;(c++)</title>
		<link>http://www.pompidev.net/2010/01/05/accessing-privates-without-friendc/</link>
		<comments>http://www.pompidev.net/2010/01/05/accessing-privates-without-friendc/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 21:12:34 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=427</guid>
		<description><![CDATA[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 {
          [...]]]></description>
			<content:encoded><![CDATA[<p>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:</p>
<p><code lang="cpp"></p>
<pre>class A {
    public:
        class Observer {
             protected:
                 int GetPrivate(A &amp; a) {return a.ValueA;};
        };
    private:
        int ValueA;
};

class B: public A::Observer {
    public:
        void Foo (A &amp; a) {
             cout&lt;&lt;GetPrivate(A);
        }
};</pre>
<p> </p>
<p></code>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 &#8220;pattern&#8221; recently, I am not sure what is the direct benefit of this.</p>
<p>I believe a benefit can be in the sense of making a programmer&#8217;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.<br />
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&#8217;s instance for something.</p>
<p>Can you think how you would use this &#8220;pattern&#8221;? Do you think there is no use for it?<br />
Tell me what you think.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2010/01/05/accessing-privates-without-friendc/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>I like delegates (Input example)</title>
		<link>http://www.pompidev.net/2009/12/26/i-like-delegates-input-example/</link>
		<comments>http://www.pompidev.net/2009/12/26/i-like-delegates-input-example/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 16:50:40 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[The RPG Game]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=404</guid>
		<description><![CDATA[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 &#038; d) { [...]]]></description>
			<content:encoded><![CDATA[<p>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:</p>
<p><code lang="cpp">
<pre>class Base {
	public:
		virtual void foo() = 0;
		virtual ~Base(){};
};

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

class B: public Base {
	public:
		void Initialize (Base &#038; d) { this->d = &#038;d; };
		void foo() {...; this->d->foo(); };
	private:
		Base * d;
};</pre>
<p></code> </p>
<p>As you can see, class B can use class A&#8217;s functionality by pointing to it. But what is it good for? Here is a more concrete example.</p>
<p><code lang="cpp">
<pre>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 &#038; A_Keyboard);
		void ClearText();
		void Handle();
		std::string GetText();
		TextKeyboard();
};

class TextKeyboardFeeder: public BaseTextKeyboard {
	public:
		void Initialize (BaseTextKeyboard &#038; A_Delegate);
		void Enable();
		void Disable();
		void ClearText();
		std::string GetText();
		void Handle();
		TextKeyboardFeeder();
	private:
		bool IsEnable;
		std::string Text;
		BaseTextKeyboard * Delegate;
};
</pre>
<p></code></p>
<p>I needed to have text input in TRG&#8217;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.</p>
<p>Since I already wrote the text field class, I wanted to write the &#8220;windows keyboard&#8221; 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.<br />
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.</p>
<p>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&#8217;s own std:string. Only when the text field is in focus, the corresponding TextKeyboardFeeder will read from the WindowsKeyboard class.<br />
We have another layer of feeders that point to the actual WindowsKeyboard. Each text field has it&#8217;s own copy of TextKeyboardFeeder. Each feeder copy has it&#8217;s own std:string that contains keyboard input, but all the feeders point to the same WindowsKeyboard and read the text input from it.<br />
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.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2009/12/26/i-like-delegates-input-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Recursive Development</title>
		<link>http://www.pompidev.net/2009/12/22/recursive-development/</link>
		<comments>http://www.pompidev.net/2009/12/22/recursive-development/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 13:23:55 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[The RPG Game]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=392</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>I have been working on a little language to represent GUI objects placement for the TRG project.<br />
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.<br />
Here is an example of an early stage of the parsed GUI, first the result and then the GUI text file:</p>
<div id="attachment_398" class="wp-caption aligncenter" style="width: 410px"><img class="size-full wp-image-398" title="GUIExample" src="http://www.pompidev.net/wp-content/uploads/2009/12/GUIExample.jpg" alt="GUI Example" width="400" height="400" /><p class="wp-caption-text">GUI Example</p></div>
<p><code>
<pre>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");
}
</pre>
<p></code></p>
<p>The problem? I don&#8217;t know what I want to have in TRG&#8217;s GUI yet. I believe it&#8217;s better to develop code around &#8220;real life situations&#8221;, 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&#8217;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.<br />
It is a sort of a compromise, but I think it&#8217;s better than just guessing.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2009/12/22/recursive-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Minimizing &#8220;thought resources&#8221;</title>
		<link>http://www.pompidev.net/2009/12/18/minimizing-thought-resources/</link>
		<comments>http://www.pompidev.net/2009/12/18/minimizing-thought-resources/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 15:38:31 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=371</guid>
		<description><![CDATA[It can be fun to think hard about something. But sometimes we waste a lot more thought than we could to achieve the same goal and even better. Let&#8217;s say that efficient use of thought resources is to choose the path that requires you the minimum thinking and effort to achieve the same goal or better.
I [...]]]></description>
			<content:encoded><![CDATA[<p>It can be fun to think hard about something. But sometimes we waste a lot more thought than we could to achieve the same goal and even better. Let&#8217;s say that efficient use of thought resources is to choose the path that requires you the minimum thinking and effort to achieve the same goal or better.<br />
I will try to bring a metaphor, because I am afraid a math or code example would be less intuitive.<br />
Let&#8217;s say you need to carry rocks from one place to another. You can pick them one by one, by hand, and carry them. In some cases this will be the best solution, but what if you need to carry rocks every day for the whole year? Wouldn&#8217;t it be better to build or buy a wheelbarrow? Though, if you needed to carry a few works than maybe getting a wheelbarrow is not worthwhile.</p>
<p>In programming this can mean planning ahead how you are going to solve a problem, or researching for the right existing technology to use.<br />
However, things are not as simple as that. Planning consume thought resources or effort. You might end up planning too much ahead or investing long hours in planning something you don&#8217;t really know if it will work. This means there need to be a balance between planning and just trying things out. It might sound funny, but I believe you don&#8217;t want to sweat too much most of the time you code. A game requires large amounts of code and work, and if every minute of it would require you a lot of thought and effort, you will quickly burn out. A lot of the time coding should be easy or with very little effort. Of course, sometimes it&#8217;s tough. And sometimes it gets really tough, but you want to minimize the times it gets really tough.</p>
<p>The thing that inspired me to write this article is some code I had to write to build a tree from a data structure. This data structure is the result of a text file I parsed with boost::spirit(more about that in future post). In my first attempt I simply used a tool I had available, of building a tree. I forgot I had another tool built upon it that would make my life much easier.<br />
The basic tool would call two virtual methods, build child and build sibling, and with those you are suppose to build the tree. The code I wrote for this tool was long, ugly and didn&#8217;t work. After this failed attempt I realized I have a tool I built upon the basic tool. This tool allows me to add the edges of the tree. I have an AddEdge method that gets parent index, child index and node data. The implementation make sure all those edges I add will create a tree after I call BuildTree. A lot simpler.<br />
The first code snippet is of the advanced tree building tool, and the second code snippet is of the basic building tool. Notice the code is not spartanized much, and you don&#8217;t really need to try and understand it. Just try to see which one looks prettier. You might not see the code if you are not at the original blog website(because it&#8217;s a lot of code, and because of different plug-ins), so for the code you should visit <a href="http://www.pompidev.net/2009/12/18/minimizing-thought-resources/">my blog</a>.</p>
<p><code lang="cpp">
<pre>
	void
	NodeFunction::NodeFunctionCall::AddNode (MathNode n, DWORD A_Parent, DWORD A_ListIndex, Tree<ParameterNode>::Builder &#038; b)
	{
		using boost::fusion::at_c;
		this->CurrentIndex++;
		DWORD i = this->CurrentIndex;
		if (at_c<1>(n.Node).size()!=0)
		{
			NodeFunction::NodeFunctionCall::ParameterNode NodeData;

			NodeData.IsOperation = true;
			NodeData.Operation = at_c<0>((at_c<1>(n.Node))[A_ListIndex]);
			b.AddEdge (A_Parent, i, NodeData);
			if (A_ListIndex==0)
				this->AddSingleNode (at_c<0>(n.Node).get(), i, b);
			else
				this->AddSingleNode (at_c<1>((at_c<1>(n.Node))[A_ListIndex-1]).get(), i, b);
			if (A_ListIndex+1==at_c<1>(n.Node).size())
				this->AddSingleNode (at_c<1>((at_c<1>(n.Node))[A_ListIndex]).get(), i, b);
			else
				this->AddNode (n, A_Parent, A_ListIndex+1, b);
			return;
		}
		this->AddSingleNode (at_c<0>(n.Node).get(), A_Parent, b);
	}
</pre>
<p></code></p>
<p>Basic tree builder code.</p>
<p><code lang="cpp">
<pre>
	MemberClass<TreeNodeBuilderData<NodeFunction::NodeFunctionCall::ParameterNode, NodeFunction::NodeFunctionCall::BuilderData> >
	NodeFunction::NodeFunctionCall::Builder::CreateNode (MathNode A_Node, MathNode A_ExtraNode, DWORD A_Index, bool A_ExtraSibling)
	{
		MemberClass<TreeNodeBuilderData<NodeFunction::NodeFunctionCall::ParameterNode, NodeFunction::NodeFunctionCall::BuilderData> > Result;

		NodeFunction::NodeFunctionCall::ParameterNode NodeData;

		Result->bCreate = false;
		bool IsExtraSibling = false;

		if (A_Index!=0 &#038;&#038; A_ExtraSibling &#038;&#038; (A_Index-1)==boost::fusion::at_c<1>(A_Node.Node).size())
		{
			IsExtraSibling = true;
			A_Index = 0;
			A_Node = A_ExtraNode;
			A_ExtraSibling = false;
		}

		while (boost::fusion::at_c<1>(A_Node.Node).size()==0)
		{
			MathSingleNodeType * SingleNode = &#038;(boost::fusion::at_c<0>(A_Node.Node).get().Node);
			boost::recursive_wrapper<MathNode> * p = boost::get<boost::recursive_wrapper<MathNode> >(SingleNode);
			if (p==NULL)
			{
				Result = this->CreateSingleNode (boost::fusion::at_c<0>(A_Node.Node).get());
				if (IsExtraSibling)
					Result->Data.IsSibling = false;
				return Result;
			}
			A_Node = p->get();
		};

		if (A_Index<boost::fusion::at_c<1>(A_Node.Node).size())
		{
			ComplexNode c = boost::fusion::at_c<1>(A_Node.Node);
			NodeData.IsOperation = true;
			NodeData.Operation = boost::fusion::at_c<0>(c[A_Index]);
			NodeFunction::NodeFunctionCall::BuilderData b;
			b.IsSibling = true;//!IsLast || A_ExtraSibling;
			boost::recursive_wrapper<MathSingleNode> * Single = A_Index==0?&#038;boost::fusion::at_c<0>(A_Node.Node):&#038;boost::fusion::at_c<1>(c[A_Index-1]);
			MathSingleNode n = Single->get();
			if (boost::get<boost::recursive_wrapper<MathNode> >(&#038;n.Node)!=NULL)
				b.Node = boost::get<boost::recursive_wrapper<MathNode> >(n.Node).get();
			else
			{
				MathNode m;
				boost::fusion::at_c<0>(m.Node) = *Single;
				b.Node = m;
				if (A_Index==0 &#038;&#038; !IsExtraSibling)
					b.IsSibling = false;
			}
			bool IsLast = A_Index==boost::fusion::at_c<1>(A_Node.Node).size()-1;
			b.IsNull = false;
			b.Index = A_Index;
			if (IsLast)
			{
				b.IsExtra = true;
   				boost::recursive_wrapper<MathSingleNode> * Single = &#038;boost::fusion::at_c<1>(c[A_Index]);
				n = Single->get();
				if (boost::get<boost::recursive_wrapper<MathNode> >(&#038;n.Node)!=NULL)
					b.ExtraNode = boost::get<boost::recursive_wrapper<MathNode> >(n.Node).get();
				else
				{
					MathNode m;
					boost::fusion::at_c<0>(m.Node) = *Single;
					b.ExtraNode = m;
				}
			}
			Result->bCreate = true;
			Result->NodeData = NodeData;
			Result->Data = b;
			return Result;
		}
		GlobalErrorWrap::Assert (false, "Unreachable ParsedGUI build code");
		return Result;
	}
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2009/12/18/minimizing-thought-resources/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Copy paste and coding</title>
		<link>http://www.pompidev.net/2009/10/02/copy-paste-and-coding/</link>
		<comments>http://www.pompidev.net/2009/10/02/copy-paste-and-coding/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 09:34:04 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=111</guid>
		<description><![CDATA[Some people(my friend) think that if you can copy and paste some code it means it is a reusable code. That is wrong in two ways. First, reusable code means that the same code can be used in many different projects, it doesn&#8217;t say how many times you need it in one project. Secondly, as [...]]]></description>
			<content:encoded><![CDATA[<p>Some people(my friend) think that if you can copy and paste some code it means it is a reusable code. That is wrong in two ways. First, reusable code means that the same code can be used in many different projects, it doesn&#8217;t say how many times you need it in one project. Secondly, as a rule of thumb, copy pasting in programming is a bad thing(sort of).<br />
In this post I will not talk about reusable code, but rather how to avoid copy pasting. There is actually a very important mechanism for copy pasting in code. That is inheritance. Inheritance helps you copying the same code from one class into a new class, without actually having the same code written twice. Lets try to show a code example in C++.</p>
<p><code><br />
class BaseSpriteDrawer {<br />
public:<br />
    void DrawCenter (int x, int y, Texture &amp; t)<br />
    {<br />
     this-&gt;Draw (x-t.GetWidth()/2, y-t.GetHeight()/2, t);<br />
    };<br />
    virtual void Draw (int x, int y, Texture &amp; t) = 0;<br />
}</code><br />
<code><br />
class SpriteDrawerA: public BaseSpriteDraw {            <br />
public:<br />
    void Draw (int x, int y, Texture &amp; t);<br />
};</code><br />
<code><br />
class SpriteDrawerB: public BaseSpriteDraw {            <br />
public:<br />
    void Draw (int x, int y, Texture &amp; t);<br />
};</code></p>
<p>In this example you can see there are two different implementations for drawing sprites. Each one of those have different code for Draw. However, DrawCenter has the same code for both implementations so instead of writing the same code twice for each of the implementations, I have used inheritance. We have &#8220;copy pasted&#8221; the content of the class BaseSpriteDrawer or &#8220;copy pasted&#8221; DrawCenter.<br />
The reason copy pasting is bad, is that you have the same code to maintain in two different places. If you discover a bug inside a function, you need to fix all the places you copy pasted that function. You just have more code to maintain, more copies of the same thing to maintain which translates into more work and more bugs.<br />
There is also the additional bonus of saving you a lot of time. Sometimes you need the same code with small variations, and it would seem more work to figure out how to do this with inheritance, instead of just copy pasting and having two copies of the same code. However, in case you need a third copy of the code, with the inherited code it would be a lot easier to create the third &#8220;copy&#8221; of the code instead of copy pasting the same code for the second time.</p>
<p>If you are a beginner, I suggest you try to avoid copy pasting almost completely. It would be a good exercise or a good challenge to try doing something else each time you have the urge to copy paste some code. That being said, I myself don&#8217;t completely avoid copy pasting. While as a rule of thumb, its better to avoid copy pasting, sometimes its the fastest immediate solution. The thing is, not all of my code get the same treatment. Some code get better treatment than other code. If its code that is not so important and is not long, then I might copy paste it. I also might copy paste something, and when I see I get back to the same code to add something new, I would fix my bad practice of copy pasting and make a better, cleaner code.</p>
<p>There is a lot more to talk about this subject, and a lot more examples and techniques of how to avoid copy pasting. Copy pasting is actually implied from spartan programming, I have already mentioned spartan programming  and I hope to talk about it in future posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2009/10/02/copy-paste-and-coding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>String operations performance.</title>
		<link>http://www.pompidev.net/2009/09/25/string-operations-performance/</link>
		<comments>http://www.pompidev.net/2009/09/25/string-operations-performance/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 17:12:24 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=92</guid>
		<description><![CDATA[Performance is a strange beast.
I was just profiling a section in Labyrinthica that was responsible of drawing the walls sprites. The function had a loop that iterates about 200 times and each iteration calls a sprite draw call. Inside the loop there was the following code:
ostringstream OStr;
OStr&#60;&#60;"Not 1 or 2("&#60;&#60;i&#60;&#60;")";
Error::Assert (i==1 &#124;&#124; i==2, OStr.str());
With this code [...]]]></description>
			<content:encoded><![CDATA[<p>Performance is a strange beast.<br />
I was just profiling a section in <a href="http://www.pompipompi.net">Labyrinthica</a> that was responsible of drawing the walls sprites. The function had a loop that iterates about 200 times and each iteration calls a sprite draw call. Inside the loop there was the following code:</p>
<p><code>ostringstream OStr;<br />
OStr&lt;&lt;"Not 1 or 2("&lt;&lt;i&lt;&lt;")";<br />
Error::Assert (i==1 || i==2, OStr.str());</code></p>
<p>With this code the walls drawing function took 7% of a specific time. Then I changed this part of code to:</p>
<p><code>ostringstream OStr;<br />
OStr&lt;&lt;"Not 1 or 2";<br />
Error::Assert (i==1 || i==2, OStr.str());</code></p>
<p>After this change I got 4%. I then changed it to:</p>
<p><code>Error::Assert (i==1 || i==2, "Not 1 or 2");</code></p>
<p>And I got down to 2%. The conclusion is that performance can be very tricky. What might seem innocent(A simple string handling) might turn to be big CPU usage when performed inside a loop.<br />
I found that there is quite an imagination between profiling and debugging. Maybe there is a way to reduce the time of profiling and avoid from these kind of pitfalls? I hope to figure this out in the future. I think there is something that might help.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2009/09/25/string-operations-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bugs as an opportunity to learn</title>
		<link>http://www.pompidev.net/2009/09/25/bugs-as-an-opportunity-to-learn/</link>
		<comments>http://www.pompidev.net/2009/09/25/bugs-as-an-opportunity-to-learn/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 08:47:47 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=76</guid>
		<description><![CDATA[In a previous blog post, I talked about bug negative verification. I also said that debugging should be avoided as much as possible.
That is true, debugging is mostly a waste of time. You spend a lot of hours trying to figure out why what you yourself wrote doesn&#8217;t work as it should. After you solve [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous <a href="http://www.pompidev.net/2009/09/13/bug-negative-verification/">blog post</a>, I talked about bug negative verification. I also said that debugging should be avoided as much as possible.<br />
That is true, debugging is mostly a waste of time. You spend a lot of hours trying to figure out why what you yourself wrote doesn&#8217;t work as it should. After you solve the bug, you don&#8217;t have a new feature, there is no prevention that you will make the same mistake in the future and you might have to redo the same wasteful debugging process you just did. Right? Well, not exactly.<br />
A good philosophy to adopt is, can I do something so the same kind of bugs won&#8217;t reappear in the future? If you invest some time, after solving the bug, to figure out how to prevent future similar bugs from happening you might learn or gain something from the bug. <strong>That is why a bug is an opportunity to learn how to prevent similar bugs in the future</strong>.<br />
For instance, a buffer overflow is when you are accessing an array beyond its allocated size. In c++ it would be doing something like this:<br />
int a[4];<br />
a[10] = 12;<br />
If your program is doing weird things, you might eventually capture this bug. But its obvious it is better to use an array that is safe. Such as, an array that check if the index provided for cell access is within the boundaries of the array. If its not, it will report a run time error and let you know you did something wrong.<br />
However, things are not always as simple as in the case of the array. Sometimes its not clear how you can prevent certain bugs. Lets say you have a game with medieval weapons such as swords and daggers. You want to give the dagger a power of 2 and the sword a power of 3. You gave the sword a power of 3, but you accidentally gave the dagger a power of 4. This is a bug, even though nothing will crash. It would be very difficult to prevent this kind of bug, but I can think of ways that would help catching this bug early.<br />
Another concrete example is GPU shaders. You can write a shader in some high level language such as HLSL for directX. These shaders often have global parameters you can set through your program. I had a bug in a shader that it didn&#8217;t draw what I meant for it to draw. I then began debugging. First I checked if the color texture was really passed to the shader. Then I checked the normals in the vertex data and etc. I finally found that I forgot to set one of the global parameters of the shader. I wasted an hour or two to figure out this bug. A way to prevent this bug is to keep track of which parameters are set before each draw call, and report an error if not all the parameters were set.<br />
However, you sometimes don&#8217;t want to set all the parameters in a shader, so what is the right choice?</p>
<p>I would say its a good habit to do some thinking after solving a bug, and not immediately move on to the next task. Why this bug happened? How I solved it? Did I really solve it? How can I prevent similar bugs from happening in the future? Should I prevent similar bugs in the future or is it not cost effective and having this kind of bug from time to time is acceptable?</p>
<p>Last but not least, you need to take what I said with a grain of salt. This is something that worked for me, from my own experience under certain conditions, but you don&#8217;t have to do exactly the same. Its not formal anyway, because you can&#8217;t 100% formalize programming. Its an advice, not rules or a recipe to follow blindly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2009/09/25/bugs-as-an-opportunity-to-learn/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Geometry based Anti Alias(GAA)</title>
		<link>http://www.pompidev.net/2009/09/20/geometry-based-anti-aliasgaa/</link>
		<comments>http://www.pompidev.net/2009/09/20/geometry-based-anti-aliasgaa/#comments</comments>
		<pubDate>Sun, 20 Sep 2009 21:02:02 +0000</pubDate>
		<dc:creator>ofer</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.pompidev.net/?p=53</guid>
		<description><![CDATA[Abstract
Suggesting a technique of implementing a Geometry based Anti Alias(GAA), instead of using the built in 3D graphics AA. This technique has the potential to improve performance and quality of the AA under certain conditions. In short, I am using a geometry based or fins geometry outline technique, and use it to draw translucent smooth [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Abstract</strong><br />
Suggesting a technique of implementing a Geometry based Anti Alias(GAA), instead of using the built in 3D graphics AA. This technique has the potential to improve performance and quality of the AA under certain conditions. In short, I am using a geometry based or fins geometry outline technique, and use it to draw translucent smooth edges with the same color of the original 3D model.</p>
<p><strong>Pre Requirements</strong><br />
In order to implement this algorithm, one need to have a geometry based or fins geometry Non Photo Realistic outline shaders implemented. <br />
This type of shader use a mesh of fins. For every edge or intersection between two triangles in the original mesh, there is a fin in the fins mesh. When rendering this fins mesh, we select in the shader which fins will be visible and which will not. The fins that are visible are those that one of the two triangles the fin belongs to is facing the camera and the other doesn&#8217;t. This cause that the viewable fins are the outline fins of the projected mesh on the screen space.<br />
Some articles explaining how to do this, can be found here:<br />
<a href="http://www.cgstarad.com/NPR/GSContours.pdf">Single Pass GPU Stylized Edges</a><br />
<a href="http://ati.amd.com/developer/shaderx/ShaderX_NPR.pdf">NPR with Pixel and Vertex Shader</a></p>
<p><strong>How it works<br />
</strong>Once you have the fins geometry, either by precalculating or using the geometry shader, you need to add additional information to the vertexes of the fin. If you are drawing a black fading outline using the fin geometry, you already have a V coordinate that is 0 where the fin is touching the 3D model and 1 at the farest point of the fin from the 3D model. For the faded black outline, we use this V coordinate to determine what alpha value we want the fin to have in the pixel.</p>
<p style="TEXT-ALIGN: center"><img class="size-full wp-image-62 alignnone" title="Black Outline" src="http://www.pompidev.net/wp-content/uploads/2009/09/BlackOutline.bmp" alt="Black Outline" /></p>
<p>The additional information we need to add, is all the information we have in the 3D model vertex where the fin come out from, which is used to calculate the final color of the correspondent triangles. For instance, if the vertex keeps a normal to calculate diffuse lighting, we need to keep this normal in the correspondent fin vertex as well.<br />
We pass this information from the fin vertex to the pixel shader and on the pixel shader we calculate the color just like we would calculate the color in the pixel shader of the 3D model.<br />
The next step is to multiply the fin color with an alpha, much like we did with the faded black alpha, and we get the anti aliased edge.<br />
The results are shown in the following images of a ball and a scene from the game <a href="http://www.pompipompi.net">Labyrinthica: The quest of lima</a>. For comparison I have included a render with no AA and a render with AA from an NVIDIA Geforce 8600 GTS set at 16Q.<br />
Also a render of GAA outline without the 3D model.</p>
<p style="TEXT-ALIGN: center"><img title="BallAliased" src="http://www.pompidev.net/wp-content/uploads/2009/09/BallAliased.bmp" alt="Aliased ball" /></p>
<p style="TEXT-ALIGN: center">Aliased ball</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-64" title="BallAA16Q" src="http://www.pompidev.net/wp-content/uploads/2009/09/BallAA16Q.bmp" alt="Built in Anti Alias" /></p>
<p style="text-align: center;">Built in Anti Alias</p>
<p style="text-align: center;"><img class="alignnone size-full wp-image-65" title="BallAA" src="http://www.pompidev.net/wp-content/uploads/2009/09/BallAA.bmp" alt="GAA Ball" /></p>
<p style="text-align: center;">GAA ball</p>
<p style="TEXT-ALIGN: center"><strong><img class="alignnone size-full wp-image-67" title="BallAAOutline" src="http://www.pompidev.net/wp-content/uploads/2009/09/BallAAOutline.bmp" alt="GAA Outline only" /></strong></p>
<p style="TEXT-ALIGN: center">GAA only</p>
<p style="TEXT-ALIGN: center"><strong> </strong></p>
<p style="TEXT-ALIGN: center"><img class="alignnone size-full wp-image-68" title="LimaAA" src="http://www.pompidev.net/wp-content/uploads/2009/09/LimaAA.bmp" alt="Lima GAA" /></p>
<p><strong>Performance, quality and issues<br />
</strong>GAA might prove to have better or worse performance than the built in AA of the graphics card.<br />
The main bottlenecks of GAA are the vertex shader, in case no geometry shader is available, and part of the bottlenecks that the 3D model suffer from depending on the shader it use to calculate color. For instance, a use of texture might cause a memory bus bottleneck. On the other hand, GAA will most likely be calculated for only small part of the pixels on the screen, unlike the graphics card AA which is calculated for all the pixels in the screen.<br />
In terms of quality, GAA has several differences from built in AA. You can control the fin&#8217;s thickness, making it possible for smoother and more pleasing AA. It does not make textures or models&#8217; surfaces blurred or smoothed. And you can add a black outline for NPR rendering almost for free.</p>
<p style="text-align: center;"><img class="size-full wp-image-66 aligncenter" title="BallOutline" src="http://www.pompidev.net/wp-content/uploads/2009/09/BallOutline.bmp" alt="GAA NPR Outline" /></p>
<p>GAA might not work for edges with very high curvature or surface with unsmooth normals or unsmooth parameters used for calculating the color. Problems may arise due to the fact that the color on a specific vertex of a mesh is not the same color as the pixel next to it. Because the data at the pixel is the interpolation of 3 vertexes and not the exact data in the closest vertex. This might cause problems such as back facing normals on the fin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pompidev.net/2009/09/20/geometry-based-anti-aliasgaa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
