<?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>Scriptionary Blog &#187; snippets</title>
	<atom:link href="http://blog.scriptionary.com/tag/snippets/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.scriptionary.com</link>
	<description>The informal yet informational sub-site</description>
	<lastBuildDate>Fri, 19 Feb 2010 16:21:55 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Simple Scene Graph in C++</title>
		<link>http://blog.scriptionary.com/2009/02/17/simple-scene-graph-in-c/</link>
		<comments>http://blog.scriptionary.com/2009/02/17/simple-scene-graph-in-c/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 20:07:15 +0000</pubDate>
		<dc:creator>Eddy Luten</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[graphics programming]]></category>
		<category><![CDATA[snippets]]></category>

		<guid isPermaLink="false">http://blog.scriptionary.com/?p=68</guid>
		<description><![CDATA[There are several articles gathering dust bunnies on the internet on creating a scene graph class in C++ for your 3D engine but most are pretty vague and quite old. Hopefully, this post will give you a foot in the door in creating your own scene graph for your engine.
To start off, let&#8217;s go over [...]]]></description>
			<content:encoded><![CDATA[<p>There are several articles gathering dust bunnies on the internet on creating a scene graph class in C++ for your 3D engine but most are pretty vague and quite old. Hopefully, this post will give you a foot in the door in creating your own scene graph for your engine.</p>
<p>To start off, let&#8217;s go over some basics. A scene graph is a tree-like data structure which holds information about the scene you want to display. Every node has a parent and every node may have children. In this post we&#8217;ll use the std::vector to store the scene nodes but you can substitute this with whatever you want. A scene graph can be visualized like so:</p>
<pre>             [root node]
                  |
        o=========o=========o
        |         |         |
    [child 1] [child 2] [child 3]
        |
    o===o====o
    |        |
[child 4][child 5]
             |
         [child 6]</pre>
<p>Any node may have any number of children who&#8217;s children may have any number of children, etc. Each node in the scene graph may have a name for lookup functionality so a very lookup system will be implemented. We will also need functionality to add a child node, remove a child node, set/get a node&#8217;s parent and an update function for updating the graph hierarchically.<br />
<span id="more-68"></span><br />
Beware that this scene graph is for educational purposes <strong>only</strong>, I do not recommend that you implement this scene graph into your engine as it uses very simple algorithms and general-purpose classes from the C++ Standard Template Library. Also, keep in mind that <strong>a scene graph is not used for rendering your objects</strong>, it is used to keep hierarchical information and for applying hierarchical transformations.</p>
<p>Rendering your objects is done through a different type of structure such as a Binary Space Partitioning Tree (BSP-Tree) or an Octree which are structures more suitable for visibility testing and quite a bit faster. Your scene graph is updated each cycle of your simulation or game so that all the objects in your scene have their correct transformations.</p>
<p>Let&#8217;s start off with declaring our base class, the Node (below is the entire Node.h file):</p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
#ifndef __node_h_
#define __node_h_ 1
#include &lt;vector&gt;

class Node
{
public:
	Node(Node* Parent = NULL, const char* Name = NULL);
	virtual ~Node(void);

	virtual void Update(void);

	Node* GetParentNode(void) const;
	void SetParentNode(Node* NewParent);

	void AddChildNode(Node* ChildNode);
	void RemoveChildNode(Node* ChildNode);

	const char* GetNodeName(void) const;
	const size_t CountChildNodes(const bool&amp; RecursiveCount = false) const;
	virtual const bool IsRootNode(void) const = 0;

	Node* GetChildNodeByName(const char* SearchName);

private:
	Node* m_Parent;
	const char* m_Name;
	std::vector&lt;Node*&gt; m_Children;

}; // class Node

#endif</pre>
<p>There are not many methods in this class so you have room for expansion if you feel like it. Beware that this class can only be used as a base class and cannot be initialized as <code>new Node()</code>. Let&#8217;s continue by examining the individual methods of this class:</p>
<p><strong>Node::Node(Node* Parent, const char* Name)</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
Node::Node(Node* Parent, const char* Name)
	: m_Name(Name)
{
	m_Parent = Parent;
} // Constructor
</pre>
<p>As you can see I&#8217;ve kept the constructor very simple. The default for both parameters is <code>NULL</code> as both are optional. A node does not necessarily need a parent and a node does not require a name. You can of course change this by removing the <code>= NULL</code> sections out of the header file and throwing and exception if <code>NULL</code> was found in the source file.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>Node::~Node(void)</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
Node::~Node(void)
{
	m_Parent = NULL;
	m_Children.clear();
} // Destructor
</pre>
<p>The class destructor is also very simple, it simply sets the pointer to the parent node to <code>NULL</code> and clears the children-vector.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>void Node::Update(void)</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
void Node::Update(void)
{
	if(!m_Children.empty())
	{
		for(size_t i = 0; i &lt; m_Children.size(); ++i)
		{
			if(NULL != m_Children[i])
			{
				m_Children[i]-&gt;Update();
			}
		}
	}
} // Update()
</pre>
<p>Still pretty simple, this method goes through the children-vector and calls the Update method on each child that does not equal <code>NULL</code>. The child object in return calls the Update method so the behavior is recursive.</p>
<p>This method was designed to be overriden and called as <code>Node::Update()</code> by the overriding method.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>Node* Node::GetParentNode(void) const</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
Node* Node::GetParentNode(void) const
{
	return(m_Parent);
}; // GetParentNode()
</pre>
<p>A &#8220;property&#8221; which simply returns a pointer to the parent node.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>void Node::SetParentNode(Node* NewParent)</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
void Node::SetParentNode(Node* NewParent)
{
	if(NULL != m_Parent)
	{
		m_Parent-&gt;RemoveChildNode(this);
	}
	m_Parent = NewParent;
}; // SetParentNode()
</pre>
<p>This method sets a new parent node for the selected node and removes the node from the old parent node&#8217;s children-vector.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>void Node::AddChildNode(Node* ChildNode)</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
void Node::AddChildNode(Node* ChildNode)
{
	if(NULL != ChildNode)
	{
		if(NULL != ChildNode-&gt;GetParentNode())
		{
			ChildNode-&lt;SetParentNode(this);
		}
		m_Children.push_back(ChildNode);
	}
}; // AddChildNode()
</pre>
<p>Adds the node to the children-vector and updates the parent to the new parent if a parent was set.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>void Node::RemoveChildNode(Node* ChildNode)</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
void Node::RemoveChildNode(Node* ChildNode)
{
	if(NULL != ChildNode &amp;&amp; !m_Children.empty())
	{
		for(size_t i = 0; i &lt; m_Children.size(); ++i)
		{
			if(m_Children[i] == ChildNode)
			{
				m_Children.erase(m_Children.begin() + i);
				break; // break the for loop
			}
		}
	}
}; // RemoveChildNode()
</pre>
<p>This method loops through all of the child nodes and will remove the selected child node from the children-vector if found.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>const char* Node::GetNodeName(void) const</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
const char* Node::GetNodeName(void) const
{
	return(m_Name);
}; // GetNodeName()
</pre>
<p>A &#8220;property&#8221; which returns the name of the current node.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>const size_t Node::CountChildNodes(const bool &#038;RecursiveCount) const</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
const size_t Node::CountChildNodes(const bool &amp;RecursiveCount) const
{
	if(!RecursiveCount)
	{
		return(m_Children.size());
	}
	else
	{
		size_t Retval = m_Children.size();
		for(size_t i = 0; i &lt; m_Children.size(); ++i)
		{
			Retval += m_Children[i]-&gt;CountChildNodes(true);
		}
		return(Retval);
	}
}; // CountChildNodes()
</pre>
<p>Method counts all of the child nodes, recursive if required. If the recursive Boolean is set to true, the function will iterate over the entire hierarchy from the current node down and return a full node-count.</p>
<hr style="width: 200px; margin: 10px auto;" />
<p><strong>Node* Node::GetChildNodeByName(const char *SearchName)</strong></p>
<pre style="overflow: auto; border: 1px solid silver; padding: 5px;">
Node* Node::GetChildNodeByName(const char *SearchName)
{
	Node* Retval = NULL;
	if(!m_Children.empty())
	{
		for(size_t i = 0; i &lt; m_Children.size(); ++i)
		{
			if(0 == strcmp(m_Children[i]-&gt;m_Name, SearchName))
			{
				Retval = m_Children[i];
				break; // break the for loop
			}
		}
	}
	return(Retval);
}; // GetChildNodeByName()
</pre>
<p>This method will return a node referenced by name if it exists, otherwise it will return <code>NULL</code>. The function is fairly expensive and should be replaced with something more efficient but is fine for small trees and demos.</p>
<p><strong>Conclusion:</strong><br />
As you can see, the scene graph is quite simple but once you understand how to implement one customization isn&#8217;t hard. Things you might want to change are passing a time value to the Update() method of Node so that your nodes may have a notion of time passed between calls, something faster than std::vector for storage and implementing a type-checking mechanism.</p>
<p>Regardless of the above, if you&#8217;re slapping together a quick demo that&#8217;s not performance sensitive the code with tweaks should do fine. <span style="background: #FFE;">Let me know if I missed or something or screwed something up since this post has been sitting in limbo for quite a while.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.scriptionary.com/2009/02/17/simple-scene-graph-in-c/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Little Endians, Bytes and Binary</title>
		<link>http://blog.scriptionary.com/2009/02/17/little-endians-bytes-and-binary/</link>
		<comments>http://blog.scriptionary.com/2009/02/17/little-endians-bytes-and-binary/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 16:08:54 +0000</pubDate>
		<dc:creator>Eddy Luten</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[snippets]]></category>

		<guid isPermaLink="false">http://blog.scriptionary.com/?p=70</guid>
		<description><![CDATA[I&#8217;ve recently had the need to read an entire file into a byte array but still had the need to extract integers from it. Turns out, it&#8217;s very possible to do this but platform dependently since the byte-ordering (or endianness) on different machines can differ.
For example, Little-Endian machine A has an integer that it needs [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently had the need to read an entire file into a byte array but still had the need to extract integers from it. Turns out, it&#8217;s very possible to do this but platform dependently since the byte-ordering (or <em>endianness</em>) on different machines can differ.</p>
<p>For example, Little-Endian machine <strong>A</strong> has an integer that it needs to write to disk: <code>12345</code>. Big-Endian machine <strong>B</strong> has the same integer that it needs to write to disk as well.</p>
<p>The hexadecimal representation of the file on machine <strong>A</strong> would look like: <code>00 00 30 39</code> while machine <strong>B</strong>&#8217;s output would look like: <code>39 30 00 00</code>.</p>
<p>If we were to read machine <strong>A</strong>&#8217;s file on machine <strong>B</strong>, the output would not be <code>12345</code> as expected but <code>245618442240</code> instead. Now that&#8217;s quite a problem. Any file written on machine <strong>A</strong> would be useless in any other environment.</p>
<p>In the meantime, be aware that there&#8217;s no way to determine if a file is Big or Little Endian so you would need to set a standard for your file. I use Little-Endian byte ordering since that&#8217;s my machine&#8217;s native format and 99% of the time, yours as the x86 family of processors is Little-Endian.</p>
<p>So in order to read any of the files we have on disk, regardless of endianness, we first need to detect the endianness of our current machine and somehow detect the endianness of the file we&#8217;re trying to read. This is not a big pain in the ass as you might suspect since machines, in addition to files, also order their memory in Big- or Little-Endian byte ordering.<br />
<span id="more-70"></span><br />
<strong>C++ Code:</strong>
<pre style="margin-bottom: 10px; background: #FFE; border: 1px solid silver;">const bool IsLittleEndian(void)
{
	static const signed int Bytes = 58;
	static const bool Test = (*(&amp;Bytes) != 58);
	return(Test);
}</pre>
<p>A little explanation to the code above: the first line in the function sets the value of the integer to 58 (the integer is static, so this will only be declared once) so that the value in hexadecimal becomes: <code>3A 00 00 00</code>.<br />
An integer is four bytes long so on a Little-Endian machine, the first byte should be our number, 58, which is smaller than the maximum size of one byte, 255, meaning that the number will not overflow to the next byte.<br />
The next line retrieves the address of the integer and compares the first byte of the integer at index zero with the number 58. If the machine is Big-Endian, the function will return false and true for Little-Endian.</p>
<p>Now that we have this out of the way, you can save your file in the endianness that you want so you retain portability. From this point on, I&#8217;m going to assume you have a Little-Endian system.</p>
<p>The next obstacle I faced in trying to convert an array of bytes into an integer was the actual conversion. Consider again our previous example of integer <code>12345</code> in Little-Endian: <code>39 30 00 00</code>. If we were to read this sequence of bytes into an integer from left to right, the number would be wrong again. Because of this we need to read the bytes one-by-one and insert them into the desired integer.</p>
<p><strong>C++ Code:</strong>
<pre style="margin-bottom: 10px; background: #FFE; border: 1px solid silver;">const size_t IntSize = sizeof(int);

const int DecodeInt(const char ByteArray[])
{
	int RetVal = 0;

	for(int i = int(IntSize - 1); i &gt; -1; &ndash;&ndash;i)
	{
		RetVal |= int(ByteArray[i] &amp; 0xFF);
		if(0 != i)
		{
			RetVal &lt;&lt;= 8;
		}
	}

	return(RetVal);
}</pre>
<p>Alright, that&#8217;s a bit of code there, let&#8217;s go over it line by line.</p>
<p><code>const size_t IntSize = sizeof(int);</code><br />
The first line is simply a constant I&#8217;ve added to improve readability a bit, it equals the size of an integer in bytes (4).</p>
<p><code>int RetVal = 0;</code><br />
The return value is a signed integer initialized to zero (so we don&#8217;t have numerical surprises).</p>
<p><code>const int DecodeInt(const char ByteArray[])</code><br />
The actual function takes a byte-array as parameter but will only process 4 bytes of information from it.</p>
<p><code>for(int i = int(IntSize - 1); i &gt; -1; &ndash;&ndash;i)</code><br />
As you might have noticed, the loop inside the function loops backwards, this is to convert from the format on disk to the format of a regular integer.The loop stops when the index -1 has been reached because we also want to process index 0.</p>
<p><code>RetVal |= int(ByteArray[i] &amp; 0xFF);</code><br />
This line is part one of the bread and butter of this function. The line logically OR-s the clamped (max 255, or 0xFF) byte value to the integer. This basically would result in something like:</p>
<pre style="margin-bottom: 10px; border: 1px solid silver;">
<strong>1</strong>00<strong>111</strong>0<strong>1</strong> (0x9D, some value from a byte-array)
<strong>1</strong>11<strong>111</strong>1<strong>1</strong> (0xFF, the 255 mask for clamping)
-------- AND
<strong>10011101</strong> (0x9D, result is the same as 0x9D < 255)

10011101 (0x9D, the result of the AND operation)
00000000 (0x00, the integer RetVal's value at this point)
-------- OR
10011101 (0x9D, the result is the same, no clamping was necessary)</pre>
<p>If you're sure that the values you're using are between 0 and 255, you don't have to clamp to 255 but it's in there regardless. This is specifically handy for freak negative values that might pop up when reading from files and unsigned to signed casting.</p>
<p><code>if(0 != i){ RetVal &lt;&lt;= 8; }</code><br />
Translates to: if the current index is not the last (0), shift the value of RetVal 8 (amount of bits in a byte) positions to the left. This assures that the value that were assigned are in the correct position, the last iteration is not shifted since it will be inserted at the correct place.</p>
<p><strong>Sample iteration for value: 3258794</strong></p>
<pre style="margin-bottom: 10px; border: 1px solid silver;">{ 0xAA 0xB9 0x31 0x00 } = Byte Array for value 3258794

0000 0000 0000 0000 0000 0000 0000 0000 RetVal = 0x00
0000 0000 0000 0000 0000 0000 <span style="color:green">0000 0000</span> After OR-ing 0x00
0000 0000 0000 0000 <span style="color:green">0000 0000</span> <span style="color:red;">0000 0000</span> After Left Shift of 8
0000 0000 0000 0000 <span style="color:green">0000 0000</span> <span style="color:red;">0011 0001</span> After OR-ing 0x31
0000 0000 <span style="color:green">0000 0000</span> <span style="color:red;">0011 0001</span> <span style="color:blue">0000 0000</span> After Left Shift of 8
0000 0000 <span style="color:green">0000 0000</span> <span style="color:red;">0011 0001</span> <span style="color:blue">1011 1001</span> After OR-ing 0xB9
<span style="color:green">0000 0000</span> <span style="color:red;">0011 0001</span> <span style="color:blue">1011 1001</span> <span style="color: black">0000 0000</span> After Left Shift of 8
<span style="color:green">0000 0000</span> <span style="color:red;">0011 0001</span> <span style="color:blue">1011 1001</span> <span style="color: black">1010 1010</span> After OR-ing 0xAA

<strong>Result:</strong> 1100011011100110101010, or the decimal value of 3258794</pre>
<p>Good luck <img src='http://blog.scriptionary.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.scriptionary.com/2009/02/17/little-endians-bytes-and-binary/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Amount of Digits in an Integer</title>
		<link>http://blog.scriptionary.com/2008/10/11/amount-of-digits-in-an-integer/</link>
		<comments>http://blog.scriptionary.com/2008/10/11/amount-of-digits-in-an-integer/#comments</comments>
		<pubDate>Sat, 11 Oct 2008 20:59:26 +0000</pubDate>
		<dc:creator>Eddy Luten</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[snippets]]></category>

		<guid isPermaLink="false">http://blog.scriptionary.com/?p=45</guid>
		<description><![CDATA[Here&#8217;s another little snippet that might come in handy in your programmatic travels. I&#8217;ll show you an example of usage below, which might also be of interest to you. The code presented is in C, not C++. First, the code to count the amount of digits in an integer:

const size_t intlen(long long int Num)
{
	size_t out [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s another little snippet that might come in handy in your programmatic travels. I&#8217;ll show you an example of usage below, which might also be of interest to you. The code presented is in C, not C++. First, the code to count the amount of digits in an integer:</p>
<pre style="border: 1px solid rgb(204, 204, 204); margin: 5px; padding: 5px; overflow: auto; background-color: rgb(239, 239, 239);">
const size_t intlen(long long int Num)
{
	size_t out = 1;
	while (Num /= 10) ++out;
	return out;
}; // numlen
</pre>
<p>Looks simple enough; simply count the amount of times we can divide the number by 10 without the result being zero. This function takes a copy of an <code>int</code> (or <code>long long</code>) so that we don&#8217;t have to copy the number inside the body of the function and returns a <code>size_t</code> (<code>unsigned int</code>).</p>
<p>As for the usage example, it&#8217;s a bit more complex and might seem a bit &ldquo;obfuscated&rdquo; at first, but fear not, I will explain below.</p>
<pre style="border: 1px solid rgb(204, 204, 204); margin: 5px; padding: 5px; overflow: auto; background-color: rgb(239, 239, 239); height: 250px;">
void inttoa(long long int Num, char** RetVal)
{
	size_t neg = (Num < 0);
	size_t len = intlen(Num) + (neg ? 1 : 0); // add one for the "-" character
	size_t i;

	*RetVal = (char *) malloc(sizeof(char) * (len + 1));

	if (NULL == (*RetVal))
		return; // bad malloc

	if (neg)
		Num = -Num; // make pos if neg

	for (i = len; i; (Num /= 10), --i) // loop backwards
		(*RetVal)[i-1] = (char)((Num % 10) + '0'); // add modulo to char zero

	if (neg)
		(*RetVal)[0] = '-'; // first char

	(*RetVal)[len] = 0; // last char, null terminator
}; // intttoa
</pre>
<p>As you might have suspected, this function converts an integer to character string. First, we determine if the number is negative and retrieve its length with the help of the previous function. We allocate a character string with the length determined and start appending a character to the string.</p>
<p>You can use it like so:</p>
<pre style="border: 1px solid rgb(204, 204, 204); margin: 5px; padding: 5px; overflow: auto; background-color: rgb(239, 239, 239);">
char* mystring; // don't allocate, don't do anything
inttoa(42, &#038;mystring); // simply pass it to the function

// do things with the string

free(mystring); // you *do* have to free() the string though
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.scriptionary.com/2008/10/11/amount-of-digits-in-an-integer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flattening Multidimensional Arrays</title>
		<link>http://blog.scriptionary.com/2008/10/11/flattening-multidimensional-arrays/</link>
		<comments>http://blog.scriptionary.com/2008/10/11/flattening-multidimensional-arrays/#comments</comments>
		<pubDate>Sat, 11 Oct 2008 21:25:25 +0000</pubDate>
		<dc:creator>Eddy Luten</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[snippets]]></category>

		<guid isPermaLink="false">http://blog.scriptionary.com/?p=44</guid>
		<description><![CDATA[Edit: Thank you, fixitman for the insightful comment; the code has been fixed to work with non-square arrays as well.
In an effort to produce a better performing multidimensional array, I would like to share the following with you. Say we have a Matrix (or multidimensional array) of 5 x 5 integer elements, M. In order [...]]]></description>
			<content:encoded><![CDATA[<div style="margin: 5px; border: 1px solid silver; background-color: #FFE; padding: 5px;"><strong>Edit:</strong> Thank you, fixitman for the <a href="#comment-1452">insightful comment</a>; the code has been fixed to work with non-square arrays as well.</div>
<p>In an effort to produce a better performing multidimensional array, I would like to share the following with you. Say we have a Matrix (or multidimensional array) of <code>5 x 5</code> integer elements, <em>M</em>. In order to allocate such an array in C++, we use the following code:<br />
<span id="more-44"></span></p>
<pre style="border: 1px solid rgb(204, 204, 204); margin: 5px; padding: 5px; overflow: auto; background-color: rgb(239, 239, 239);">
const size_t Width = 5;
const size_t Height = 5;
int** Array = new int*[Height]; // 2-Dimensional

for (size_t i = 0; i < Height; ++i)
	Array[i] = new int[Width];

// etcetera.

for (size_t i = 0; i < Height; ++i)
	delete[] Array[i];
delete[] Array;</pre>
<p>In order to counter-act this looping behavior, which, in many cases will slow down the program upon allocation and freeing of memory (due to the loops), the array may be flattened like so:</p>
<pre style="border: 1px solid rgb(204, 204, 204); margin: 5px; padding: 5px; overflow: auto; background-color: rgb(239, 239, 239);">
const size_t Width = 5;
const size_t Height = 5;
int* Array = new int[Width*Height]; // 1-Dimensional

// etcetera.

delete [] Array;</pre>
<p>Thus causing fewer allocations than before, and eliminating loops entirely. You might think that the array is entirely out of order, and no logical index can be obtained for selecting e.g.: <code>Array[2][3];</code>. This is where a simple calculation comes in handy.</p>
<p><code>A<sub>X,Y</sub> = (Y x Width) + X</code></p>
<p>With this calculation we can select our element by doing the following:</p>
<pre style="border: 1px solid rgb(204, 204, 204); margin: 5px; padding: 5px; overflow: auto; background-color: rgb(239, 239, 239);">
[...]
// desired position:
const size_t X = 2;
const size_t Y = 3;
[...]
int RequestedInteger = Array[(Y*Width)+X];
</pre>
<style type="text/css">
.exampleTable
{
	float: right;
	margin:0px;
	margin-left: 10px;
	padding:0px;
	text-align: center;
	font-family: monospace;
	border: 1px solid #333;
}
.exampleTable tr
{
	border-collapse: collapse;
}
.exampleTable td, th
{
	padding: 2px;
}
.exampleTable td
{
	border: 1px solid #333;
}
.exampleTable th
{
	background-color: #EEE;
}
</style>
<table class="exampleTable" cellpadding="0" cellspacing="0">
<tr>
<th>O</th>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th rowspan="7" style="vertical-align: top;">X</th>
</tr>
<tr>
<th>0</th>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<th>1</th>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<th>2</th>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<th>3</th>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
</tr>
<tr>
<th>4</th>
<td>20</td>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<th colspan="6" style="text-align: left;">Y</th>
</tr>
</table>
<p>This works because if we visualize our flattened array's indexes in a table (right &rarr;), we can see that if we take Y (3) and multiply it by the Width (5) we get the appropriate first index of the row (15, or 0,3). If we add X (2) we have selected index 17, which is the index we want (X<sub>2</sub>, Y<sub>3</sub>).</p>
<p>This implementation is faster because we only allocate one single block of memory of X*Y instead of X*Y blocks of memory. The disadvantage of this is that to select any index from the array, you will have to calculate the expression, but this is a minor operation compared to the allocation/de-allocation loops.</p>
<div style="clear:both;></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.scriptionary.com/2008/10/11/flattening-multidimensional-arrays/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CriticalSection wrapper class</title>
		<link>http://blog.scriptionary.com/2008/08/22/criticalsection-wrapper-class/</link>
		<comments>http://blog.scriptionary.com/2008/08/22/criticalsection-wrapper-class/#comments</comments>
		<pubDate>Fri, 22 Aug 2008 15:09:39 +0000</pubDate>
		<dc:creator>Eddy Luten</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[posix]]></category>
		<category><![CDATA[pthreads]]></category>
		<category><![CDATA[snippets]]></category>
		<category><![CDATA[Win32]]></category>

		<guid isPermaLink="false">http://blog.scriptionary.com/?p=41</guid>
		<description><![CDATA[What: A C++ wrapper around both WINAPI (Microsoft Windows) and PThreads (POSIX threads) functionality.
Why: To abstract cross platform functionality.
Remarks: On  windows, CRITICAL_SECTION objects cannot be shared cross-process. This means that the class is tied to your application or DLL process. Comments are in Doxygen/Javadoc style.


#ifdef _WIN32
#include &#60;windows.h&#62;
#else
#include &#60;unistd.h&#62;
#include &#60;pthread.h&#62;
#endif

/**
 * @class A wrapper-class around [...]]]></description>
			<content:encoded><![CDATA[<p><strong>What:</strong> A C++ wrapper around both WINAPI (Microsoft Windows) and PThreads (POSIX threads) functionality.<br />
<strong>Why:</strong> To abstract cross platform functionality.<br />
<strong>Remarks:</strong> On  windows, CRITICAL_SECTION objects cannot be shared cross-process. This means that the class is tied to your application or DLL process. Comments are in Doxygen/Javadoc style.<br />
<span id="more-41"></span></p>
<pre style="overflow: auto; height: 400px; background-color: #EFEFEF; margin: 5px; padding: 5px; border: 1px solid #CCC;">
#ifdef _WIN32
#include &lt;windows.h&gt;
#else
#include &lt;unistd.h&gt;
#include &lt;pthread.h&gt;
#endif

/**
 * @class A wrapper-class around Critical Section functionality, WIN32 &#038; PTHREADS.
 */
class CriticalSection
{
public:
	/**
	 * @brief CriticalSection class constructor.
	 */
	explicit CriticalSection(void)
	{
	#ifdef _WIN32
		if (0 == InitializeCriticalSectionAndSpinCount(&#038;this-&gt;m_cSection, 0))
			throw("Could not create a CriticalSection");
	#else
		if (pthread_mutex_init(&#038;this-&gt;m_cSection, NULL) != 0)
			throw("Could not create a CriticalSection");
	#endif
	}; // CriticalSection()

	/**
	 * @brief CriticalSection class destructor
	 */
	~CriticalSection(void)
	{
		this-&gt;WaitForFinish(); // acquire ownership
	#ifdef _WIN32
		DeleteCriticalSection(&#038;this-&gt;m_cSection);
	#else
		pthread_mutex_destroy(&#038;this-&gt;m_cSection);
	#endif
	}; // ~CriticalSection()

	/**
	 * @fn void WaitForFinish(void)
	 * @brief Waits for the critical section to unlock.
	 * This function puts the waiting thread in a waiting
	 * state.
	 * @see TryEnter()
	 * @return void
	 */
	void WaitForFinish(void)
	{
		while(!this-&gt;TryEnter())
		{
		#ifdef _WIN32
			Sleep(1); // put waiting thread to sleep for 1ms
		#else
			usleep(1000); // put waiting thread to sleep for 1ms (1000us)
		#endif
		};
	}; // WaitForFinish()

	/**
	 * @fn void Enter(void)
	 * @brief Wait for unlock and enter the CriticalSection object.
	 * @see TryEnter()
	 * @return void
	 */
	void Enter(void)
	{
		this-&gt;WaitForFinish(); // acquire ownership
	#ifdef _WIN32
		EnterCriticalSection(&#038;this-&gt;m_cSection);
	#else
		pthread_mutex_lock(&#038;this-&gt;m_cSection);
	#endif
	}; // Enter()

	/**
	 * @fn void Leave(void)
	 * @brief Leaves the critical section object.
	 * This function will only work if the current thread
	 * holds the current lock on the CriticalSection object
	 * called by Enter()
	 * @see Enter()
	 * @return void
	 */
	void Leave(void)
	{
	#ifdef _WIN32
		LeaveCriticalSection(&#038;this-&gt;m_cSection);
	#else
		pthread_mutex_unlock(&#038;this-&gt;m_cSection);
	#endif
	}; // Leave()

	/**
	 * @fn bool TryEnter(void)
	 * @brief Attempt to enter the CriticalSection object
	 * @return bool(true) on success, bool(false) if otherwise
	 */
	bool TryEnter(void)
	{
		// Attempt to acquire ownership:
	#ifdef _WIN32
		return(TRUE == TryEnterCriticalSection(&#038;this-&gt;m_cSection));
	#else
		return(0 == pthread_mutex_trylock(&#038;this-&gt;m_cSection));
	#endif
	}; // TryEnter()

private:
#ifdef _WIN32
	CRITICAL_SECTION m_cSection; //!&lt; internal system critical section object (windows)
#else
	pthread_mutex_t m_cSection; //!&lt; internal system critical section object (*nix)
#endif
}; // class CriticalSection
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.scriptionary.com/2008/08/22/criticalsection-wrapper-class/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>One to watch: MSDN Code Gallery</title>
		<link>http://blog.scriptionary.com/2008/04/02/one-to-watch-msdn-code-gallery/</link>
		<comments>http://blog.scriptionary.com/2008/04/02/one-to-watch-msdn-code-gallery/#comments</comments>
		<pubDate>Wed, 02 Apr 2008 14:05:17 +0000</pubDate>
		<dc:creator>Eddy Luten</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[free stuff]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[snippets]]></category>

		<guid isPermaLink="false">http://blog.scriptionary.com/2008/04/02/one-to-watch-msdn-code-gallery/</guid>
		<description><![CDATA[While reading Betsy Aoki&#8217;s blog I stumbled upon her post about Gotdotnet being dead. I&#8217;m not crying about it, I barely knew that site, but when you go to the old URL you&#8217;ll be presented with what seems to be Microsoft&#8217;s implementation of a resource dump: the MSDN Code Gallery &#8212; which is pretty neat.
Sure, [...]]]></description>
			<content:encoded><![CDATA[<p>While reading <a href="http://blogs.msdn.com/betsya/" target="_blank">Betsy Aoki&#8217;s blog</a> I stumbled upon her post about <a href="http://www.gotdotnet.com/" target="_blank">Gotdotnet</a> being dead. I&#8217;m not crying about it, I barely knew that site, but when you go to the old URL you&#8217;ll be presented with what seems to be Microsoft&#8217;s implementation of a resource dump: the <a href="http://code.msdn.microsoft.com/" target="_blank">MSDN Code Gallery</a> &#8212; which is pretty neat.</p>
<p>Sure, there are only 4 C++ related things so far but if you&#8217;re a .NET programmer this site is pretty nifty, it even allows you to post your own snippets or host your own discussion. Of course there&#8217;s a huge license you&#8217;ll have to obey to and you have to donate your firstborn to Microsoft before posting anything&#8230; but that&#8217;s besides the point <img src='http://blog.scriptionary.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.scriptionary.com/2008/04/02/one-to-watch-msdn-code-gallery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
