<?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>db-in&#039;s blog &#187; General</title>
	<atom:link href="http://db-in.com/blog/category/general/feed/" rel="self" type="application/rss+xml" />
	<link>http://db-in.com/blog</link>
	<description></description>
	<lastBuildDate>Mon, 05 Mar 2012 15:15:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Calculating Normals and Tangent Space</title>
		<link>http://db-in.com/blog/2012/03/calculating-normals-and-tangent-space/</link>
		<comments>http://db-in.com/blog/2012/03/calculating-normals-and-tangent-space/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 15:15:19 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[GLSL ES]]></category>
		<category><![CDATA[OpenGL ES]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1459</guid>
		<description><![CDATA[A full tutorial showing how to calculate Vertex Normals and Tangent Space. Using the most accurate approach creating a 100% function Normal, Tangent and Bitangent (also known as Binormal).]]></description>
			<content:encoded><![CDATA[<p>Hi guys!</p>
<p>In this article I&#8217;ll show how to calculate per-vertex Normals and the Tangent Space. Here you&#8217;ll see the most accurate technique, generating real Normals and breaking the vertex when necessary. This article is an intermediate part of the &#8220;All about Shaders&#8221; series. Would be nice if you&#8217;ve read the first part <a href="http://db-in.com/blog/2011/08/all-about-shaders-part-13/" title="All about Shaders – (part 1/3)" target="_blank">All about Shaders – (part 1/3)</a></p>
<p><span id="more-1459"></span></p>
<p><br/></p>
<h2><strong>At a glance</strong></h2>
<p>First off, the calculations and routines that we&#8217;ll create here is not an easy task, there are complexes concepts and calculations involved here. So, be sure you have this macro view:</p>
<ul>
<li>Usually the 3D softwares will export an Optimized Per-Vertex Normal, for those cases we can save our time, avoiding re-create the Normals. So we&#8217;ll create the Normal Vector ONLY when the Normals from 3D file was not optimized or don&#8217;t exist.</li>
<li>Non optimized Normals means that the same Normal vector was written many times by the 3D software. It happens in some 3D file formats, like COLLADA, that the same Normal vector can appear hundred times, making the parse processing very expensive.</li>
<li>It&#8217;s a good idea to calculate the Tangent Space always as possible (all that we need is Vertex Position and Vertex Texcoord).</li>
<li>The best way to deal with meshes using OpenGL is to use what we call &#8220;Array of Structures&#8221;, however I&#8217;ll show you a generice algorithym that can be used with &#8220;Structure of Arrays&#8221; as well.</li>
</ul>
<p>If these four bullets sounds like &#8220;Greek*&#8221; for you, I highly recommend you read some other articles before proceed:</p>
<ul>
<li><a href="http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13/" title="All about OpenGL ES 2.x – (part 1/3)" target="_blank">All about OpenGL ES 2.x – (part 1/3)</a></li>
<li><a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/" title="All about OpenGL ES 2.x – (part 2/3)" target="_blank">All about OpenGL ES 2.x – (part 2/3)</a></li>
<li><a href="http://db-in.com/blog/2011/05/all-about-opengl-es-2-x-part-33/" title="All about OpenGL ES 2.x – (part 3/3)" target="_blank">All about OpenGL ES 2.x – (part 3/3)</a></li>
</ul>
<p>(* well, if you are a greek guy, sorry for that and please, take this word as equivalent to &#8220;chinese&#8221; or something like that).</p>
<p>As I explained before, to calculate the Normals we just need the vertex position, but to calculate the Tangent Space we&#8217;ll need the texcoord already calculated. If the mesh we are working on doesn&#8217;t have texcoord we&#8217;ll skip the Tangent Space phase, because is not possible to create an arbitrary UV Map in the code, UV Maps are design dependents and change the way as the texture is made.</p>
<p>Hands at work!</p>
<p><br/></p>
<h2><strong>Calculating Normals &#8211; Step 1</strong></h2>
<p>In theory, the technique to calculate the face normals is simple: We&#8217;ll find the perpendicular vector for each face (triangle). However as you saw in the first tutorial of &#8220;<a href="http://db-in.com/blog/2011/08/all-about-shaders-part-13/#shading_types" target="_blank">All About Shaders</a>&#8220;, the face normals are not so good. So, we need to calculate the vertex normals.</p>
<p>The things become a little bit more complex when we try to calculate the vertex normals. Every Face Normal will affect the vertex that compose the face. One single vertex can be shared by multiple faces, so, the final Vertex Normal will be the averaged vector of each Face that share this Vertex. As each face has its own size, the averaged Vertex Normal vector should consider those differences.</p>
<div id="attachment_1461" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/09/adjacent_normal_example1.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/09/adjacent_normal_example1.jpg" alt="Vertices shared by multiple faces will have the resulting Normal as an average of all adjacent faces&#039; Normals." title="adjacent_normal_example" width="600" height="500" class="size-full wp-image-1461" /></a><p class="wp-caption-text">Vertices shared by multiple faces will have the resulting Normal as an average of all adjacent faces&#039; Normals.</p></div>
<p><a href="http://db-in.com/blog/wp-content/uploads/2011/09/teapot_strange1.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/09/teapot_strange1.jpg" alt="" title="teapot_strange" width="300" height="203" class="alignleft size-full wp-image-1462" /></a>Just with this concept, you can create the Normals, but they will seem strange in some meshes. Like this teapot at the left side. When I created my first Normals, I spent weeks trying to find what was wrong with my calculus or with this concept&#8230;  &#8220;Everything is OK, but only that fucking vertex is not. Why?&#8221;, I thought. Many others said that was a problem with my code, a problem with my memory allocation, and all other kinds of shits. But only after look closely to a great 3D software I found the problem. I&#8217;ll show you the same image that I spent hours looking to until I find the solution.</p>
<div id="attachment_1463" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/09/vertex_normal_example1.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/09/vertex_normal_example1.jpg" alt="Vertex Normals" title="vertex_normal_example" width="600" height="463" class="size-full wp-image-1463" /></a><p class="wp-caption-text">Vertex Normals</p></div>
<p>Did you notice something strange? This is a basic teapot mesh, many 3D softwares give you this to make tests with materials and lights. But this mesh has ONE single strange vertex: a vertex with 2 Normal Vectors. Is it possible? Actually, NO. The mesh structure must follow a pattern, so you can&#8217;t have all vertices with 1 Normal and only one vertex with 2 Normals. This is a very important point that no one talk about it, actually, I never seen anyone talking about this.</p>
<p>It&#8217;s time to understand what happens. Your mesh structure is not complete until you calculate the Normals. Why? Because some vertices will be &#8220;break/split&#8221; into two or more vertices by the Normals. This is what happens in that image. The 3D softwares will not show you this, but there are two vertices, with the same position and texcoords, but with different Normals. Obviously the 3D softwares prefer to omit this for performance reasons, but we can&#8217;t omit this fact to OpenGL. We must inform to the Shaders that there are two vertices instead of a single one.</p>
<p>And how will we know where to break a vertex? By the angle between faces. WOW, this thing of Normals is becoming very complex! Yeah, I told you that this is a very important and complex part. Let&#8217;s think by steps. Usually the light looks continuous on a surface until an angle of ~80º (like a sphere), however two faces with an angle > ~80º will form a hard edge, like the table&#8217;s corners. OK, now translating to English, this is what we&#8217;ll do:</p>
<ol>
<li>Calculate each face&#8217;s Normal.</li>
<li>Calculate the angle between face&#8217;s Normals.</li>
<li>At each group of ~80º we&#8217;ll create a new set of Normals.</li>
<li>Finally we&#8217;ll find the averaged Normal for each group, respecting the face&#8217;s size.</li>
</ol>
<p>Well, now it looks more simple, with just 4 simple steps. Nice! OK, let&#8217;s put our hands on code. First off, let&#8217;s create our Vector/Math functions.</p>
<table width="675">
<tbody>
<tr>
<th>Vector Math</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
// Early in definitions...
typedef struct
{
	float x;
	float y;
} vec2;

// Vector's distance.
static inline vec2 vec2Subtract(vec2 vecA, vec2 vecB)
{
	return (vec2){vecA.x - vecB.x, vecA.y - vecB.y};
}

typedef struct
{
	float x;
	float y;
	float z;
} vec3;

static const vec3 kvec3Zero = {0.0f, 0.0f, 0.0f};

// Vector's length.
static inline float vec3Length(vec3 vec)
{
	// Square root.
	return sqrtf(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
}

// Vector's normalization.
static inline vec3 vec3Normalize(vec3 vec)
{
	// Find the magnitude/length. This variable is called inverse magnitude (iMag)
	// because instead divide each element by this magnitude, let's do multiplication, it's faster.
	float iMag = vec3Length(vec);

	// Avoid divisions by 0.
	if (iMag != 0.0f)
	{
		iMag = 1.0f / iMag;

		vec.x *= iMag;
		vec.y *= iMag;
		vec.z *= iMag;
	}

	return vec;
}

// Vector's sum.
static inline vec3 vec3Add(vec3 vecA, vec3 vecB)
{
	return (vec3){vecA.x + vecB.x, vecA.y + vecB.y, vecA.z + vecB.z};
}

// Vector's distance.
static inline vec3 vec3Subtract(vec3 vecA, vec3 vecB)
{
	return (vec3){vecA.x - vecB.x, vecA.y - vecB.y, vecA.z - vecB.z};
}

// Checks for zero values.
vec3IsZero(vec3 vec)
{
	return (vec.x == 0.0f &#038;&#038; vec.y == 0.0f &#038;&#038; vec.z == 0.0f);
}

// The dot product returns the cosine of the angle formed by two vectors.
static float vec3Dot(vec3 vecA, vec3 vecB)
{
	return vecA.x * vecB.x + vecA.y * vecB.y + vecA.z * vecB.z;
}

// The cross product returns an orthogonal vector with the other two,
// that means, the new vector is mutually perpendicular to the other two.
static vec3 vec3Cross(vec3 vecA, vec3 vecB)
{
	vec3 vec;

	vec.x = vecA.y * vecB.z - vecA.z * vecB.y;
	vec.y = vecA.z * vecB.x - vecA.x * vecB.z;
	vec.z = vecA.x * vecB.y - vecA.y * vecB.x;

	return vec;
}

// Checks if there is a NaN value inside the informed vector.
// If a NaN value is found, it's changed to 0.0f (zero).
static vec3 vec3Cleared(vec3 vec)
{
	vec3 cleared;
	cleared.x = (vec.x != vec.x) ? 0.0f : vec.x;
	cleared.y = (vec.y != vec.y) ? 0.0f : vec.y;
	cleared.z = (vec.z != vec.z) ? 0.0f : vec.z;

	return cleared;
}
</pre>
<p>Now we&#8217;re ready to go further:</p>
<table width="675">
<tbody>
<tr>
<th>Calculating Face Normals</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
// Private variables...
// Assumes that all the variables that start with "_" is a private one
// and you must implement it by your self and some of those values must
// be present before you start:

// vec3 *_vertices    "array of vertices positions"   (required)
// vec3 *_texcoords   "array of texture coordinates"  (optional)
// vec3 *_normals     "array of normals"              (optional/to calculate)
// vec3 *_tangents    "array of tangents"             (to calculate)
// vec3 *_bitangents  "array of bitangents"           (to calculate)

// int  _vCount       "vertices count"                (required)
// int  _tCount       "texture coordinates count"     (optional)
// int  _nCount       "normals count"                 (optional/to calculate)
// int  _taCount      "tangents count"                (to calculate)
// int  _biCount      "bitangents count"              (to calculate)

// int *_faces        "array of face indices"         (required)
// int  _facesCount   "faces indices count"           (required)
// int  _facesStride  "stride of faces indices"       (required)

// Checks the crease angle for the normal calculations.
// This function creates and divides the normals for a vertex, recursively.
static unsigned int creaseAngle(unsigned int index, vec3 vector, vec3 **buffer, unsigned int *count, NSMutableDictionary *list)
{
	// Let's talk about this function later on.
}

// Calculating the Tangent Space.
void calculateTangentSpace()
{
	unsigned int i, length;
	unsigned int j, lengthJ;

	unsigned int *newFaces, *outFaces;
	unsigned int oldFaceStride = _facesStride;

	int i1, i2, i3;
	int vi1, vi2, vi3;
	int ti1, ti2, ti3;

	vec3 vA, vB, vC;
	vec2 tA, tB, tC;
	vec3 distBA, distCA;
	vec2 tdistBA, tdistCA;

	vec3 normal;
	vec3 tangent;
	vec3 bitangent;

	vec3 *normalBuffer;
	vec3 *tangentBuffer;
	vec3 *bitangentBuffer;

	NSMutableDictionary *multiples;

	Element *element;
	int vLength, vOffset;
	int nLength, nOffset;
	int tLength, tOffset;

	float area, delta;
	float *outValue;

	// Checks if the parsed mesh has Normals and Texture Coordinates.
	BOOL hasNormals = NO;// CUSTOM: Check if your mesh structure already has normals.
	BOOL hasTextures = YES;// CUSTOM: Check if your mesh structure already has texcoords.

	// Gets the vertex element.
	vLength = 4;// CUSTOM: Take the length of your vertex position component.
	vOffset = 0;// CUSTOM: Take the offset  of your vertex position component in the Array of Structures.

	// If the normal element doesn't exist yet, creates a new one.
	if (!hasNormals)
	{
		// CUSTOM: Create the Normal elements if it doesn't exist yet.
		// The element should be just as the vertex one, having a length and an offset.
		// IMPORTANT: Increate the stride of your Array of Structures (_facesStride).
	}

	// Gets the normal element.
	nLength = 3;// CUSTOM: Take the normal length.
	nOffset = 7;// CUSTOM: Take the normal offset. In this case (7) we consider it's after the texcoord.

	// If the texture coordinate element exist, gets it and create tangent and bitangent element.
	if (hasTextures)
	{
		tLength = 3;// CUSTOM: Take the texcoord length.
		tOffset = 4;// CUSTOM: Take the texcoord offset. In this case it's after the vertices positions.

		// CUSTOM: Here you should create the Tangent and Bitangent elements. Just as any
		// other element until here, they must have length and offset.
		// IMPORTANT: Increate the stride of your Array of Structures (_facesStride).
	}

	// Allocates memory to the new faces.
	newFaces = malloc(sizeof(int) * (_facesCount * _facesStride));

	// A priori, assumes that for each vertex exists only one normal.
	_nCount = _taCount = _biCount = _vCount;

	// Initializes the buffers for the tangent space elements.
	// This memory allocation must use calloc because they must be 0 (zero) value,
	// otherwise NaN values can be generated.
	normalBuffer = calloc(_nCount, sizeof(vec3));
	tangentBuffer = calloc(_taCount, sizeof(vec3));
	bitangentBuffer = calloc(_biCount, sizeof(vec3));

	// Initializes the dictionaries to deal with vertices with multiple normals in it.
	multiples = [[NSMutableDictionary alloc] init];

	// Loop through each triangle.
	length = _facesCount;
	for (i = 0; i < length; i += 3)
	{
		// Triangle Vertices. At this moment _faces is an ordered list of elements' indices:
		// iv1, it1, in1, iv2, in2, it2, iv3, it3, in3...
		//  |			   |			  |
		//  V			   V			  V
		// iv1,			  iv2,			 iv3
		// So the following lines will extract the indices of vertices that form a triangle.
		i1 = _faces[i * oldFaceStride + vOffset];
		i2 = _faces[(i + 1) * oldFaceStride + vOffset];
		i3 = _faces[(i + 2) * oldFaceStride + vOffset];

		// Calculates the vertex indices in the array of vertices.
		vi1 = i1 * vLength;
		vi2 = i2 * vLength;
		vi3 = i3 * vLength;

		// Retrieves 3 vertices from the array of vertices.
		vA = (vec3){_vertices[vi1], _vertices[vi1 + 1], _vertices[vi1 + 2]};
		vB = (vec3){_vertices[vi2], _vertices[vi2 + 1], _vertices[vi2 + 2]};
		vC = (vec3){_vertices[vi3], _vertices[vi3 + 1], _vertices[vi3 + 2]};

		// Calculates the vector of the edges, the distance between the vertices.
		distBA = vec3Subtract(vB, vA);
		distCA = vec3Subtract(vC, vA);

		//*************************
		//	Normals
		//*************************
		if (!hasNormals)
		{
			// Calculates the face normal to the current triangle.
			normal = vec3Cross(distBA, distCA);

			// Searches for crease angles considering the adjacent triangles.
			// This function also initialize new blocks of memory to the buffer, setting them to 0 (zero).
			i1 = creaseAngle(i1, normal, &#038;normalBuffer, &#038;_nCount, multiples);
			i2 = creaseAngle(i2, normal, &#038;normalBuffer, &#038;_nCount, multiples);
			i3 = creaseAngle(i3, normal, &#038;normalBuffer, &#038;_nCount, multiples);

			// Averages the new normal vector with the oldest buffered.
			normalBuffer[i1] = vec3Add(normal, normalBuffer[i1]);
			normalBuffer[i2] = vec3Add(normal, normalBuffer[i2]);
			normalBuffer[i3] = vec3Add(normal, normalBuffer[i3]);
		}
		else
		{
			// If the parsed file has normals in it, retrieves their indices in the array of normals.
			vi1 = _faces[i * oldFaceStride + nOffset] * nLength;
			vi2 = _faces[(i + 1) * oldFaceStride + nOffset] * nLength;
			vi3 = _faces[(i + 2) * oldFaceStride + nOffset] * nLength;

			// Retrieves the normals.
			vA = (vec3){_normals[vi1], _normals[vi1 + 1], _normals[vi1 + 2]};
			vB = (vec3){_normals[vi2], _normals[vi2 + 1], _normals[vi2 + 2]};
			vC = (vec3){_normals[vi3], _normals[vi3 + 1], _normals[vi3 + 2]};

			// Calculates the face normal to the current triangle.
			normal = vec3Add(vec3Add(vA, vB), vC);
		}

// CONTINUE...
</pre>
<p>Let's understand all those lines:</p>
<ul>
<li><strong>Lines 1-16</strong>: Definition of the output variables.</li>
<li><strong>Lines 20-23</strong>: A very important function to calculate the crease angle between faces. We'll discuss more about it later on.</li>
<li><strong>Lines 28-59</strong>: Defining the variables we'll use to calculate the Normals and the Tangent Space.</li>
<li><strong>Lines 62-63</strong>: CUSTOM CODE. Checks if there are Normals and Texture Coordinates already calculated in your mesh structure.</li>
<li><strong>Lines 66-67</strong>: CUSTOM CODE. Gets the length of each Vertex set (usually 3 or 4) and its offset in the Array of Faces.</li>
<li><strong>Lines 70-75</strong>: CUSTOM CODE. If there is no previous calculated Normals, create a new element and define its length (usually 3) and its offset in the Array of Faces.</li>
<li><strong>Lines 78-79</strong>: CUSTOM CODE. Gets the length of each Normal set (usually 3) and its offset in the Array of Faces.</li>
<li><strong>Lines 82-90</strong>: CUSTOM CODE. If there is a calculated Texture Coordinates, then create the Tangent and Bitangent elements. As both Tangent and Bitangent will follow the same elements rule, so you just need to define the length and offset in face for one of them.</li>
<li><strong>Lines 93-106</strong>: Allocating the necessary memory for the calculations.</li>
<li><strong>Lines 109-110</strong>: Starting the loop through all triangles of your mesh.</li>
<li><strong>Lines 118-120</strong>: Getting the indices form the current working triangle.</li>
<li><strong>Lines 123-130</strong>: Getting the vertices related to the current triangle.</li>
<li><strong>Lines 133-134</strong>: Calculating the distance between triangle's vertices. Depending on the order which you calculate this distance, the resulting normal vector direction can change. So, be careful about changing this order.</li>
<li><strong>Lines 142-153</strong>: If there are no previous normals. The cross product between the calculated distances will generate a perpendicular vector, it's the face normal to the current triangle (<a href="http://www.euclideanspace.com/maths/algebra/vectors/vecAlgebra/cross/index.htm" target="_blank">Cross Product info</a>). Then the crease angles are calculated, so we add the current normal vector to the normalBuffer. When we sum two vectors we are automatically calculating the middle vector. (<a href="http://www.euclideanspace.com/maths/algebra/vectors/vecAlgebra/index.htm" target="_blank">Add Vector info</a>).<br />
IMPORTANT: We're not normalizing the vector in this step, by doing so we make sure each triangle area (size) will be considered, because they have different lengths.</li>
<li><strong>Lines 158-168</strong>: If there are previous calculated normals. We calculate the current face normal, because the final format for normals are always vertex normal, not face normal. For the next steps we'll need the face normal.</li>
</ul>
<p><br/></p>
<h2><strong>The Crease Angle - Step 2</strong></h2>
<p>As I said before, the crease angle is a crucial part to create perfect normals, otherwise your normals will look correct for some meshes but very strange in other ones. My crease angle is recursive, that means, it will automatically break the vertex index and count as many times as necessary. So if one single vertex has 3 different normals, this function will break it 3 times.</p>
<p>This function must be called once per vertex. In the above code it's called at:<br />
<code>i1 = creaseAngle(i1, normal, &#038;normalBuffer, &#038;_nCount, multiples);<br />
i2 = creaseAngle(i2, normal, &#038;normalBuffer, &#038;_nCount, multiples);<br />
i3 = creaseAngle(i3, normal, &#038;normalBuffer, &#038;_nCount, multiples);</code></p>
<p>So the original vertex index can become a new index and this new one will be used in new normal vector and in tangent space (tangent and bitanget).</p>
<table width="675">
<tbody>
<tr>
<th>Calculating Crease Angle</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
// Defines the maximum crease angle ~80.
#define kCreaseAngle		0.2

// Checks the crease angle for the normal calculations.
// This function creates and divides the normals to a vertex.
static unsigned int creaseAngle(unsigned int index,
								vec3 vector,
								vec3 **buffer,
								unsigned int *count,
								NSMutableDictionary *list)
{
	NSNumber *newIndex, *oldIndex;

	// Eliminates the NaN points.
	(*buffer)[index] = vec3Cleared((*buffer)[index]);

	// Checks if the informed normal vector is not zero.
	if (!vec3IsZero((*buffer)[index]))
	{
		// Calculates the cosine of the angle between the current normal vector and the
		// averaged normal in the buffer.
		float cos = vec3Dot(vec3Normalize(vector), vec3Normalize((*buffer)[index]));

		// If the cosine is greater than the crease angle, that means the current normal vector
		// forms an acceptable angle witht the averaged normal in the buffer. Otherwise, proceeds and
		// creates a new normal vector to the current triangle face.
		if (cos <= kCreaseAngle)
		{
			// Tries to retrieve an already buffered normal with the same bend.
			oldIndex = [NSNumber numberWithInt:index];
			newIndex = [list objectForKey:oldIndex];

			// If no buffer was found, create a new register to the current normal vector.
			if (newIndex == nil)
			{
				// Retrieves the new index and stores its value as a linked list to the old one.
				newIndex = [NSNumber numberWithInt:*count];
				[list setObject:newIndex forKey:oldIndex];
				index = [newIndex intValue];

				// Reallocates the buffer and set the new buffer value to zero, avoiding NaN.
				*buffer = realloc(*buffer, NGL_SIZE_VEC3 * ++*count);
				(*buffer)[index] = kvec3Zero;
			}
			// Otherwise, repeat the process with the buffered value to check for new crease angles.
			else
			{
				index = creaseAngle([newIndex intValue], vector, buffer, count, list);
			}
		}
	}

	return index;
}
</pre>
<p>Understanding line by line:</p>
<ul>
<li><strong>Line 12</strong>: Clearing any possible NaN value. If a NaN value is found, it'll be set to 0.0f (zero).</li>
<li><strong>Line 15</strong>: Making sure that an empty buffer index will be skipped, because there is no reason to calculate the crease angle between a face and no other.</li>
<li><strong>Line 19</strong>: Calculating the "dot" product (<a href="http://www.euclideanspace.com/maths/algebra/vectors/vecAlgebra/dot/index.htm" target="_blank">Dot Product info</a>) we get the cosine of the angle formed between two faces. These faces are: The new normal vector and the value that is already in the normal buffer. Both of them must be normalized at this point, otherwise their lengths will affect the resulting dot product.</li>
<li><strong>Line 24</strong>: Check if the calculated cosine is bellow the crease angle. So, if a cosine value is lower than the crease angle it means the calculated angle is higher than the maximum angle. Then the process of breaking the buffer index will start.</li>
<li><strong>Lines 27-31</strong>: Creating NSNumbers. The old value is, actually, the current index parameter. The line 28 tries to retrieve if there is an already calculated broken index referenced by the current index. If there is a previous calculated reference, that means, if the current index was broken before, then the crease angle function will be called again. Otherwise, the process of breaking the buffer index will continue.</li>
<li><strong>Lines 34-36</strong>: The new buffer index will be created in the end of the current buffer array. This new index will be stored and linked with the current index. So, if the current index appear again we already know where is it broken index.</li>
<li><strong>Lines 39-40</strong>: Reallocating the memory of the buffer array and setting the new index to zero, avoiding NaN values.</li>
<li><strong>Line 50</strong>: The returned index will always be one of these two situations:
<ol>
<li>An empty buffer index (zero vector).</li>
<li>A buffer index in which its stored normal forms an acceptable angle with the new normal.</li>
</ol>
</li>
</ul>
<p>Nice! Now we have the correct calculated Normals, respecting the crease angle. Besides if there is a previous calculated normals, this routine respects that and calculates only the face normal again.</p>
<p>Now it's time to enter in the Tanget Space.</p>
<p><br/></p>
<h2><strong>Calculating the Tanget Space - Step 3</strong></h2>
<p>As you know the Tangent Space is formed by the Tangent Vector and the Bitangent Vector. Just to make this point clear, the word "Binormal" is wrong in the 3D context. Because a 2D circle can have a Binormal, however there is only one Normal Vector in the 3D space. So the perpendicular angle between the Normal and the Tangent is the Bitangent. Some guys still calling as Binormal, we can understand what they want to say, but we know this term is a misspelling, there is no Binormal in the 3D space.</p>
<p>OK, now let's understand the concept of the Tangent Space.</p>
<p>The Tangent Space is a local stuff related at how the light interacts on each face of the surface. But the tangent space doesn't exist in the reality, right? Right, it doesn't. The tangent space is something created as a workaround to use the "Bump Technique". Now a day, there are many bump techniques, like bump map, parallax map , displacement map and many others. Independent of the technique the tangent space vector must be calculated.</p>
<p>The tangent and bitangent are orthogonal vector with the Normal and instruct us about the direction of the face's texture coordinate (U and V map directions). This direction will be used to calculate the light based on the RGB colors of the bump image file. </p>
<p>So in short, the Tangent Space is just a convention that we create as a workaround the bump technique. Here is how we'll calculate the Tangent Space.</p>
<table width="675">
<tbody>
<tr>
<th>Calculating Tangent Space</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">

// CONTINUING...

		//*************************
		//  Tangent Space
		//*************************
		if (hasTextures)
		{
			// The crease angle process produces splits on the per-vertex normals, as the tangent space
			// must be orthogonalized, the tangent and bitanget follow those splits.
			if (_nCount > _taCount)
			{
				// Normals, Tangents and Bitangents buffers will always have the same number of elements.
				tangentBuffer = realloc(tangentBuffer, sizeof(vec3) * _nCount);
				bitangentBuffer = realloc(bitangentBuffer, sizeof(vec3) * _nCount);

				// Setting the brand new buffers to 0 (zero).
				lengthJ = _nCount;
				for (j = _taCount - 1; j < lengthJ; ++j)
				{
					tangentBuffer[j] = kvec3Zero;
					bitangentBuffer[j] = kvec3Zero;
				}

				_taCount = _biCount = _nCount;
			}

			// Retrieves texture coordinate indices.
			ti1 = _faces[i * oldFaceStride + tOffset] * tLength;
			ti2 = _faces[(i + 1) * oldFaceStride + tOffset] * tLength;
			ti3 = _faces[(i + 2) * oldFaceStride + tOffset] * tLength;

			// Retrieves the texture coordinates.
			tA = (vec2){_texcoords[ti1], _texcoords[ti1 + 1]};
			tB = (vec2){_texcoords[ti2], _texcoords[ti2 + 1]};
			tC = (vec2){_texcoords[ti3], _texcoords[ti3 + 1]};

			// Calculates the vector of the texture coordinates edges, the distance between them.
			tdistBA = vec2Subtract(tB, tA);
			tdistCA = vec2Subtract(tC, tA);

			// Calculates the triangle's area.
			area = tdistBA.x * tdistCA.y - tdistBA.y * tdistCA.x;

			//*************************
			//  Tangent
			//*************************
			if (area == 0.0f)
			{
				tangent = kvec3Zero;
			}
			else
			{
				delta = 1.0f / area;

				// Calculates the face tangent to the current triangle.
				tangent.x = delta * ((distBA.x * tdistCA.y) + (distCA.x * -tdistBA.y));
				tangent.y = delta * ((distBA.y * tdistCA.y) + (distCA.y * -tdistBA.y));
				tangent.z = delta * ((distBA.z * tdistCA.y) + (distCA.z * -tdistBA.y));
			}

			// Averages the new tagent vector with the oldest buffered.
			tangentBuffer[i1] = vec3Add(tangent, tangentBuffer[i1]);
			tangentBuffer[i2] = vec3Add(tangent, tangentBuffer[i2]);
			tangentBuffer[i3] = vec3Add(tangent, tangentBuffer[i3]);

			//*************************
			//  Bitangent
			//*************************
			// Calculates the face bitangent to the current triangle,
			// completing the orthogonalized tangent space.
			bitangent = vec3Cross(normal, tangent);

			// Averages the new bitangent vector with the oldest buffered.
			bitangentBuffer[i1] = vec3Add(bitangent, bitangentBuffer[i1]);
			bitangentBuffer[i2] = vec3Add(bitangent, bitangentBuffer[i2]);
			bitangentBuffer[i3] = vec3Add(bitangent, bitangentBuffer[i3]);
		}

// CONTINUE...
</pre>
<p>Understanding line by line:</p>
<ul>
<li><strong>Line 6</strong>: Just create tangent space if there is texture coordinates on the mesh.</li>
<li><strong>Lines 10 - 25</strong>: Checking if the "Crease Angle" routine changed the normals. If so, adjust the tangents and bitangents buffers to have the same size as the normals buffer.</li>
<li><strong>Lines 27 - 42</strong>: Calculates the direction of the UV coordinates and the area of the current face (triangle).</li>
<li><strong>Lines 47 - 64</strong>: Calculates the tangent vector for the current triangle and add this value into the tangents buffer.</li>
<li><strong>Lines 71 - 76</strong>: As the Tangent Space is formed by three orthogonal vectors, we can calculate the last one (bitangent) very easy just by calculating the cross product between the Normal and Tangent.</li>
</ul>
<p>OK, that's all, it's done!<br />
Now we have all that we need: Normals, Tangents and Bitangents. They all are pretty perfect now and we just need to bring their values back into the arrays format. You can make this last step as you wish, I'll show you here a way that I'm used to.</p>
<p><br/></p>
<h2><strong>Updating the Original Arrays - Step 4</strong></h2>
<p>OK, as I told you at the start, we'll use the "Array of Structures" in our final format. So we need to create/update that array and its indices based on the new elements, which may include Normals, Tangents and Bitangents.</p>
<p>I'll rewrite the <code>"calculateTangentSpace()"</code> function just to you take a look at it without breaks/continues.</p>
<table width="675">
<tbody>
<tr>
<th>Puting All Together</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">

// CONTINUING...		

		// Copies the oldest face indices and inserts the new tangent space indices.
		outFaces = newFaces + (i * _faceStride);
		lengthJ = _faceStride;
		for (j = 0; j < lengthJ; ++j)
		{
			*outFaces++ = (j < oldFaceStride) ? _faces[i * oldFaceStride + j] : i1;
		}

		outFaces = newFaces + ((i + 1) * _faceStride);
		for (j = 0; j < lengthJ; ++j)
		{
			*outFaces++ = (j < oldFaceStride) ? _faces[(i + 1) * oldFaceStride + j] : i2;
		}

		outFaces = newFaces + ((i + 2) * _faceStride);
		for (j = 0; j < lengthJ; ++j)
		{
			*outFaces++ = (j < oldFaceStride) ? _faces[(i + 2) * oldFaceStride + j] : i3;
		}
	}

	// Commits the changes for the original array of faces. At this time, it could looks like:
	// iv1, it1, in1, ita1, ibt1, iv2, it2, in2, ita2, ibt2,...
	_faces = realloc(_faces, sizeof(int) * (_faceNumber * _faceStride));
	memcpy(_faces, newFaces, sizeof(int) * (_faceNumber * _faceStride));

	// Reallocates the memory for the array of normals, if needed.
	if (!hasNormals)
	{
		_normals = realloc(_normals, sizeof(vec3) * _nCount);
	}

	// Reallocates the memory for the array of tangents and array of bitangents, if needed.
	if (hasTextures)
	{
		_tangents = realloc(_tangents, sizeof(vec3) * _taCount);
		_bitangents = realloc(_bitangents, sizeof(vec3) * _biCount);
	}

	// Loops through all new values of the tangent space, normalizing all the averaged vectors.
	length = _nCount;
	for (i = 0; i < length; i++)
	{
		// Puts the new normals, if needed.
		if (!hasNormals)
		{
			normal = vec3Normalize(normalBuffer[i]);
			outValue = _normals + (i * 3);
			*outValue++ = normal.x;
			*outValue++ = normal.y;
			*outValue = normal.z;
		}

		// Puts the new tangent and bitangent, if needed.
		// Isn't necessary here the Gram–Schmidt Orthogonalization process, because all the vectors
		// of the tangent space are already orthogonalized in reason of the crease angle approach.
		if (hasTextures)
		{
			tangent = vec3Normalize(tangentBuffer[i]);
			bitangent = vec3Normalize(bitangentBuffer[i]);

			outValue = _tangents + (i * 3);
			*outValue++ = tangent.x;
			*outValue++ = tangent.y;
			*outValue = tangent.z;

			outValue = _bitangents + (i * 3);
			*outValue++ = bitangent.x;
			*outValue++ = bitangent.y;
			*outValue = bitangent.z;
		}
	}

	// Frees the memories.
	free(newFaces);
	free(normalBuffer);
	free(tangentBuffer);
	free(bitangentBuffer);

	[multiples release];
}
</pre>
<p>Let's understand more about those last lines:</p>
<ul>
<li><strong>Lines 4 - 21</strong>: Using a pointer to insert the new face indices in the "newFaces" array, pointers is much faster than accessing the array by indices. These lines also respect the old face indices to place the new ones in the last positions.</li>
<li><strong>Lines 26 - 27</strong>: Updating the original "array of faces". As you can see in the comments, at this point the new "array of faces" will be as "index of vertex 1, index of texcoord 1, index of normal 1, index of tangent 1, index of bitangent 1, index of vertex 2, ...". Remember that in this article I'll not include the job of converting those array into one single "array of structures", however with this "array of faces" you can do it very easy.</li>
<li><strong>Lines 30 - 40</strong>: Preparing the Normals, Tangents and Bitangents to receive the calculated values.</li>
<li><strong>Lines 43 - 74</strong>: Updating the Normals, Tangents and Bitangents values using pointers.</li>
<li><strong>Lines 77 - 82</strong>: Clearing the allocated memory.</li>
</ul>
<p><br/><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p>WOW, a lot of code in this article, don't you think? I'll try to simplify the steps, as you may notice was only 4 steps until here. So, here is all that you need:</p>
<ol>
<li>Calculate the Normals or use the Face Normals you already has.</li>
<li>When you need to calculate the Normals you must calculate the crease angle and split the Normals according to this calculation.</li>
<li>Calculate the Tangent Space, which includes Tangent and Bitangent.</li>
<li>Update the original arrays, including the Normals, Tangents and Bitangents.</li>
</ol>
<p>OK, my friends, now you have all that you need to construct your preferable array for OpenGL ("array of structures" or "structure of arrays").</p>
<p>In my next article will continue the series about shaders. Let's talk about shader some techniques advanced skills in OpenGL ES Shaders.</p>
<p>If you have any doubts, just Tweet me:<br />
<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script><br />
<a href="http://twitter.com/share?&#038;url=&#038;text=@dineybomfim &#038;related=dineybomfim" class="twitter-share-button" data-related="dineybomfim" data-text="@dineybomfim " data-count="none" data-url="">Tweet</a> </p>
<p>See you soon!</p>
<p><iframe scrolling="no" src="http://db-in.com/downloads/apple/tribute_to_jobs.html" width="100%" height="130px"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2012/03/calculating-normals-and-tangent-space/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Objective-C Singleton</title>
		<link>http://db-in.com/blog/2011/12/objective-c-singleton/</link>
		<comments>http://db-in.com/blog/2011/12/objective-c-singleton/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 08:46:05 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Singleton]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1477</guid>
		<description><![CDATA[Singleton design pattern in Obj-C, the best way to create a Singleton class thread-safe. Includes a Xcode template for Singleton classes.]]></description>
			<content:encoded><![CDATA[<p>Hello fellows,</p>
<p>Due to many emails I have been received on the last months, I decide to create a single article to explain a little bit about the Singleton classes (also known as Singleton Pattern). I&#8217;ll focus here on Objective-C and Cocoa approach, however I&#8217;ll talk a little bit generally, so you can take the concept to other languages as well.</p>
<p>Let&#8217;s start!<br />
<span id="more-1477"></span></p>
<p><br/></p>
<h2><strong>Just Give me the Code!</strong></h2>
<p>Ok, ok. For who of you that just want the final code without protraction, here is it, you can choose a Xcode template or the pure code:</p>
<p><em><br />
<h3>Xcode template (Xcode 4)</h3>
<p></em><br />
A cool template for Xcode 4 that I created to use over my working machines.</p>
<ol>
<li>Download the zipped file bellow.</li>
<li>Unzip and copy the &#8220;db-in&#8221; folder to &#8220;/Library/Developer/Xcode/Templates/File Templates&#8221;</li>
<li>Open an Xcode project and try to add a new file. You will see a category called &#8220;db-in&#8221; on the left side, under the iOS platform.</li>
</ol>
<p><a href="http://db-in.com/downloads/xcode4_singleton_template.zip" onmousedown="_gaq.push(['_trackEvent', 'Singleton iOS', 'Xcode', 'Download']);"><img class="alignleft" title="download" src="http://db-in.com/imgs/download_button.png" alt="Download Xcode template files"/><br />
<strong>Download now</strong><br />
Xcode Singleton Class template<br />
40kb<br />
</a></p>
<p><em><br />
<h3>Pure code</h3>
<p></em><br />
Here is the code for your header and source files:</p>
<table width="675">
<tbody>
<tr>
<th>Header file (.h)</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
@interface MySingleton : NSObject

+ (MySingleton *) instance;

@end
</pre>
<table width="675">
<tbody>
<tr>
<th>Source file (.m)</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
@interface MySingleton()

// Make any initialization of your class.
- (id) initSingleton;

@end

@implementation MySingleton

- (id) initSingleton
{
	if ((self = [super init]))
	{
		// Initialization code here.
	}

	return self;
}

+ (MySingleton *) instance
{
	// Persistent instance.
	static MySingleton *_default = nil;

	// Small optimization to avoid wasting time after the
	// singleton being initialized.
	if (_default != nil)
	{
		return _default;
	}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
	// Allocates once with Grand Central Dispatch (GCD) routine.
	// It's thread safe.
	static dispatch_once_t safer;
	dispatch_once(&#038;safer, ^(void)
				  {
					  _default = [[MySingleton alloc] initSingleton];
				  });
#else
	// Allocates once using the old approach, it's slower.
	// It's thread safe.
	@synchronized([MySingleton class])
	{
		// The synchronized instruction will make sure,
		// that only one thread will access this point at a time.
		if (_default == nil)
		{
			_default = [[MySingleton alloc] initSingleton];
		}
	}
#endif
	return _default;
}

- (id) retain
{
	return self;
}

- (oneway void) release
{
	// Does nothing here.
}

- (id) autorelease
{
	return self;
}

- (NSUInteger) retainCount
{
    return INT32_MAX;
}

@end
</pre>
<p><br/></p>
<h2><strong>At a glance</strong></h2>
<p>First off, Singleton is a Design Patterns, I know you know some patterns and also use some of them every day in your works. Like MVC (Model View Controller) which all of us use to create our App in Xcode, or also the Delegate Pattern, which Cocoa framework uses largely. So the Singleton is one of those patterns. There are hundreds of patterns, if you want to learn more about Design Patterns I suggest you this book:<br />
<a href="http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612" title="Design Pattern" target="_blank">http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612</a></p>
<p>OK, now about Singleton Pattern. It&#8217;s simple the concept of instantiate (allocate the necessary memory) for a class once and share this instance with all other classes/functions that need it, making at this form, a single point of access.</p>
<p>There are many discussion about the Singleton, many criticisms and many enthusiasm. In my humble opinion, the Singleton Pattern is very useful to control/manage some global data. Like the user account, for example, specially when some data need a special treatment, like user imagem data.</p>
<p>Anyway, my objective here is just to show you how to create a real Singleton class, using the minimum code as possible and make it thread-safe. Remember that in Objective-C multithreading is always something that we must be aware and think about.</p>
<p><br/></p>
<h2><strong>Coding the concept</strong></h2>
<p>In theory the code is very simple, instead of allocate and initialize the class, we just call a class method that returns the singleton instance. We can use this approach through all our application:</p>
<table width="675">
<tbody>
<tr>
<th>Simple singleton</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
// Inside a ClassA, for example.
MySingleton *foo = [MySingleton instance];
[foo setSomeValue:1];

// Inside a ClassB, for example.
MySingleton *foo = [MySingleton instance];
[foo someValue]; // gets the value that was set on ClassA.
</pre>
<p>It&#8217;s important to remember that a singleton class SHOULDN&#8217;T BE RELEASED! Using the Cocoa logic, when you call &#8220;instance&#8221; you are not allocating nor copying any memory, so you shouldn&#8217;t release it.</p>
<p>Well, but the memory must be allocated for someone, right? Yes, the memory will be allocated and controlled by the &#8220;instance&#8221; method. Let&#8217;s talk about the singleton lock.</p>
<p><br/></p>
<h2><strong>Singleton Lock</strong></h2>
<p>We create a kind of lock to make sure our instance will be initialized only once. Like this:</p>
<table width="675">
<tbody>
<tr>
<th>Singleton lock</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
+ (MySingleton *) instance
{
	// Persistent instance.
	static MySingleton *_default = nil;

	if (_default == nil)
	{
		_default = [[MySingleton alloc] init];
	}

	return _default;
}
</pre>
<p>This code will work for 99,9% of the time for ALL kind of languages. However, there is a rare kind of situation which this code will fail. We&#8217;re talking about the multithreading behavior where two threads try to access the singleton instance AND the singleton is not initialized yet.</p>
<div id="attachment_1481" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/12/singleton_lock.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/12/singleton_lock.jpg" alt="In a very rare situation, two threads can try to initialize a singleton at the same time." title="singleton_lock" width="600" height="600" class="size-full wp-image-1481" /></a><p class="wp-caption-text">In a very rare situation, two threads can try to initialize a singleton at the same time.</p></div>
<p>Notice that initializing a class is something very fast, could be done in one or two microseconds, however for a multithreading application, this could be time enough to cause a redundant instantiation. As the singleton, usually, is never deallocated, the double memory allocation will represent a leak.</p>
<p>To solve this problem, all that we need is to make sure our singleton lock be thread-safe, that means, only one thread can make the initialization process. At this point, with Objective-C we have many options, let&#8217;s see the best one.</p>
<p><br/></p>
<h2><strong>Thread Safe</strong></h2>
<p>The best and faster approach is using the GCD (Grand Central Dispatch). However the GCD is not available for all iOS versions, just for iOS 4 or later. So we must think in a solution that fits good for all. The &#8220;@synchronized&#8221; instruction is something that works for all iOS versions, it creates a kind of funnel/queue in which only one thread can run at a time.</p>
<p>The problem with &#8220;@synchronized&#8221; is that it&#8217;s very slow and could make threads run at a synchronized way. So, to avoid unnecessarily wasting time with the @synchronized, let&#8217;s create a way to make the things run faster after the singleton being initialized:</p>
<table width="675">
<tbody>
<tr>
<th>Thread safe</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
+ (MySingleton *) instance
{
	// Persistent instance.
	static MySingleton *_default = nil;

	// Small optimization to avoid wasting time after the
	// singleton being initialized.
	if (_default != nil)
	{
		return _default;
	}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
	// Allocates once with Grand Central Dispatch (GCD) routine.
	// It's thread safe.
	static dispatch_once_t safer;
	dispatch_once(&#038;safer, ^(void)
				  {
					  _default = [[MySingleton alloc] init];
					  // private initialization goes here.
				  });
#else
	// Allocates once using the old approach, it's slower.
	// It's thread safe.
	@synchronized([MySingleton class])
	{
		// The synchronized instruction will make sure,
		// that only one thread will access this point at a time.
		if (_default == nil)
		{
			_default = [[MySingleton alloc] init];
			// private initialization goes here.
		}
	}
#endif
	return _default;
}
@end
</pre>
<p>Notice that the &#8220;if (_default != nil)&#8221; is a single check, that runs very very fast and can avoid our code of spending time with unnecessary checks. About the GCD and blocks, it&#8217;s a simple piece of code that makes the same thing as the code without GCD. The only difference is that the GCD approach uses the special data type &#8220;dispatch_once_t&#8221; (a kind of BOOL) to check if the code have been executed before.</p>
<p>If you want more information about GCD and the blocks, here is it:<br />
<a href="http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" title="Blocks guide" target="_blank">http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html</a><br />
<a href="http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html" title="GCD reference" target="_blank">http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html</a><br />
<a href="http://developer.apple.com/library/ios/#featuredarticles/Short_Practical_Guide_Blocks/_index.html" title="Blocks for beginners" target="_blank">http://developer.apple.com/library/ios/#featuredarticles/Short_Practical_Guide_Blocks/_index.html</a></p>
<p><br/></p>
<h2><strong>Final adjustments</strong></h2>
<p>OK, we&#8217;re almost done. Now, just to make sure that any other class (including classes from Cocoa framework) will not change the retain count of our singleton class, we can override some methods:</p>
<table width="675">
<tbody>
<tr>
<th>Avoiding changes on memory count</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
- (id) retain
{
	return self;
}

- (oneway void) release
{
	// Does nothing here.
}

- (id) autorelease
{
	return self;
}

- (NSUInteger) retainCount
{
    return INT32_MAX;
}
</pre>
<p>The dealloc method is not necessary, because the singleton will never be deallocated. But remember to release and retain the memory for internal variables, by the way this is why @property and @synthesize exist.</p>
<p><br/></p>
<h2><strong>Conclusion</strong></h2>
<p>Very well, my friends, that is all about Singleton Pattern for Obj-C. I hope you liked. Enjoy your singletons and feel free to ask anything you want.</p>
<p>Cya!</p>
<p><iframe scrolling="no" src="http://db-in.com/downloads/apple/tribute_to_jobs.html" width="100%" height="130px"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/12/objective-c-singleton/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tribute to Steve Jobs</title>
		<link>http://db-in.com/blog/2011/10/tribute-to-steve-jobs/</link>
		<comments>http://db-in.com/blog/2011/10/tribute-to-steve-jobs/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 15:39:19 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[Feature]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[jobs]]></category>
		<category><![CDATA[steve]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1464</guid>
		<description><![CDATA[In 25 years Steve Jobs changed the world forever and ever.]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s still hard to me to write about Steve Jobs, if I start to think about the last 5 years of my life I find my self crying with a twirl of sadness and happiness.</p>
<p>I&#8217;m feeling that I must to pay more than a single tribute to Steve Jobs, I want to disseminate this tribute to more than a single post. So this is the deal, I want to talk a little bit about my idea with this tribute and start doing this.</p>
<p><span id="more-1464"></span></p>
<p></p>
<h2><strong>The Image</strong></h2>
<p>This image, created by a student (Jonathan Mak Long) early this week became a symbol, an epic symbol and at the same time a tribute to Steve Jobs.</p>
<div id="attachment_1465" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/10/1pod0042-apple-logo-steve-jobs-silhouette-e1318079135422.jpeg"><img src="http://db-in.com/blog/wp-content/uploads/2011/10/1pod0042-apple-logo-steve-jobs-silhouette-e1318079135422.jpeg" alt="Tribute created by Jonathan Mak Long" title="1pod0042-apple-logo-steve-jobs-silhouette" width="600" height="533" class="size-full wp-image-1465" /></a><p class="wp-caption-text">Tribute created by Jonathan Mak Long</p></div>
<p>This image is so amazing, it have hundreds of implicit significations and many subliminal values. But I don&#8217;t want to start a philosophical discuss about this. Just one thing I want to talk about is the first thing that this image make me remember.</p>
<p>I started to search how this image could be created and I found these two images:<br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/10/apple_jobs_11.jpeg"><img src="http://db-in.com/blog/wp-content/uploads/2011/10/apple_jobs_11.jpeg" alt="" title="apple_jobs_1" width="600" height="300" class="aligncenter size-full wp-image-1470" /></a></p>
<p>They are good as well, but still far from the Long&#8217;s image. So, I found this another one:<br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/10/apple_jobs_3.jpeg"><img src="http://db-in.com/blog/wp-content/uploads/2011/10/apple_jobs_3.jpeg" alt="" title="apple_jobs_3" width="600" height="305" class="aligncenter size-full wp-image-1468" /></a></p>
<p>Good, this image is more closest to what the Long&#8217;s image brings to my mind: Steve Jobs on the stage. It&#8217;s the strongest memory in my mind. Everyone knows how advanced was his rhetoric skills, how many implicit values and messages Jobs could put in one single sentence. His words reflect his way to think and his way changed everything. So, the great visionary that Steve Jobs was were reflected in their presentations and the Long&#8217;s image makes me remember that.</p>
<p>Finally, I found another image, a real photo, this one:<br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/10/apple_jobs_4.jpeg"><img src="http://db-in.com/blog/wp-content/uploads/2011/10/apple_jobs_4.jpeg" alt="" title="apple_jobs_4" width="500" height="450" class="aligncenter size-full wp-image-1469" /></a></p>
<p>So, the Long&#8217;s image is the next step in this chain. I don&#8217;t know if the Jonathan Mak Long had this idea in his mind, of also represent the Jobs&#8217; life on the stage. The point is that it comes to my mind when I saw the Long&#8217;s image. So, the new &#8220;Apple Logo&#8221; from Jonathan Mak is absolutely amazing under all points of view, I want to use it!</p>
<p></p>
<h2><strong>The Text</strong></h2>
<p>I heard this week: &#8220;We lost our john Lennon, we lost our hero&#8221;. This is true. Today all my life is around what the Steve Jobs did. I have macs on my work and at home, my phone is Apple, I play games on iPads, the last gift I gave to my wife was an iPod, we watch movies on an AppleTV, I teach Apple technology, everyday in my life I work/think in iOS APPs.</p>
<p>The changes that Steve Jobs made goes much beyond the technology. The Jobs&#8217; legacy opened some whole new markets, with thousands companies working on it around the globe everyday, by the way, my daily job is on one of those companies. Steve Jobs really made millions of jobs around the world.<br />
<div id="attachment_1475" class="wp-caption alignleft" style="width: 235px"><a href="http://db-in.com/blog/wp-content/uploads/2011/10/advertisement.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/10/advertisement-225x300.jpg" alt="One of my first advertisements. (Click to enlarge)" title="advertisement" width="225" height="300" class="size-medium wp-image-1475" /></a><p class="wp-caption-text">One of my first advertisements. (Click to enlarge)</p></div><br />
I&#8217;m graduated in Publicity &#038; Advertising and I always was in love with Apple computers. Not for coincidence, this image at the left was the first advertisement I made in my life, about 8 years ago. Today, more than ever, nowadays this image is really true! Everything fits into our pockets, thanks to Steve Jobs.</p>
<p>5 years ago I was an ActionScript developer (Flash), but I hated that, because we can&#8217;t create great 3D on Flash (even today with Stage3D/Molehill, Flash developers can&#8217;t do the same as iOS can). With iOS I found myself! I found a place to put everything I know, to make great animations, great graphics, to think psychologically in the content and produce amazing user experiences. And the truth is, without Jobs, I could never find my place in this world.</p>
<p>We felt ourselves comfortable knowing we could focus on what we love, because there was one person on the backstage, that was thinking in &#8220;one more thing&#8221; that will change the day of tomorrow again. But now, this guy is dead&#8230;</p>
<p>But he showed to us the path, now we all know that everyone can change the world if they are &#8220;crazy enough to think they can change the world&#8221;. I want &#8220;to stay hungry, to stay foolish&#8221;. The Jobs death is not the end, it&#8217;s just the beginning of a new era, as he was used to say: a dot that we&#8217;ll connect only in some years when we look back, it&#8217;s impossible to understand the magnitude of this dot right now. The Jobs&#8217; death is a dot in the history of the mankind.</p>
<p></p>
<h2><strong>The Tribute</strong></h2>
<p>So I want to do something, more than a simple tribute to Steve Jobs, I want to change something in my life now that will reflect my gratitude to the Jobs&#8217; legacy. So, here is the symbol of this change, here is the deal:</p>
<p><em>From now and forever in my life, every post, every topic, every article, every single tutorial I make, I&#8217;ll finish with the following signature.</em></p>
<p><iframe scrolling="no" src="http://db-in.com/downloads/apple/tribute_to_jobs.html" width="100%" height="130px"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/10/tribute-to-steve-jobs/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Universal Framework iPhone iOS (2.0)</title>
		<link>http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/</link>
		<comments>http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/#comments</comments>
		<pubDate>Tue, 12 Jul 2011 16:55:58 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[App]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1442</guid>
		<description><![CDATA[Learn how to construct a Custom Framework to iOS Devices and distribute it.]]></description>
			<content:encoded><![CDATA[<p><a href="http://db-in.com/blog/wp-content/uploads/2011/07/framework_ios_2.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/07/framework_ios_2.png" alt="" title="framework_ios_2" width="300" height="300" class="alignright size-full wp-image-1447" /></a>Hello my friends,</p>
<p>Due to some bugs and questions with the old tutorial, I&#8217;m creating this new one, much more simpler and less bugs than the another one. I&#8217;ll not post the old link here because everything you need to know you can find right here.</p>
<p>Nowadays, exist few alternatives to create a Framework to iOS, changing the default Xcode Script, which could not be a good choice if you want to publish the APPs constructed with your custom Framework. I&#8217;ll treat here about how to construct an Universal Framework to iOS, using the default tools from Xcode.</p>
<p>Let&#8217;s start!<br />
<span id="more-1442"></span></p>
<p><a name="list_contents"></a><br />
Here is a little list of contents to orient your reading:</p>
<table width="675">
<tr>
<th colspan=2>List of Contents to this Tutorial</th>
</tr>
<tr>
<td valign="top">
<ul>
<li><a href="#framework_ios">Framework on iOS? Really?</a></li>
<li><a href="#understanding">Understanding Universal, Dynamic and Static concepts</a></li>
<li><a href="#framework_project">Constructing a Framework Project</a>
<ul>
<li><a href="#step_1">1. Create the Project</a></li>
<li><a href="#step_2">2. Framework Classes</a></li>
</ul>
</li>
<li><a href="#creating_framework">Creating the Framework</a>
<ul>
<li><a href="#step_3">3. Create a Framework Target</a></li>
<li><a href="#step_4">4. Bundle Setup</a></li>
<li><a href="#step_5">5. Adding code and resources to the Bundle (Framework)</a></li>
</ul>
</li>
<li><a href="#building_universal">Building the Universal Framework</a>
<ul>
<li><a href="#step_6">6. Creating Universal Target</a></li>
<li><a href="#step_7">7. Lipo Tool Script</a></li>
</ul>
</li>
<li><a href="#importing">Importing your Universal Framework</a>
<ul>
<li><a href="#step_8">8. Importing</a></li>
</ul>
</li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
</td>
</tr>
</table>
<p>You can download the project I used in this article:</p>
<p><a href="http://db-in.com/downloads/framework-ios.zip" onmousedown="_gaq.push(['_trackEvent', 'Framework iOS', 'Xcode', 'Download']);"><img class="alignleft" title="download" src="http://db-in.com/imgs/download_button.png" alt="Download Xcode project files to iPhone"/><br />
<strong>Download now</strong><br />
Xcode project files to Framework-iOS<br />
403kb<br />
</a><br/></p>
<p><br/><a name="faq"></a></p>
<h2><strong>FAQ</strong></h2>
<p><a href="#list_contents">top</a><br />
First off, I want to make sure you understand what this Framework to iOS can do, this can safe your time reading this article:</p>
<ol>
<li><strong>Can I use this Framework as a Bundle to store my files, XIBs, images?</strong><br />
A: Yes, you can and now it&#8217;s very very easy to retrieve your files.</li>
<li><strong>Can I use this Framework to import other Frameworks, like import UIKit, CoreGraphics, OpenGL?</strong><br />
A: No. There is no way to do that. Your code in this custom Framework can import classes from other frameworks normally, but it is just a reference, classes from another framework will not be compiled at this time. So you must import the referenced Framework on the new project as well.</li>
<li><strong>Will be my code visible to others?</strong><br />
A: No. This Framework will export a compiled binary, so anyone can see inside it. You can make the same for some other files, like XIBs.</li>
<li><strong>Why I need this?</strong><br />
A: This is for developers/teams that want to share their codes without shows the entire code (.m/.c/.cpp files). Besides this is for who want to organize compiled code + resources (images, videos, sounds, XIBs, plist, etc) into one single place. And this is also for that teams that want to work together above the same base (framework).</li>
</ol>
<p><br/><a name="framework_ios"></a></p>
<h2><strong>Framework on iOS? Really?</strong></h2>
<p><a href="#list_contents">top</a><br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/04/framework_icon.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/framework_icon.png" alt="" title="framework_icon" width="128" height="128" class="alignleft size-full wp-image-1397" /></a>Ok buddies, let&#8217;s make something clear, many people had said:&#8221;iOS doesn&#8217;t support custom Frameworks!&#8221;, &#8220;Custom Framework is not allowed at iOS!&#8221;, &#8220;Doesn&#8217;t exist custom Framework on iOS!&#8221; and many other discouraging things like these. Look, I&#8217;ve made many frameworks and worked with many others, I don&#8217;t believe that is really impossible to use a Framework on iOS. According to my experience and knowledge about Frameworks, it&#8217;s absolutely feasible a custom Framework on iOS Devices. If we think more about this issue we can find an elegant solution, right? First, let&#8217;s understand what a Framework really is, here is the definition of framework by Apple&#8217;s eyes:</p>
<blockquote><p>A framework is a hierarchical directory that encapsulates shared resources, such as a dynamic shared library, nib files, image files, localized strings, header files, and reference documentation in a single package.</p></blockquote>
<p>Doesn&#8217;t make many sense something with this description not be allowed in iOS, thinking in architecture and structure. Apple also says:</p>
<blockquote><p>A framework is also a bundle and its contents can be accessed using Core Foundation Bundle Services or the Cocoa NSBundle class. However, unlike most bundles, a framework bundle does not appear in the Finder as an opaque file. A framework bundle is a standard directory that the user can navigate.</p></blockquote>
<p>Good, now thinking about iOS security, performance and size, the only thing in a Framework definition which doesn&#8217;t fit in iOS technology is the &#8220;dynamic shared library&#8221;. The words &#8220;dynamic&#8221; and &#8220;shared&#8221; are not welcome in the iOS architecture. So the Apple allows us to work and distribute something called &#8220;<strong>Static Library</strong>&#8220;. I don&#8217;t like it! It&#8217;s not so easy as a Cocoa Framework, if a developer got your Static Library, he needs to set a header path too, or import the header files&#8230; it&#8217;s not useful, that&#8217;s a shit!</p>
<p><a href="http://db-in.com/blog/wp-content/uploads/2011/05/static_library_no.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/static_library_no.png" alt="" title="static_library_no" width="128" height="128" class="alignright size-full wp-image-1403" /></a></p>
<p>Well, so a Framework concept is absolutely compatible with iOS, except by the &#8220;dynamic shared library&#8221;, on the other hand Apple says that a &#8220;static library&#8221; is OK for iOS. So if we replace the &#8220;dynamic shared libraries&#8221; by a &#8220;static library&#8221; we could construct a Custom Framework to iOS, right?</p>
<p>Right!!!!</p>
<p>This is exactly what we&#8217;ll make in this article, let&#8217;s construct a Framework with Static Library, by the way, an Universal Framework.</p>
<p><br/><a name="understanding"></a></p>
<h2><strong>Understanding Universal, Dynamic and Static concepts</strong></h2>
<p><a href="#list_contents">top</a><br />
Simple answer:</p>
<ul>
<li>Universal: Which works perfect on all architectures. iOS devices uses <strong>armv6</strong> and <strong>armv7</strong>, iOS simulator on MacOS X uses <strong>i386</strong>.</li>
<li>Dynamic: The compiler doesn&#8217;t include the target files directly. The classes/libraries are already pre-compiled (binary format) and lies on the system path. Besides, the dynamic libraries can be shared by many applications. This is exactly what Cocoa Framework is.</li>
<li>Static: It represents that classes/libraries which is compiled by the compiler at the build phase. These files can&#8217;t be shared by other applications and relies on application path.</li>
</ul>
<p>Simple as that. If you need more informations about Dynamic VS Static libraries, try this <a href="http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/OverviewOfDynamicLibraries.html" target="_blank">Apple&#8217;s Documentation</a>.</p>
<p>No more concepts, hands at work!</p>
<p><br/><a name="framework_project"></a></p>
<h2><strong>Constructing a Framework Project</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_1"></a><br />
<h3>1. Create the Project:</h3>
<p><a href="#list_contents">top</a><br />
I want to show you step by step of the entire process, so let&#8217;s start with the most basic, create an iOS project. You can choose one application template in Xcode, this is not really important, but remember to choose one template which could test your Framework code before export it.<br />
<div id="attachment_1399" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_project.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_project.jpg" alt="Create an application project." title="xcode_new_project" width="600" class="size-full wp-image-1399" /></a><p class="wp-caption-text">Create an application project.</p></div></p>
<p><br/><a name="step_2"></a></p>
<h3>2. Framework Classes:</h3>
<p><a href="#list_contents">top</a><br />
<div id="attachment_1400" class="wp-caption alignleft" style="width: 267px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_project_navigator.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_project_navigator.jpg" alt="Create your framework classes." title="xcode_project_navigator" width="257" height="286" class="size-full wp-image-1400" /></a><p class="wp-caption-text">Create your framework classes.</p></div></p>
<p>Remember to create an &#8220;import header&#8221; to make everything simpler and organized to the user of your framework. Remember to write this header file with a framework notation, just as shown in the image bellow. Also remember to create your classes taking care to hide the classes which should not be visible to the other developers (users of your framework). We will set the public and private headers soon, but it&#8217;s very important to you protect the &#8220;core&#8221; classes, I mean, that classes which you don&#8217;t want to make visible to other developers.</p>
<p>For those private classes, you could import their header inside the &#8220;<strong>.m</strong>&#8221; (or .mm, .cpp, etc) file of a public class, by doing this you protect the header of private classes. Well, I know you probably already know that, I&#8217;m saying just to reinforce.</p>
<p>Remember that organization is 90% of a good framework, so try follow all the Apple advices to create your classes names, methods, properties, functions, etc.</p>
<p><br/><a name="creating_framework"></a></p>
<h2><strong>Creating the Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_3"></a><br />
<h3>3. Create a Framework Target:</h3>
<p><a href="#list_contents">top</a><br />
OK, let&#8217;s create a target to compile our framework. Click on the icon of your project in the project navigator at the left and hit the button &#8220;Add Target&#8221;. A new window will come up. Now is our first trick. Instead to create a &#8220;Cocoa Touch Static Library&#8221; or a &#8220;Cocoa Framework&#8221; we will create a &#8220;Bundle&#8221; target.</p>
<p>A Bundle? Really? Yes! I can explain. A &#8220;Cocoa Framework&#8221; target can&#8217;t be compiled to armv6/armv7 and Xcode doesn&#8217;t allow us to use &#8220;Static Libraries&#8221; in a &#8220;Cocoa Framework&#8221;, so we can&#8217;t use this target. On the other hand, we can&#8217;t use &#8220;Cocoa Touch Static Library&#8221; either, because it doesn&#8217;t use the framework structure that we want.</p>
<p>Now, the <strong>Bundle</strong> target could be the best choice. It can hold any file we want, we can compile source code inside it and&#8230; we can turn it into a framework. To say the truth, almost all &#8220;Framework &#038; Library&#8221; targets could be turned into a framework too, even the &#8220;Cocoa Touch Static Library&#8221;, throughout this article you probably will figure out how. For now, let&#8217;s create a <strong>Bundle</strong> target.</p>
<div id="attachment_1402" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_target.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_target.jpg" alt="Create a Bundle target rather than Cocoa Touch Static Library." title="xcode_new_target" width="600" class="size-full wp-image-1402" /></a><p class="wp-caption-text">Create a Bundle target rather than Cocoa Touch Static Library.</p></div>
<p><br/><a name="step_4"></a></p>
<h3>4. Bundle Setup:</h3>
<p><a href="#list_contents">top</a><br />
It&#8217;s time to make all the necessary changes to the Bundle target. Different than the old tutorial. You don&#8217;t need to clean up anything. Just know that everything else will be ignored (linked frameworks .plist files, .pch etc&#8230;).</p>
<p>I&#8217;m sure you already know this, but just to reinforce, here is the Build Setting screen, you can find it by clicking on the project icon in the left project navigator and then clicking in the &#8220;Build Setting&#8221; tab.<br />
<div id="attachment_1405" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_settings-e1304231010699.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_settings-e1304231010699.jpg" alt="You must make a special Build Setting to turn a Bundle into a framework." title="xcode_build_settings" width="600" class="size-full wp-image-1405" /></a><p class="wp-caption-text">You must make a special Build Setting to turn a Bundle into a framework.</p></div></p>
<p>Here is our second great trick, or should be better to say &#8220;tricks&#8221;. Let&#8217;s change the &#8220;<strong>Build Setting</strong>&#8221; following this list:</p>
<ul>
<li><strong><em>Base SDK</em></strong>: <span style="color: #3366ff;"><strong>Latest iOS (iOS X.X)</strong></span> (in the X.X will appear the number of the lastest iOS SDK installed on your machine).</li>
<li><strong><em>Architectures</em></strong>: <span style="color: #3366ff;"><strong>$(ARCHS_STANDARD_32_BIT) armv6</strong></span> (it’s very important to be exactly this value including the space before &#8220;armv6&#8243;) This setting is valid to Xcode 4.2, if you are using an old version, use the &#8220;Standard (armv6 armv7)&#8221; option. (the values for this property depend on the value of the item bellow, so set that first).</li>
<li><strong><em>Build Active Architecture Only</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span> (otherwise we can&#8217;t compile to armv6 and armv7 at the same time).</li>
<li><strong><em>Valid Architecture</em></strong>: <span style="color: #3366ff;"><strong>$(ARCHS_STANDARD_32_BIT)</strong></span> (it&#8217;s very important to be exactly this value). If your Xcode is showing two lines with armv6 and armv7, delete then and insert this value in one single line.</li>
<li><strong><em>Dead Code Stripping</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Link With Standard Libraries</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Mach-O Type</em></strong>: <span style="color: #3366ff;"><strong>Relocatable Object File</strong></span>. This is the most important change. Here, we instruct the compiler to treat the Bundle as a relocatable file, by doing this, we can turn it into a framework with the wrapper setting.</li>
<li><strong><em>Other Linker Flags</em></strong>: This setting is not mandatory, but if you are planning to use any kind of C++ code (.cpp or .mm) on this framework, Chris Moore (on the comments) advises to use the &#8220;-lstdc++&#8221; option. In this case could be a good idea to use &#8220;-ObjC&#8221; too, to avoid conflicts in old compilers.</li>
<li><strong><em>Wrapper Extension</em></strong>: <span style="color: #3366ff;"><strong>framework</strong></span>. Here we change the Bundle to a Framework. To Xcode, frameworks is just a folder with the extension <em>.framework</em>, which has inside one or more compiled binary sources, resources and some folders, a folder, usually called Headers, contains all the public headers.</li>
<li><strong><em>Generate Debug Symbols</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span> (this is a very important setting, otherwise the framework will not work on other computers/profiles).</li>
<li><strong><em>Precompile Prefix Header</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Prefix Header</em></strong>: <span style="color: #3366ff;"><strong>&#8220;&#8221;</strong></span>. (Leave it blank).</li>
</ul>
<p><span style="color: #ff0000;"><strong>IMPORTANT:</strong> Since the Xcode 4.x the architectures armv6 has no longer support. So, to create a real Universal Framework we must make a small &#8220;hack&#8221;:</span></p>
<ol>
<li>After change the settings above close the Xcode, find the .xcodeproj (the project file) in Finder and then &#8220;Show Package Contents&#8221;.</li>
<li>Open the file &#8220;project.pbxproj&#8221; into a text editor.</li>
<li>Delete all the lines with VALID_ARCHS = “$(ARCHS_STANDARD_32_BIT)”.</li>
</ol>
<p><br/><a name="step_5"></a></p>
<h3>5. Adding code and resources to the Bundle (Framework)</h3>
<p><a href="#list_contents">top</a><br />
It&#8217;s time to place the content in our framework and define the public headers. To do that, with the Bundle target selected, click on the &#8220;<strong>Build Phase</strong>&#8221; tab. At bottom, hit the button &#8220;<strong>Add Phase</strong>&#8221; and then &#8220;<strong>Add Copy Headers</strong>&#8220;.</p>
<p>Open the recently created &#8220;<strong>Copy Headers</strong>&#8221; section and separate your public headers from the private or project headers. The difference here is:</p>
<ul>
<li>Public: Headers that other developers must know in order to work with your framework. In the final framework product, these headers will be visible even to Xcode.</li>
<li>Private: Headers that is not necessary to other developers, but is good for consult or for reference. These headers will not be visible to Xcode, but will be in the framework folder.</li>
<li>Project: Headers that the other developers nor Xcode have access. In reality these headers will not be placed in the final product, this is just to instruct the compiler to create your custom framework.</li>
</ul>
<p>Now, open the &#8220;<strong>Compile Source</strong>&#8221; section and put there all your <strong>.m</strong>, <strong>.c</strong>, <strong>.mm</strong>, <strong>.cpp</strong> or any other compilable source file.</p>
<p>If your framework include not compilable files, like images, sounds and other resources, you can place them in the &#8220;<strong>Copy Bundle Resources</strong>&#8221; section. Later, when we generate the final framework, all your resources will be placed in a folder called &#8220;Resources&#8221;, but you can change it. That folder is very important, because it will be part of the path to retrieve your resources from the framework product.</p>
<p><span style="color: #3366ff;"><strong>Tip:</strong> To add many files at once, click on the “+” button and write the files’ extension on the search field. For example “.m”, “.c”, “.cpp”, “.h”, etc. This can save a lot of time.</span></p>
<p>This is how your &#8220;<strong>Build Phase</strong>&#8221; will looks like:<br />
<div id="attachment_1406" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_copy_headers.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_copy_headers.jpg" alt="Define your compilable source and the headers." title="xcode_copy_headers" width="600" class="size-full wp-image-1406" /></a><p class="wp-caption-text">Define your compilable source and the headers.</p></div></p>
<p><br/><a name="building_universal"></a></p>
<h2><strong>Building the Universal Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_6"></a><br />
<h3>6. Creating Universal Target:</h3>
<p><a href="#list_contents">top</a><br />
To join both architectures products into one, we must to use the <strong>Lipo Tool</strong>. It&#8217;s a tool which comes with iOS SDK, just to know, it is in &#8220;<Xcode Folder>/Platforms/iPhoneOS.platform/Developer/usr/bin&#8221;, its file name is &#8220;lipo&#8221;. But we don&#8217;t need to know this path, Xcode can deal with it to us.</p>
<p>Add a new target, hit the &#8220;<strong>Add Target</strong>&#8221; button, just as you did with Bundle Target. At this time a good choice is the &#8220;Aggregate&#8221; target. It doesn&#8217;t create any product directly, its purposes is just to aggregate another targets and/or run some scripts, exactly what we want! To use the Lipo Tool we&#8217;ll need to create a &#8220;<strong>Run Script</strong>&#8221; at the &#8220;<strong>Build Phase</strong>&#8220;.</p>
<div id="attachment_1409" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_all.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_all.jpg" alt="Use the &quot;Aggregate&quot; target to construct a run script." title="xcode_build_all" width="600" class="size-full wp-image-1409" /></a><p class="wp-caption-text">Use the &quot;Aggregate&quot; target to construct a run script.</p></div>
<p><br/><a name="step_7"></a></p>
<h3>7. Lipo Tool Script:</h3>
<p><a href="#list_contents">top</a><br />
This will be our greatest trick. The following script will make everything we need. It will compile the Framework Target to iOS Device and Simulator at once, will merge them with Lipo tool and will organize a good Framework Bundle structure.</p>
<p>Copy and paste this on your &#8220;Run Script&#8221; phase:</p>
<table width="675">
<tbody>
<tr>
<th>Xcode Script to Lipo Tool</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
# Sets the target folders and the final framework product.
FMK_NAME=FI
FMK_VERSION=A

# Install dir will be the final output to the framework.
# The following line create it in the root folder of the current project.
INSTALL_DIR=${SRCROOT}/Products/${FMK_NAME}.framework

# Working dir will be deleted after the framework creation.
WRK_DIR=build
DEVICE_DIR=${WRK_DIR}/Release-iphoneos/${FMK_NAME}.framework
SIMULATOR_DIR=${WRK_DIR}/Release-iphonesimulator/${FMK_NAME}.framework

# Building both architectures.
xcodebuild -configuration "Release" -target "${FMK_NAME}" -sdk iphoneos
xcodebuild -configuration "Release" -target "${FMK_NAME}" -sdk iphonesimulator

# Cleaning the oldest.
if [ -d "${INSTALL_DIR}" ]
then
rm -rf "${INSTALL_DIR}"
fi

# Creates and renews the final product folder.
mkdir -p "${INSTALL_DIR}"
mkdir -p "${INSTALL_DIR}/Versions"
mkdir -p "${INSTALL_DIR}/Versions/${FMK_VERSION}"
mkdir -p "${INSTALL_DIR}/Versions/${FMK_VERSION}/Resources"
mkdir -p "${INSTALL_DIR}/Versions/${FMK_VERSION}/Headers"

# Creates the internal links.
# It MUST uses relative path, otherwise will not work when the folder is copied/moved.
ln -s "${FMK_VERSION}" "${INSTALL_DIR}/Versions/Current"
ln -s "Versions/Current/Headers" "${INSTALL_DIR}/Headers"
ln -s "Versions/Current/Resources" "${INSTALL_DIR}/Resources"
ln -s "Versions/Current/${FMK_NAME}" "${INSTALL_DIR}/${FMK_NAME}"

# Copies the headers and resources files to the final product folder.
cp -R "${DEVICE_DIR}/Headers/" "${INSTALL_DIR}/Versions/${FMK_VERSION}/Headers/"
cp -R "${DEVICE_DIR}/" "${INSTALL_DIR}/Versions/${FMK_VERSION}/Resources/"

# Removes the binary and header from the resources folder.
rm -r "${INSTALL_DIR}/Versions/${FMK_VERSION}/Resources/Headers" "${INSTALL_DIR}/Versions/${FMK_VERSION}/Resources/${FMK_NAME}"

# Uses the Lipo Tool to merge both binary files (i386 + armv6/armv7) into one Universal final product.
lipo -create "${DEVICE_DIR}/${FMK_NAME}" "${SIMULATOR_DIR}/${FMK_NAME}" -output "${INSTALL_DIR}/Versions/${FMK_VERSION}/${FMK_NAME}"

rm -r "${WRK_DIR}"
</pre>
<p>Now build the Aggregate target. Doesn&#8217;t matter you build for iOS Device or Simulator, this script will create a working folder, compile the framework target twice in there (device + simulator) and will output a folder called &#8220;<strong>Products</strong>&#8221; located in the project root folder. There is your <strong>Universal Framework to iOS</strong>!</p>
<p><strong>Congratulations!</strong></p>
<p><br/><a name="importing"></a></p>
<h2><strong>Importing your Universal Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_8"></a><br />
<h3>8. Importing:</h3>
<p><a href="#list_contents">top</a><br />
To test your Universal Framework, create a new Xcode project, select the Application target and go to &#8220;<strong>Build Phase</strong>&#8221; tab. Open the section &#8220;<strong>Link Binary With Libraries</strong>&#8221; and hit the &#8220;<strong>+</strong>&#8221; to add a new Framework. Click the &#8220;<strong>Add Other&#8230;</strong>&#8221; button and select your Universal Framework. Remember, you must to select the &#8220;<strong>.framework</strong>&#8221; folder. Remember to import your Framework Principal Header as a framework notation. Xcode will use your public headers in the Code Completion.</p>
<p>Let&#8217;s understand what happens until here:<br />
When we set the &#8220;Mach-O Type&#8221; to &#8220;Relocatable Object File&#8221; the Xcode understand that everything related to that package will be like a &#8220;Binary Archive&#8221; like a ZIP. But that archive must be compiled again in new projects.<br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/07/xcode_bundle_import.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/07/xcode_bundle_import.jpg" alt="" title="xcode_bundle_import" width="298" height="262" class="alignleft size-full wp-image-1445" /></a><br />
Then, when we create a Framework Bundle structure, Xcode understand that everything inside it is organized in folders like &#8220;Headers&#8221; and <CompiledCode>. But, as any other external bundle, to retrieve the resources you must load the external bundle. To iOS this could be an annoying step, however our Framework structure can help. Just Click and Drag on your Framework icon from &#8220;<strong>Project Navigator</strong>&#8221; to the &#8220;<strong>Copy Bundle Resources</strong>&#8220;. By doing this all the resources in your Framework will be copied to your Application Main Bundle.</p>
<p>Now, to retrieve the resources, make use of the main bundle, just as you are used to:</p>
<table width="675">
<tbody>
<tr>
<th>Framework Bundle</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
[[NSBundle mainBundle] pathForResource:@"FI.framework/Resources/FileName"
                                ofType:@"fileExtension"];
</pre>
<p><br/><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p><a href="#list_contents">top</a><br />
Well done, my friends! As we are used, let&#8217;s make a final review and take care with some possible problems.</p>
<ul>
<li>In a common Xcode project, create a Bundle target.</li>
<li>Make the necessary setup, place your sources, headers and resources in it.</li>
<li>Create an Aggreate target and place a <strong>Run Script</strong> in it.</li>
</ul>
<p>One last advice: Take care with your classes structure. If you set, for example, the ClassB.h as a Project or Private header, but in your code you import it into a Public header, this will cause conflicts.</p>
<p>And one last tip: Notice in the sample project I removed the scheme for the &#8220;Bundle Target&#8221;. We don&#8217;t need that scheme any more, because the new script will manage the compilation to us.</p>
<p>That&#8217;s all, buddies.<br />
Enjoy your Framework to iOS!</p>
<p>Thanks for reading,<br />
See you soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/feed/</wfw:commentRss>
		<slash:comments>124</slash:comments>
		</item>
		<item>
		<title>NinevehGL is HERE!</title>
		<link>http://db-in.com/blog/2011/06/ninevehgl-is-here/</link>
		<comments>http://db-in.com/blog/2011/06/ninevehgl-is-here/#comments</comments>
		<pubDate>Wed, 22 Jun 2011 17:59:36 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[Engine]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod]]></category>
		<category><![CDATA[NinevehGL]]></category>
		<category><![CDATA[OpenGL ES]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1436</guid>
		<description><![CDATA[The NinevehGL, the brand new 3D engine to iOS is now on Open Beta phase. Become a Beta Tester and make the download right now!]]></description>
			<content:encoded><![CDATA[<p>Hello my friends,</p>
<p>After long months, just waiting for a single day, was a long wait, I know, but today the things will change a little bit. Today is THAT day.</p>
<p>After working through the nights, polishing every piece of code, thinking and rethinking routines&#8230; finally IT is here!</p>
<p>I&#8217;m very very happy to announce that NinevehGL is HERE!<br />
<span id="more-1436"></span><br />
<br/></p>
<h2><strong>Ladies and Gentlemen</strong></h2>
<p>With a great pleasure, let me introduce you the <a href="http://nineveh.gl">NinevehGL</a>!<br />
<br/><br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/06/ngl_divulgation-e1308762967637.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/06/ngl_divulgation-e1308762967637.jpg" alt="" title="ngl_divulgation" width="670" height="501" class="aligncenter size-full wp-image-1438" /></a></p>
<p><br/></p>
<h2><strong>Keep it Simple</strong></h2>
<p>You know me, I&#8217;m so bored with many web sites, softwares, 3D engines and technologies that make our life a hell with their docs (or the absence of docs), poor tutorials, complex setups, complex API or even worst&#8230; they are paid! God Dammit!!!</p>
<ul>
<li>So, let&#8217;s try something different, something simple! Starting with the web site: <a href="http://nineveh.gl">nineveh.gl</a>, just it, simple and easy.</li>
<li>What about tutorials or docs? Very simple: <a href="http://nineveh.gl/docs/tutorials/">http://nineveh.gl/docs/tutorials/</a>, video tutorials!</li>
<li>Long time to learn? Maybe… what do you think about just 30 min? 10 videos, 3 min each one. Sounds good?</li>
</ul>
<p><br/></p>
<h2><strong>Awesome features</strong></h2>
<p>There are many cool features in NinevehGL. But I think 3 are the &#8220;Killer Features&#8221;:</p>
<ul>
<li>OpenGL ES 2.0 (Programmable Pipeline): It uses the newest OpenGL ES version. More power, faster, lighter, better and shaders! With NinevehGL you can use all the power of the shaders and programmable pipeline.</li>
<li>Import directly from 3D softwares! NinevehGL doesn&#8217;t need plugins or special 3D formats to import your files! Make use of Wavefront OBJ files or COLLADA files (all 3D softwares export one of them). NinevehGL is ready to import them.</li>
<li>Made with pure Objective-C (Obj-C)! Yes, as an iOS developer, when I use OpenGL I expect to see Obj-C code, not C++ or C. NinevehGL is purely made with the native iOS language. Classes and routines follow all the Apple/Cocoa Touch guidelines.</li>
</ul>
<p>Well, another great thing about NinevehGL is that it&#8217;s FREE! A 3D engine for iOS totally FREE!</p>
<p>This is a short post just to tell you about this great news. I hope you like it.</p>
<p>See you, guys!</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/06/ninevehgl-is-here/feed/</wfw:commentRss>
		<slash:comments>56</slash:comments>
		</item>
		<item>
		<title>Binary World</title>
		<link>http://db-in.com/blog/2011/05/binary-world/</link>
		<comments>http://db-in.com/blog/2011/05/binary-world/#comments</comments>
		<pubDate>Thu, 19 May 2011 07:06:43 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[Feature]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[binary]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1420</guid>
		<description><![CDATA[A full tutorial about binary and its application, bitwise operators and more.]]></description>
			<content:encoded><![CDATA[<p>Hello everyone!</p>
<p>In this article, I&#8217;ll talk about the binaries. I&#8217;ll cover the most important concepts and operations, let&#8217;s see some examples of where and how to use binaries and also how you can use it in your daily work. If you are looking for a tutorial about binaries or a &#8220;binary tutorial&#8221;, you are in the right place.</p>
<p>Let&#8217;s delve into the binary world.<br />
<span id="more-1420"></span></p>
<p><a name="list_contents"></a><br />
Here is a little list of contents to orient your reading:</p>
<table width="675">
<tr>
<th colspan=2>List of Contents to this Tutorial</th>
</tr>
<tr>
<td valign="top">
<ul>
<li><a href="#bit_bytes">Bit and Byte</a>
<ul>
<li><a href="#try_binary">Try it Yourself</a></li>
</ul>
</li>
<li><a href="#combining_bytes">Combining Bytes</a></li>
<li><a href="#bitwise">Bitwise Operators</a></li>
<li><a href="#bit_shit">Bit Shifts Operators</a></li>
<li><a href="#applications">Real Applications to the Binaries</a>
<ul>
<li><a href="#even_odd">Even/Odd Routine</a></li>
<li><a href="#colors">Working With Colors</a></li>
<li><a href="#files">Files are Bits</a></li>
</ul>
</li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
</td>
</tr>
</table>
<p><br/></p>
<h2><strong>At a Glance</strong></h2>
<p>The binaries are the most basic and fastest approach in any programming language. Why? Our computers, and I mean, any kind of processing machine, is composed by a board with electric circuits on it, a lot of them. Through these circuits, electrical impulses passes every time, by one single circuit can pass thousands impulses per second. </p>
<div id="attachment_1427" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/electrical_impulse_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/electrical_impulse_example.jpg" alt="Representation of electrical impulses on a computer board." title="electrical_impulse_example" width="600" height="450" class="size-full wp-image-1427" /></a><p class="wp-caption-text">Representation of electrical impulses on a computer board.</p></div>
<p>The receptors of the impulses are prepared to receive only one kind of information: &#8220;has impulse or not&#8221;, it&#8217;s a single &#8220;YES or NO&#8221;. This kind of information is exactly what a <strong><em>bit</em></strong> is. A <strong><em>bit</em></strong> can has the values 1 or 0 (&#8220;YES or NO&#8221;). Very simple, right?</p>
<p>This is why the binaries are the fastest approach ever. Because it&#8217;s the most singular representation of an electrical impulse, which is the basic communication of the components of our hardwares. Everything what comes next in this article is just a little of organization above this kind of information. We&#8217;ll see how organize the <strong><em>bits</em></strong> to form a <strong><em>byte</em></strong>, data types, files and everything else in our virtual world!</p>
<p>After we understand the binary world, we&#8217;ll apply some mathematics on it and make simple operations using the <strong>BITWISE</strong> operators. Finally we go up to high level programming language and see how the binaries can be used in our daily work to improve our applications.</p>
<p><br/><a name="bit_bytes"></a></p>
<h2><strong>Bit and Byte</strong></h2>
<p><a href="#list_contents">top</a><br />
Some people get confused with these names, so let&#8217;s make everything absolutely clear: &#8220;A Bit IS NOT a Byte!&#8221;. To our high level programming language, a single bit is &#8220;invisible&#8221;, we can&#8217;t set a bit individually, all our work is done on the byte level. To us, the byte is the most basic unit, not a bit. But what the hell is the diference between bit and byte?</p>
<p>Well, one byte is composed by 8 bits, this is a constant, it&#8217;s a rule, this never will change. 1 Byte = 8 Bits.</p>
<p>So, if we think in a sequence of 8 bits, remembering from combinatorial analysis, we can say that a set of 8 bits (with 2 possible values: 0 or 1) results in 256 possibilities (2^8 = 256). To make full use of these 256 possibilites, we can think in that sequence as Power of Two.</p>
<div id="attachment_1425" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/binary_values_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/binary_values_example.jpg" alt="Every sequence of 8 bits forms 1 byte, which has 256 combinations." title="binary_values_example" width="600" height="314" class="size-full wp-image-1425" /></a><p class="wp-caption-text">Every sequence of 8 bits forms 1 byte, which has 256 combinations.</p></div>
<p>Confused? Well, look at the next list, it could help you to understand this concept:</p>
<table width="675">
<tr>
<th>Binary Computation</th>
</tr>
<tr>
<td>
<ul>
<li>1st Bit (Right to Left): 2 ^ 0 = 1</li>
<li>2nd Bit (Right to Left): 2 ^ 1 = 2</li>
<li>3th Bit (Right to Left): 2 ^ 2 = 4</li>
<li>4th Bit (Right to Left): 2 ^ 3 = 8</li>
<li>5th Bit (Right to Left): 2 ^ 4 = 16</li>
<li>6th Bit (Right to Left): 2 ^ 5 = 32</li>
<li>7th Bit (Right to Left): 2 ^ 6 = 64</li>
<li>8th Bit (Right to Left): 2 ^ 7 = 128</li>
</ul>
</td>
</tr>
</table>
<p>To compute the value, you look at every bit and check if it is valid or not (0 or 1), if it&#8217;s valid you sum the value it represents. Then you have the final value to a specific byte. The following image shows an example:</p>
<div id="attachment_1422" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/binary_base_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/binary_base_example.jpg" alt="Each bit represents a single &quot;YES&quot; or &quot;NO&quot;." title="binary_base_example" width="600" height="359" class="size-full wp-image-1422" /></a><p class="wp-caption-text">Each bit represents a single &quot;YES&quot; or &quot;NO&quot;.</p></div>
<p>The calculation in the image above was: 128 + 64 + 32 + 4 + 1 = 229. Very simple, right?</p>
<p><br/><a name="try_binary"></a></p>
<h3>Try it Yourself</h3>
<p><a href="#list_contents">top</a><br />
You could try to discover the following values by yourself:</p>
<p><script type="text/javascript" src="http://db-in.com/libs/js/jsBinary.js"></script></p>
<table width="675">
<tr>
<th>Discover the Values</th>
</tr>
</table>
<p><script type="text/javascript">
jsBinary(675,320);
</script><br />
<br/></p>
<p>If you miss some value, don&#8217;t worry, because in reality we&#8217;ll never need to make this kind of calculation by our selves. As I told you before, what happens with bits inside a byte is invisible to our high level programming languages. We&#8217;ll never (or almost never) need to write &#8220;<code>myVariable = 10101100;</code>&#8220;, instead we&#8217;ll use: &#8220;<code>value = 172;</code>&#8221;</p>
<p>Now let&#8217;s go up one level and understand how a byte can be combined with another one to form more complex structures.</p>
<p><br/><a name="combining_bytes"></a></p>
<h2><strong>Combining Bytes</strong></h2>
<p><a href="#list_contents">top</a><br />
As we&#8217;ve saw a Byte can has 256 different values, 0 &#8211; 255. But we are used to use data types with a large range, like <strong><em>int</em></strong>, wich can be -2,147,483,648 to 2,147,483,647 or even the floating numbers, how it can be?</p>
<p>It&#8217;s simple, by placing more than 1 byte to describe a data. If you are 20 years or old, you probably remember from devices of 8 bits, right? Like the game console Nintendo 8 bits. Well, now you know, that console was capable to process data types only with 1 byte at time. After comes platforms of 16 bits, 32 bits and today we are used to work with 64 bits platforms. What that means?</p>
<p>In case of 16 bits, that means 1 byte can be processed together with another byte (2 x 8 bits), for a 32 bits platforms, that means 4 bytes can be processed together (4 x 8 bits), for a 64 bits platforms that means 8 bytes processed together (8 x 8 bits) and so on. The following picture illustrate 32 bits data types <strong><em>int</em></strong> and <strong><em>float</em></strong>:</p>
<div id="attachment_1423" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/binary_combinations_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/binary_combinations_example.jpg" alt="Modern processors can work with multiple bytes at same time.  This is a representation of 32 bits data types." title="binary_combinations_example" width="600" height="600" class="size-full wp-image-1423" /></a><p class="wp-caption-text">Modern processors can work with multiple bytes at same time.  This is a representation of 32 bits data types.</p></div>
<p>Thinking about it: a simple change of processing, from reading only 1 byte to more than one, can changes everything in our devices. For example, with 8 bits at once we have a range of 256 values for colors, do you remember from computers with that configuration? Yes, it was sucks! Now, with 4 bytes at the same time we can have systems running with 4,294,967,296 different colors. Imagine the performance and processing gain to our hardwares with that simple change: from reading 1 byte to reading many of them.</p>
<p>Just as a divagation, in these days, some people say about new kind of processors: Quantum Processors! The idea is change from electrical impulses on a board to electrons state in an atom. Basically an electron have 3 states in the energy level: Up (positive), Middle (neutral) or Down (negative), so instead only a single &#8220;YES or NO&#8221;, we could identify three states: &#8220;UP, MIDDLE and DOWN&#8221;. This single fact can drive us to a new perspective and a new kind of &#8220;bit&#8221;. Besides, unlike the impulses on a board, the electrons in an atom space don&#8217;t need to follow a physical path, its is just atomic vibration, imagine how fast it can be. Now imagine how many electrons can exist in a single atom, how many &#8220;bytes&#8221; (or something similar) we could process at the same time! Today some super computers are running on great platforms like 128 bits, 256 bits, 512 bits and more, but nothing could be compared to a Quantum Processor! Well, to say the truth, I&#8217;ve read that a team led by Yale University researchers has created the first quantum processor. This still far from the market, but not so far from our world.</p>
<p>Well, this is enough divagation. Back to the earth!</p>
<p>Great, now we know how our high level programming languages deal with binaries and more, we know how the binaries work. So every time you create an <strong><em>int</em></strong> data type, for example, in reality, you are creating a set of 32 bits, or in simple words, 32 slots of 0 or 1: <strong>00000000 00000000 00000000 00000000</strong>.</p>
<p>It&#8217;s time to learn some operation we can make in the bit level.</p>
<p><br/><a name="bitwise"></a></p>
<h2><strong>Bitwise Operators</strong></h2>
<p><a href="#list_contents">top</a><br />
There are just few bitwise operators, actually 4. The actions they make are completely different than traditional mathematical operations.</p>
<table width="675">
<tr>
<th>Bitwise Operators</th>
</tr>
<tr>
<td>
<h5><strong>AND: &#038;</strong></h5>
<p>Represented by <strong><em>&#038;</em></strong> (ampersand), it takes only the filled bits between two bit sequences. For example:</p>
<pre>
   01001101
&#038;  00101011
   --------
   00001001
</pre>
<p>The example above with pseudo-code notation: <strong>77 &#038; 43 = 9</strong>.
</td>
</tr>
<tr>
<td>
<h5><strong>OR: |</strong></h5>
<p><br/><br />
Represented by <strong><em>|</em></strong> (pipe), it takes all the filled bits between two bit sequences. For example:</p>
<pre>
   01001101
|  00101011
   --------
   01101111
</pre>
<p>The example above with pseudo-code notation: <strong>77 | 43 = 111</strong>.
</td>
</tr>
<tr>
<td>
<h5><strong>XOR: ^</strong></h5>
<p><br/><br />
Represented by <strong><em>^</em></strong> (caret), it works exactly as the inverse of AND, it takes only filled bits which doesn&#8217;t repeat between two bit sequences. For example:</p>
<pre>
   01001101
^  00101011
   --------
   01100110
</pre>
<p>The example above with pseudo-code notation: <strong>77 ^ 43 = 102</strong>.
</td>
</tr>
<tr>
<td>
<h5><strong>NOT: ~</strong></h5>
<p><br/><br />
Represented by <strong><em>~</em></strong> (tilde), different from other ones, this operator works on only one bit sequence, it&#8217;s also called &#8220;complement&#8221;. It performs a negation on each bit field. So if a bit is 0, it becomes 1 and vice versa</code>. For example:</p>
<pre>
~  01001101
   --------
   10110010
</pre>
<p>The example above with pseudo-code notation: <strong>~77 = 178</strong>.<br />
It is also called "complement" because for unsigned values, it will work as the formula: <strong>~x = {max} - x</strong>, where <strong>{max}</strong> represents the maximum real value to the bit sequence. In the example above the maximum is 255 (8 bits), so ~77 = 255 - 77.<br />
For signed values, it will work as the formula: <strong>~x = -x - 1</strong>, resulting in the number necessary to push the original value to -1.
</td>
</tr>
</table>
<p>All the bitwise operators with use two sequences, just work for two sequences of the same length. But if one sequences has less bits, it will be filled with 0 at the left until reach the same length of the bigger sequence. For example: <strong>01010100 &#038; 111</strong> is in reality the operation: <strong>01010100 &#038; 00000111</strong>. Remember that 0 bits on the left doesn't change anything, just as the real numbers.</p>
<p>Using these simple operations we can really make incredible routines. The best thing is that binaries are stupidly fast with any language, but we already talked about that. Soon we'll see some real examples of binaries in our day work. Before it, we need to see the Bit Shift operations, they are like a complementation to Bitwise operators.</p>
<p><br/><a name="bit_shit"></a></p>
<h2><strong>Bit Shifts Operators</strong></h2>
<p><a href="#list_contents">top</a><br />
Exist two kind of shifts: left and right. Simple as that. Using this bit shift you'll push the bits in a byte set, that means, if your data type has 1 byte, bits will be shifted inside only 1 byte, if your data type has 4 bytes, bits will be shifted inside these 4 bytes.</p>
<table width="675">
<tr>
<th>Bit Shift Operators</th>
</tr>
<tr>
<td>
<h5><strong>LEFT-SHIFT: &lt;&lt;</strong></h5>
<p>Represented by <strong><em>&lt;&lt;</em></strong>, it pushes all bits to the left. The bit in the very left will be discarded and a new one filled with 0 will be placed in the very right. For example:</p>
<pre>
   01001101 &lt;&lt;
   --------
   10011010
</pre>
<p>The example above with pseudo-code notation: <strong>77 &lt;&lt; = 154</strong>.
</td>
</tr>
<tr>
<td>
<h5><strong>LEFT-SHIFT: &gt;&gt;</strong></h5>
<p>Represented by <strong><em>&gt;&gt;</em></strong>, it pushes all bits to the right. The bit in the very right will be discarded and a new one filled with 0 will be placed in the very left. For example:</p>
<pre>
   01001101 &gt;&gt;
   --------
   00100110
</pre>
<p>The example above with pseudo-code notation: <strong>77 &gt;&gt; = 38</strong>.
</td>
</tr>
</table>
<p>The Bit Shift operator should be always in the right side. You also can specify multiple bits to shift by placing the number to shift at the right of the operator. For example:</p>
<table width="675">
<tbody>
<tr>
<th>Shifting Multiple Bits</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
   01001101 &lt;&lt; 4
   --------
   11010000

   01001101 &gt;&gt; 3
   --------
   00001001
.</pre>
<p>Oh right, my friends, these are all the binary operators. Now with these very simple operations we'll make really great things, including in our daily work.</p>
<p><br/><a name="applications"></a></p>
<h2><strong>Real Applications to the Binaries</strong></h2>
<p><a href="#list_contents">top</a><br />
I want to show you examples that we are used to use in our daily-work, some examples that can boost your application's performance without hard re-coding, just simple changes. So my deal with you is: only real examples. Let's go.</p>
<p><br/><a name="even_odd"></a></p>
<h3>Even/Odd Routine</h3>
<p><a href="#list_contents">top</a><br />
Let's start with a very simple example. Imagine a routine that you need to fill lines in a table, you want to fill those lines in pairs, one colored line and the one with blank. A simple way would be to count the rows and on each odd number row you fill in with color and on each even number row you leave it blank. Then we could create a routine to check the result of a division by 2, but the fastest way is using binaries. A binary routine could be something like this:</p>
<table width="675">
<tbody>
<tr>
<th>Binary Routine to Check Even Odd</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// Assume the numberOfRows variable was set.
for (i = 0; i < numberOfRows; ++i)
{
    if (i&#038;1)
    {
        // The "i" is an odd number.
    }
    else
    {
        // The "i" is an even number.
    }
}
.</pre>
<p>I love this routine. It makes me think about all the implicit rules that are within binary numbers. In the example above, what we are actually doing is:</p>
<p><strong>00000001 &#038;  XXXXXXXX</strong></p>
<p>As only the first bit has a value equals to 1, the only way to create an odd number is by using that bit. So, by using the AND operator, we check if the current "i" number makes use of that bit or not. In affirmative case, the number is odd, otherwise, it will be an even number. Very simple!</p>
<p><br/><a name="colors"></a></p>
<h3>Working With Colors</h3>
<p><a href="#list_contents">top</a><br />
Binary + Colors is one of the most popular topics. Almost all Image Softwares make use of binary routines to transform the images. For example, Photoshop makes all its image effects with binary changes in the pixel level.</p>
<p>The first thing about the binary + colors is to understand what is an hexadecimal number. An hexadecimal value is represented by <strong>0xN</strong> (always need "0x" before the number), where N has 16 different values: <strong>0-9 + A-</strong>F. So the real values to an hexadecimal number is:</p>
<pre>
0x0 = 0
0x1 = 1
0x2 = 2
0x3 = 3
0x4 = 4
0x5 = 5
0x6 = 6
0x7 = 7
0x8 = 8
0x9 = 9
0xA = 10
0xB = 11
0xC = 12
0xD = 13
0xE = 14
0xF = 15
</pre>
<p>Now we can place two hexadecimal numbers side by side, one will work like our "unit place" and the other as our "decimal place". So the first has 16 possible values and the second one has other 16 values, totalizing 256 possible values. Wait, wait, wait... 256? It's a Byte, right? So we can use every combination of two hexadecimal numbers (<strong>0xNN</strong>) to represent a byte!</p>
<div id="attachment_1430" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/hexadecimal_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/hexadecimal_example.jpg" alt="Pair of hexadecimal numbers." title="hexadecimal_example" width="600" height="600" class="size-full wp-image-1430" /></a><p class="wp-caption-text">Pair of hexadecimal numbers.</p></div>
<p>Just to make this step clear, here is some values using double hexadecimal numbers.</p>
<pre>
0x00 = 0      (0 x 16 + 0)
0x10 = 16     (1 x 16 + 0)
0x20 = 32     (2 x 16 + 0)
0x21 = 33     (2 x 16 + 1)
0x22 = 34     (2 x 16 + 2)
0xA0 = 160    (10 x 16 + 0)
0xA9 = 169    (10 x 16 + 9)
0xAA = 170    (10 x 16 + 10)
0xAB = 171    (10 x 16 + 11)
0xF0 = 240    (15 x 16 + 0)
0xFF = 255    (15 x 16 + 15)
</pre>
<p>Well, by using 32 bits platforms, we can use 4 bytes to describe a color, if we think in a RGB spectrum + Alpha we can reserve 1 byte to each color channel (R,G,B,A). At this way, each color channel has 256 possible values, right? We can represent a byte with a double hexadecimal number in the form <strong>0xNN</strong>. So we could represent a full pixel with RGBA informations with an hexadecimal combination like this <strong>0xNNNNNNNN</strong>, or using a "channel representation" <strong>0xRRGGBBAA</strong>.</p>
<p>As a legacy from old times, the alpha processing doesn't has a pattern, so each software made its own implementation, some make <strong>0xRRGGBBAA</strong>, others make <strong>0xAARRGGBB</strong> and others even use <strong>0xRRGGBB + 0xAA</strong>. Until today we don't have an universal format to alpha, so let's focus only in <strong>0xRRGGBB</strong> to our study purposes.</p>
<p>Now, to isolate each color channel is very simple:</p>
<table width="675">
<tbody>
<tr>
<th>Isolating Color Channels</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
unsigned int color = 0x99AA44

unsigned char redChannel = color &gt;&gt; 16;
unsigned char greenChannel = ( color &gt;&gt; 8 ) &#038; 0xFF;
unsigned char blueChannel = color &#038; 0xFF;
.</pre>
<p>It's very simple understand what happened. If we think in a binary representation (bits), the "<em>color</em>" variable above could be something like: <strong><span style="color: #ff0000;">RRRRRRRR</span><span style="color: #339966;">GGGGGGGG</span><span style="color: #0000ff;">BBBBBBBB</span></strong>. Then, when we move <strong>sixteen bits</strong> to the right, the resulting binary is:</p>
<p><strong><span style="color: #ff0000;">RRRRRRRR</span><span style="color: #339966;">GGGGGGGG</span><span style="color: #0000ff;">BBBBBBBB</span></strong> &gt;&gt; 16 = <strong><span style="color: #ff0000;">RRRRRRRR</span></strong></p>
<p>Similar we move <strong>eight bits</strong> to get the green channel, but at this time the green channel is not isolated yet, the red channel remains in the result. Then, to isolate the green channel we use the <strong>AND bitwise with 0xFF</strong>, which is a byte representing the real value 255, by doing so, we discard all the red channel information, remaining only with the green channel:</p>
<p><strong><span style="color: #ff0000;">RRRRRRRR</span><span style="color: #339966;">GGGGGGGG</span><span style="color: #0000ff;">BBBBBBBB</span></strong> &gt;&gt; 8 = <strong><span style="color: #ff0000;">RRRRRRRR</span><span style="color: #339966;">GGGGGGGG</span></strong> &#038; 11111111 =  <strong><span style="color: #339966;">GGGGGGGG</span></strong></p>
<p>And finally we make almost the same to the blue channel:</p>
<p><strong><span style="color: #ff0000;">RRRRRRRR</span><span style="color: #339966;">GGGGGGGG</span><span style="color: #0000ff;">BBBBBBBB</span></strong> &#038; 11111111 =  <strong><span style="color: #0000ff;">BBBBBBBB</span></strong></p>
<p>If you get the pixel data from an image file, it could also has the alpha information pre-multiplied (ARGB). So to correctly extract the color channels you could make the <strong>&#038; 0xFF</strong> step even to the red channel. If the alpha is post-multiplied (RGBA), we must to push 8 bits more:</p>
<table width="675">
<tbody>
<tr>
<th>Isolating Color Channels Avoiding Alpha</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
unsigned int color = "one pixel data"

// To pixel data in format ARGB
unsigned char redChannel = ( color &gt;&gt; 16 ) &#038; 0xFF;
unsigned char greenChannel = ( color &gt;&gt; 8 ) &#038; 0xFF;
unsigned char blueChannel = ( color &gt;&gt; 0 ) &#038; 0xFF;

// To pixel data informat RGBA
unsigned char redChannel = ( color &gt;&gt; 24 ) &#038; 0xFF;
unsigned char greenChannel = ( color &gt;&gt; 16 ) &#038; 0xFF;
unsigned char blueChannel = ( color &gt;&gt; 8 ) &#038; 0xFF;
.</pre>
<p>Once you have access to the color channel of each pixel you can make almost everything with the image color. You can exclude or replace a color channel, transform it into a grey scale image, change the colors individually, well... look at the Photoshop, all that effects was made with this principle. Obviously to produce more complex effects, like a blur or motion blur you need make many passes through every pixel and depending on the image size (width and height), this could be a very expensive task.</p>
<p>I've wrote about how to reduce the color range of an image using the binary approach. It was on my last OpenGL tutorial, you can check it by <a href="http://db-in.com/blog/2011/05/all-about-opengl-es-2-x-part-33/#bpp">clicking here</a>.</p>
<p>All the informations on this topic, binary + color, are about the most popular image formats, which make use of 8 bits per channel. But, there are some image format that support more, like 16 bits/channel or even 32 bits/channel. Those high formats support an incredible range of colors, they are often used to print formats, which uses CMYK instead RGBA color formats. But if you need to work with one of that "high images", the code is almost the same, just changing some numbers of bit shifts. To our virtual world, assume all images will always use 8 bits/channel. The following image shows the supported bits per channel for each of the popular image formats. Files that support 32 bits/channel also support 16 and 8, files that support 16 bits/channel also support 8:</p>
<div id="attachment_1431" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/image_bits_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/image_bits_example.jpg" alt="Supported bits/channel on the most popular image formats." title="image_bits_example" width="600" height="450" class="size-full wp-image-1431" /></a><p class="wp-caption-text">Supported bits/channel on the most popular image formats.</p></div>
<p><br/><a name="files"></a></p>
<h3>Files are Bits</h3>
<p><a href="#list_contents">top</a><br />
Everything was made with binaries. All the files that we use are in a low-level, only bits. So we can parse and extract information from any file. But to do that, you must know the bits organization in that file. This is the principle of file security and encryption. If you make a "coder" and a "decoder" to reorganize the bits inside a file, that file will be now encrypted. More sophisticated techniques also include fake bits or even create a "key" inside the file to recreate the file with a completely new structure. But in depth, everything are bits and can be read.</p>
<p>Usually the popular file formats have their bits organizations largely exposed on documents and specifications. So we can learn to read and write those formats.</p>
<p>Here is a list with the greatest website with file format specifications:</p>
<ul>
<li><a href="http://www.fileformat.info/format/all.htm" target="_blank">http://www.fileformat.info</a></li>
<li><a href="http://www.wotsit.org/list.asp?fc=0" target="_blank">http://www.wotsit.org</a></li>
<li><a href="http://www.martinreddy.net/gfx/2d-hi.html" target="_blank">http://www.martinreddy.net/ - for 2D image files</a></li>
<li><a href="http://www.martinreddy.net/gfx/3d-hi.html" target="_blank">http://www.martinreddy.net/ - for 3D format files</a></li>
</ul>
<p>You also have 2 other choices: search in wikipedia for the file format you are looking for or even go to the page of the company/creator which made the file you are looking for. If you don't know who is the creator, you can go to this page: <a href="http://whatis.techtarget.com/file-extension-list-A/0,289933,sid9,00.html" target="_blank">http://whatis.techtarget.com</a> and search for the file extension, when you click you'll see a link to the official page of that format, if exist.</p>
<p>Talking about the file formats, in general, the great majority of the file creators try to organize the informations in 4 bytes, even those informations that need less than 4. This is a good practice to make the file more organized and more readable. But it's not a rule, some files could fill many informations into 4 byte.</p>
<p>Our high level programming languages often offer a class, or some classes, to work with binary files. So you can easily use any data type and that class will create a binary stream for you, forming a great array of bits. After put all informations on the files, you just save it, or send via internet, anyway. I'll show you a little piece of code using Objective-C (Cocoa):</p>
<table width="675">
<tbody>
<tr>
<th>Creating a Binary File with Objective-C</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// Creates some generic data to save into a file.
// As in C language the strings are made with an array of chars
// we must to know the length of the string to calculate
// the number of bits necessary to write it.
float floatNumber = 15.2;
char *charString = "this is a string";
int strLength = strlen(charString) + 1;

// Initializes the Cocoa class that deals with binaries.
NSMutableData *data = [[NSMutableData alloc] init];

// Inserts the data to save. This order is very important.
[data appendBytes:&#038;floatNumber length:sizeof(float)];
[data appendBytes:&#038;strLength length:sizeof(int)];
[data appendBytes:&#038;charString length:sizeof(char) * stringLength];

// Saves the file.
[data writeToFile:@"/path/to/save/file.test" atomically:YES];

// Frees the memory allocated.
[data release];
.</pre>
<p>Even if you are not familiar to Objective-C, you can understand the steps involved here. Using a standard C libraries, we also can use <strong>fopen</strong> function with the parameter <em><strong>"b"</strong></em> to open or write a file in the binary format.</p>
<p>The most important thing to understand is the order and length of each information in a binary file. In the example above, if we change the order of the calls to "appendBytes:length:" the resulting file will be absolutely different. The following image shows the resulting file from the code above and another file resulting from one little change in the code:</p>
<div id="attachment_1433" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/binary_files_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/binary_files_example.jpg" alt="Every file is a stream of bits." title="binary_files_example" width="600" class="size-full wp-image-1433" /></a><p class="wp-caption-text">Every file is a stream of bits.</p></div>
<p>As you can see, changing the order of one little information drives us into a whole new file. The image above shows the binary file opened in an "Hexadecimal Editor". This kind of application show to us the binary format of any file, separating the data in 4 bytes. You remember how to represent a byte using hexadecimal numbers, right? <strong>0xNNNNNNNN</strong> represents 4 bytes.</p>
<p>To read the binary file, you need follow the inverse path: selecting a set of bits by time and parsing it appropriately. For example, if you know the next 4 bytes represents a float data, parse it in a float data type, if you know the next byte represents a single char, parse it into a char and so on. Here is an important thing, to parse an information with mutable size, like a string, you need to know the length of the data in first place. So every time we need save a data with mutable size, we reserve some bits (usually 32 bits) to hold the length of the data that comes next.</p>
<p>Using the same example above, we could write to open the saved file:</p>
<table width="675">
<tbody>
<tr>
<th>Reading a Binary File with Objective-C</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// Creates the variables to receive the data from binary file.
float floatNumber;
char *charString;
int strLength;

// Creates a location/pointer to guide the position of the bytes inside the binary file.
int lastLocation = 0;

// Initializes the Cocoa class that deals with binaries.
NSData *data = [[NSData alloc] initWithContentsOfFile:@"/path/to/save/file.test"];

// Retrieves the floating number from the file and updates the location/pointer.
[data getBytes:&#038;floatNumber range:NSMakeRange(lastLocation, sizeof(float))];
lastLocation += sizeof(float);

// Retrieves the string length from the file and updates the location/pointer.
[data getBytes:&#038;strLength range:NSMakeRange(lastLocation, sizeof(int))];
lastLocation += sizeof(int);

// Allocates the necessary memory to receive the string and retrieves the data.
charString = malloc(sizeof(char) * strLength);
[data getBytes:&#038;charString range:NSMakeRange(lastLocation, sizeof(char) * strLength)];

// Frees the memory allocated.
[data release];
.</pre>
<p>Working with binary files we can make great thing on our application. We can improve the security, we can create binary files to hold informations or even open the binary files of other softwares. The performance and size is really amazing! Few kilobytes can hold a bunch of informations.</p>
<p><br/><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p><a href="#list_contents">top</a><br />
Well, as you can imagine now, we can use binaries to many things: to improve our application's performance, for security improvements, for read and write files, the binaries are useful for many things. My last advice is: don't be shy, use and abuse of binaries! After I learned about the binaries I waited many months until I really started to explore them. Don't do the same, explore the binary power right now, as in The Matrix (movie), you'll start to see the bits behind the world! <img src='http://db-in.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>So, let's remember from everything:</p>
<ul>
<li>Bits are the most basic representation of the electrical impulses on our computer boards.</li>
<li>A Bit can be 0 or 1.</li>
<li>One Byte has 8 Bits. Totalizing 256 different possibilities.</li>
<li>Bytes can be combined to form powerful platforms: 16 bits, 32 bits, 64 bits and so on.</li>
<li>Bitwise operators <strong>(&#038;, |, ^ and ~</strong>) generate new bits with some changes on the original bit(s).</li>
<li>Bit Shifts operators <strong>(&gt;&gt; and &lt;&lt;)</strong> generate new bits changing the position of the original bit(s).</li>
<li>One pair of hexadecimal values can represent one byte.</li>
<li>Every file on any computer is a binary file and can be read if you know the bit sequence.</li>
</ul>
<p>Very well my friends, this is all about the binaries. As you saw, they are really simple, very simple and in reason of this simplicity the binaries are so powerful. If you have any doubt, just ask.</p>
<p>Thanks for reading,</p>
<p>See you soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/05/binary-world/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Creating Universal Framework to iPhone iOS</title>
		<link>http://db-in.com/blog/2011/05/creating-universal-framework-to-iphone-ios/</link>
		<comments>http://db-in.com/blog/2011/05/creating-universal-framework-to-iphone-ios/#comments</comments>
		<pubDate>Sun, 01 May 2011 19:50:50 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1394</guid>
		<description><![CDATA[Learn how to construct a Custom Framework to iOS Devices and distribute it.]]></description>
			<content:encoded><![CDATA[<p><a href="http://db-in.com/blog/wp-content/uploads/2011/04/framework_ios.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/framework_ios.png" alt="" title="framework_ios" width="200" height="200" class="alignright size-full wp-image-1396" /></a>Hello my friends,</p>
<p>I felt a good impulse to write a little article about this theme, because there are few poor informations about it around the web. In many cases, are wrong or incomplete informations. So if you want to write a framework to iPhone and distribute it, you are in the right place!</p>
<p>I&#8217;ll treat here about how to construct an Universal Framework to iOS, what are the necessary configurations and everything else related to. We&#8217;ll focus on Xcode 4, but this is also valid to Xcode 3.x.</p>
<p>Let&#8217;s start!<br />
<span id="more-1394"></span></p>
<h2><span style="color:#FF0000">&#8211;WARNING&#8211;</span></h2>
<p><strong>This content is outdated! There is a new version of this article (2.0) teaching how to create an Universal Framework to iOS, much simpler and reliable:</strong><br />
<a href="http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/">http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/</a></p>
<p><a name="list_contents"></a><br />
Here is a little list of contents to orient your reading:</p>
<table width="675">
<tr>
<th colspan=2>List of Contents to this Tutorial</th>
</tr>
<tr>
<td valign="top">
<ul>
<li><a href="#framework_ios">Framework on iOS? Really?</a></li>
<li><a href="#understanding">Understanding Universal, Dynamic and Static concepts</a></li>
<li><a href="#framework_project">Constructing a Framework Project</a>
<ul>
<li><a href="#step_1">1. Create the Project</a></li>
<li><a href="#step_2">2. Framework Classes</a></li>
</ul>
</li>
<li><a href="#compiling_framework">Compiling a Framework</a>
<ul>
<li><a href="#step_3">3. Create a Framework Target</a></li>
<li><a href="#step_4">4. Bundle Setup</a></li>
<li><a href="#step_5">5. Adding code and resources to the Bundle (Framework)</a></li>
<li><a href="#step_6">6. Schemes Setup</a></li>
<li><a href="#step_7">7. Building the Framework</a></li>
</ul>
</li>
<li><a href="#building_universal">Building the Universal Framework</a>
<ul>
<li><a href="#step_8">8. Creating Universal Target</a></li>
<li><a href="#step_9">9. Lipo Tool Script</a></li>
</ul>
</li>
<li><a href="#testing">Testing your Universal Framework</a>
<ul>
<li><a href="#step_10">10. Testing</a></li>
</ul>
</li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
</td>
</tr>
</table>
<p>You can download the project I used in this article:</p>
<p><a href="http://db-in.com/downloads/framework-ios.zip" onmousedown="_gaq.push(['_trackEvent', 'Framework iOS', 'Xcode', 'Download']);"><img class="alignleft" title="download" src="http://db-in.com/imgs/download_button.png" alt="Download Xcode project files to iPhone"/><br />
<strong>Download now</strong><br />
Xcode project files to Framework-iOS<br />
403kb<br />
</a><br/></p>
<p><br/><a name="framework_ios"></a></p>
<h2><strong>Framework on iOS? Really?</strong></h2>
<p><a href="#list_contents">top</a><br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/04/framework_icon.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/framework_icon.png" alt="" title="framework_icon" width="128" height="128" class="alignleft size-full wp-image-1397" /></a>Ok buddies, let&#8217;s make something clear, many people had said:&#8221;iOS doesn&#8217;t support custom Frameworks!&#8221;, &#8220;Custom Framework is not allowed at iOS!&#8221;, &#8220;Doesn&#8217;t exist custom Framework on iOS!&#8221; and many other discouraging things like these. Look, I&#8217;ve made many frameworks and worked with many others, I don&#8217;t believe that is really impossible to use a Framework on iOS. According to my experience and knowledge about Frameworks, it&#8217;s absolutely feasible a custom Framework on iOS Devices. If we think more about the issue we can find an elegant solution, right? First, let&#8217;s understand what a Framework really is, here is the definition of framework by Apple&#8217;s eyes:</p>
<blockquote><p>A framework is a hierarchical directory that encapsulates shared resources, such as a dynamic shared library, nib files, image files, localized strings, header files, and reference documentation in a single package.</p></blockquote>
<p>Doesn&#8217;t make many sense something with this description not be allowed in iOS, thinking in architecture and structure. Apple also says:</p>
<blockquote><p>A framework is also a bundle and its contents can be accessed using Core Foundation Bundle Services or the Cocoa NSBundle class. However, unlike most bundles, a framework bundle does not appear in the Finder as an opaque file. A framework bundle is a standard directory that the user can navigate.</p></blockquote>
<p>Good, now thinking about iOS security, performance and size, the only thing in a Framework definition which doesn&#8217;t fit in iOS technology is the &#8220;dynamic shared library&#8221;. The words &#8220;dynamic&#8221; and &#8220;shared&#8221; are not welcome in the iOS architecture. So the Apple allows us to work and distribute something called &#8220;<strong>Static Library</strong>&#8220;. I don&#8217;t like it! It&#8217;s not so easy as a Cocoa Framework, if a developer got your Static Library, he needs to set a header path too, or import the header files&#8230; it&#8217;s not useful, that&#8217;s a shit!</p>
<p><a href="http://db-in.com/blog/wp-content/uploads/2011/05/static_library_no.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/static_library_no.png" alt="" title="static_library_no" width="128" height="128" class="alignright size-full wp-image-1403" /></a></p>
<p>Well, so a Framework concept is absolutely compatible with iOS, except by the &#8220;dynamic shared library&#8221;, on the other hand Apple says that a &#8220;static library&#8221; is OK for iOS. So if we replace the &#8220;dynamic shared libraries&#8221; by a &#8220;static library&#8221; we could construct a Custom Framework to iOS, right?</p>
<p>Right!!!!</p>
<p>This is exactly what we&#8217;ll make in this article, let&#8217;s construct a Framework with Static Library, by the way, an Universal Framework.</p>
<p><br/><a name="understanding"></a></p>
<h2><strong>Understanding Universal, Dynamic and Static concepts</strong></h2>
<p><a href="#list_contents">top</a><br />
Simple answer:</p>
<ul>
<li>Universal: Which works perfect on all architectures. iOS devices uses <strong>armv6</strong> and <strong>armv7</strong>, iOS simulator on MacOS X uses <strong>i386</strong>.</li>
<li>Dynamic: The compiler doesn&#8217;t include the target files directly. The classes/libraries are already pre-compiled (binary format) and lies on the system path. Besides, the dynamic libraries can be shared by many applications. This is exactly what Cocoa Framework is.</li>
<li>Static: It represents that classes/libraries which is compiled by the compiler at the build phase. These files can&#8217;t be shared by other applications and relies on application path.</li>
</ul>
<p>Simple as that. If you need more informations about Dynamic VS Static libraries, try this <a href="http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/OverviewOfDynamicLibraries.html" target="_blank">Apple&#8217;s Documentation</a>.</p>
<p>No more concepts, hands at work!</p>
<p><br/><a name="framework_project"></a></p>
<h2><strong>Constructing a Framework Project</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_1"></a><br />
<h3>1. Create the Project:</h3>
<p><a href="#list_contents">top</a><br />
I want to show you step by step of the entire process, so let&#8217;s start with the most basic, create an iOS project. You can choose one application template in Xcode, this is not really so important, but remember to choose one template which could test your Framework code before export it.<br />
<div id="attachment_1399" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_project.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_project.jpg" alt="Create an application project." title="xcode_new_project" width="600" class="size-full wp-image-1399" /></a><p class="wp-caption-text">Create an application project.</p></div></p>
<p><br/><a name="step_2"></a></p>
<h3>2. Framework Classes:</h3>
<p><a href="#list_contents">top</a><br />
<div id="attachment_1400" class="wp-caption alignleft" style="width: 267px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_project_navigator.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_project_navigator.jpg" alt="Create your framework classes." title="xcode_project_navigator" width="257" height="286" class="size-full wp-image-1400" /></a><p class="wp-caption-text">Create your framework classes.</p></div>Now it&#8217;s time to create (or import) your framework classes, just as you are used to in any other application. Remember that organization is 80% of a good framework, so try follow all the Apple advices to create your classes names, methods, properties, functions, etc.</p>
<p>Remember to create an import header to make everything more simple and organized to the user of your framework. Remember to write this header file with a framework notation, just as shown in the image bellow. Also remember to create your classes taking care to hide the classes which should not be visible to the other developers (users of your framework). We will set the public and private headers soon, but it&#8217;s very important to you protect the &#8220;core&#8221; classes, I mean, that classes which you don&#8217;t want to make visible to other developers.</p>
<p>For those private classes, you could import their header inside the &#8220;<strong>.m</strong>&#8221; (or .mm, .cpp, etc) file of a public class, by doing this you protect the header of private classes. Well, I know you probably already know that, I&#8217;m saying just to reinforce.</p>
<p>After you have all the classes (and also other files, like images, sounds, etc.), you are ready to compile a custom framework. In the next step, we&#8217;ll create a target to compile our framework, this will be our first big trick!</p>
<div id="attachment_1401" class="wp-caption aligncenter" style="width: 457px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_framework_header.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_framework_header.jpg" alt="Create your framework header with framework notation." title="xcode_framework_header" width="447" height="157" class="size-full wp-image-1401" /></a><p class="wp-caption-text">Create your framework header with framework notation.</p></div>
<p><br/><a name="compiling_framework"></a></p>
<h2><strong>Compiling a Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_3"></a><br />
<h3>3. Create a Framework Target:</h3>
<p><a href="#list_contents">top</a><br />
OK, let&#8217;s create a target to compile our framework. Click on the icon of your project in the project navigator at the left and hit the button &#8220;Add Target&#8221;. A new window will come up. Now is our first trick. Instead to create a &#8220;Cocoa Touch Static Library&#8221; or a &#8220;Cocoa Framework&#8221; we will create a &#8220;Bundle&#8221; target.</p>
<p>A Bundle? Really? Yes! I can explain. A &#8220;Cocoa Framework&#8221; target can&#8217;t be compiled to armv6/armv7 and Xcode doesn&#8217;t allow us to use &#8220;Static Libraries&#8221; in a &#8220;Cocoa Framework&#8221;, so we can&#8217;t use this target. On the other hand, we can&#8217;t use &#8220;Cocoa Touch Static Library&#8221; either, because it doesn&#8217;t use the framework structure that we want.</p>
<p>Now, the <strong>Bundle</strong> target could be the best choice. It can hold any file we want, we can compile source code inside it and&#8230; we can turn it into a framework. To say the truth, almost all &#8220;Framework &#038; Library&#8221; targets could be turned into a framework too, even the &#8220;Cocoa Touch Static Library&#8221;, throughout this article you probably will figure out why. For now, let&#8217;s create a <strong>Bundle</strong> target.</p>
<div id="attachment_1402" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_target.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_target.jpg" alt="Create a Bundle target rather than Cocoa Touch Static Library." title="xcode_new_target" width="600" class="size-full wp-image-1402" /></a><p class="wp-caption-text">Create a Bundle target rather than Cocoa Touch Static Library.</p></div>
<p><br/><a name="step_4"></a></p>
<h3>4. Bundle Setup:</h3>
<p><a href="#list_contents">top</a><br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_remove_framework.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_remove_framework.jpg" alt="" title="xcode_remove_framework" width="314" height="113" class="alignleft size-full wp-image-1404" /></a>It&#8217;s time to make all the necessary changes to the Bundle target. First of all, make sure you have cleaned up all the default files from the Bundle target. Remove the linked frameworks (you can find it clicking in the &#8220;<strong>Build Phase</strong>&#8221; tab and then they are in the section &#8220;<strong>Link Binary With Libraries</strong>&#8220;) and delete the Preference List file (.plist), the pre-compiled headers (.pch) and the language files.</p>
<p>I&#8217;m sure you already know this, but just to reinforce, here is the Build Setting screen, you can find it by clicking on the project icon in the left project navigator and then clicking in the &#8220;Build Setting&#8221; tab.<br />
<div id="attachment_1405" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_settings-e1304231010699.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_settings-e1304231010699.jpg" alt="You must make a special Build Setting to turn a Bundle into a framework." title="xcode_build_settings" width="600" class="size-full wp-image-1405" /></a><p class="wp-caption-text">You must make a special Build Setting to turn a Bundle into a framework.</p></div></p>
<p>Here is our second great trick, or should be better to say &#8220;tricks&#8221;. Let&#8217;s change the &#8220;<strong>Build Setting</strong>&#8221; following this list:</p>
<ul>
<li><strong><em>Architectures</em></strong>: <span style="color: #3366ff;"><strong>Standard (armv6 armv7)</strong></span> (the values for this property depend on the value of the item bellow).</li>
<li><strong><em>Base SDK</em></strong>: <span style="color: #3366ff;"><strong>Latest iOS (iOS X.X)</strong></span> (in the X.X will appear the number of the lastest iOS SDK installed on your machine).</li>
<li><strong><em>Build Active Architecture Only</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span> (this is a very important set, if it&#8217;s YES then we can&#8217;t compile to armv6 and armv7 at the same time).</li>
<li><strong><em>Supported Platforms</em></strong>: <span style="color: #3366ff;"><strong>iphonesimulator iphoneos</strong></span>.
<li><strong><em>Valid Architecture</em></strong>: <span style="color: #3366ff;"><strong>$(ARCHS_STANDARD_32_BIT)</strong></span> (it&#8217;s very important to be exactly this value, seems there is a bug in Xcode 4, once you set i386 as supported platforms to iOS, it can&#8217;t be removed anymore and it could generate errors in your project. So, to avoid any architectures error, use this value).</li>
<li><strong><em>Installation Directory</em></strong>: [optional change] I like to set this to <span style="color: #3366ff;"><strong>$(BUILT_PRODUCTS_DIR)</strong></span>, but this is not really relevant to our purposes here. You can set it to a path of your choice.</li>
<li><strong><em>Mac OS X Deployment Target</em></strong>: <span style="color: #3366ff;"><strong>Compiler Default</strong></span>.</li>
<li><strong><em>Dead Code Stripping</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Link With Standard Libraries</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Mach-O Type</em></strong>: <span style="color: #3366ff;"><strong>Relocatable Object File</strong></span>. This is the most important change. Here, we instruct the compiler to treat the Bundle as a relocatable file, by doing this, we can turn it into a framework with the wrapper setting.</li>
<li><strong><em>Other Linker Flags</em></strong>: [optional change] <span style="color: #3366ff;"><strong>-ObjC</strong></span>, could be good make sure the compiler understands what&#8217;s the language it is compiling for, this can reduce the warnings at the compilation.</li>
<li><strong><em>Info.plist File</em></strong>: <span style="color: #3366ff;"><em>empty</em></span>, remove any value from this field.</li>
<li><strong><em>Wrapper Extension</em></strong>: <span style="color: #3366ff;"><strong>framework</strong></span>. Here we change the Bundle to a Framework. To Xcode, frameworks is just a folder with the extension <em>.framework</em>, which has inside one or more compiled binary sources, resources and some folders, a folder, usually called Headers, contains all the public headers.</li>
<li><strong><em>Precompile Prefix Header</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Prefix Header</em></strong>: <span style="color: #3366ff;"><em>empty</em></span>, remove any value from this field.</li>
<li><strong><em>Generate Debug Symbols</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span> (this is a very important setting, otherwise your framework will not work on another computer/profile).</li>
</ul>
<p><br/><a name="step_5"></a></p>
<h3>5. Adding code and resources to the Bundle (Framework)</h3>
<p><a href="#list_contents">top</a><br />
It&#8217;s time to place the content in our framework and define the public headers. To do that, with the Bundle target selected, click on the &#8220;<strong>Build Phase</strong>&#8221; tab. At bottom, hit the button &#8220;<strong>Add Phase</strong>&#8221; and then &#8220;<strong>Add Copy Headers</strong>&#8220;.</p>
<p>Open the recently created &#8220;<strong>Copy Headers</strong>&#8221; section and separate your public headers from the private or project headers. The difference here is:</p>
<ul>
<li>Public: Headers that other developers must know in order to work with your framework. In the final framework product, these headers will be visible even to Xcode.</li>
<li>Private: Headers that is not necessary to other developers, but is good for consult or for reference. These headers will not be visible to Xcode, but will be in the framework folder.</li>
<li>Project: Headers that the other developers nor Xcode have access. In reality these headers will not be placed in the final product, this is just to instruct the compiler to create your custom framework.</li>
</ul>
<p>Now, open the &#8220;<strong>Compile Source</strong>&#8221; section and put there all your <strong>.m</strong>, <strong>.c</strong>, <strong>.mm</strong>, <strong>.cpp</strong> or any other compilable source file. If your framework include not compilable files, like images, sounds and other resources, you can place them in the &#8220;<strong>Copy Bundle Resources</strong>&#8221; section, in the example of this article, I used no resources. This is how your &#8220;<strong>Build Phase</strong>&#8221; will looks like:<br />
<div id="attachment_1406" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_copy_headers.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_copy_headers.jpg" alt="Define your compilable source and the headers." title="xcode_copy_headers" width="600" class="size-full wp-image-1406" /></a><p class="wp-caption-text">Define your compilable source and the headers.</p></div></p>
<p><br/><a name="step_6"></a></p>
<h3>6. Schemes Setup</h3>
<p><a href="#list_contents">top</a><br />
This is an important change to compile our framework. You don&#8217;t need to compile it in the Debug modes, we just need the Release mode, because if you have any Macro in your code which works only in Debug mode, like DEBUG macro, it will assume the configuration of the product that the other developers will make. So to us now, only the Release is important.</p>
<p>You can change it accessing the menu <strong>Product > Manage Schemes&#8230;</strong> or by the schemes short cut: the drop list in front at the Build/Run bottom in the top left corner of the Xcode window.</p>
<p>At this point could be a good idea to delete all the current schemes and then press the button &#8220;<strong>AutoCreate Schemes Now</strong>&#8220;. The important is select your framework target and hit the button &#8220;<strong>Edit</strong>&#8221; at the bottom. In the next window, change the &#8220;<strong>Build Configuration</strong>&#8221; from Debug to Release. Change to Release in all the situations: Run, Test, Profile, Analyze and Archive. By doing this, we ensure that our framework target will always compile the Release version.</p>
<div id="attachment_1407" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_manage_schemes.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_manage_schemes.jpg" alt="Build the custom framework only to Release." title="xcode_manage_schemes" width="600"  class="size-full wp-image-1407" /></a><p class="wp-caption-text">Build the custom framework only to Release.</p></div>
<p><br/><a name="step_7"></a></p>
<h3>7. Building the Framework</h3>
<p><a href="#list_contents">top</a><br />
OK, here is the annoying step of this process. Until now, I don&#8217;t figure out a more easy an elegant way to do this. You must to compile this target twice: one to <strong>iOS Device</strong> (this will compile for the architectures armv6/arvm7) and to <strong>iOS Simulator</strong> (can be iPhone or iPad with any SDK, doesn&#8217;t matter, the simulator always will compile for the architecture i386).</p>
<p>I&#8217;ve tried another way, like create an &#8220;integrator&#8221; and I placed two targets to its &#8220;Target Dependencies&#8221;, but trust me, it&#8217;s worst, because you need to change 2 targets instead 1 in cases when you change the framework content. Besides, the dependencies will assume the architectures of the &#8220;integrator&#8221;, so you need to compile twice too. Anyway&#8230;  the best solution I found until now is use only 1 target and build it twice. If you find a better one, please tell me.</p>
<div id="attachment_1408" class="wp-caption aligncenter" style="width: 380px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_compile_ios_simulator.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_compile_ios_simulator.jpg" alt="Compile the framework target twice: iOS Device and Simulator." title="xcode_compile_ios_simulator" width="370" height="194" class="size-full wp-image-1408" /></a><p class="wp-caption-text">Compile the framework target twice: iOS Device and Simulator.</p></div>
<p>After the compile complete, you can see in the &#8220;<strong>Products</strong>&#8221; folder in the Project Navigator at the left, that your framework product now is active. Right click on it and hit &#8220;<strong>Show in Finder</strong>&#8220;. Take a look at this product, its is your iOS Framework! Great!</p>
<p>But we&#8217;re not done yet. You can test this product in other applications if you want, but it will only work to one architecture. We must to create an Universal version of this product. If you look around your framework product in the Finder, you&#8217;ll see that it is in a folder called &#8220;Release-iphoneos&#8221; (if you didn&#8217;t change the destination folder in the Build Settings). And if you have compiled to Simulator too, you&#8217;ll see another folder called &#8220;Release-iphonesimulator&#8221; which contains the same framework product, but this version is for architecture i386.</p>
<p>So, let&#8217;s join both products into one.</p>
<p><br/><a name="building_universal"></a></p>
<h2><strong>Building the Universal Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_8"></a><br />
<h3>8. Creating Universal Target:</h3>
<p><a href="#list_contents">top</a><br />
To join both architectures products into one, we must to use the <strong>Lipo Tool</strong>. It&#8217;s a tool which comes with iOS SDK, just to know, it is in &#8220;<Xcode Folder>/Platforms/iPhoneOS.platform/Developer/usr/bin&#8221;, its file name is &#8220;lipo&#8221;. But we don&#8217;t need to know this path, Xcode can deal with it to us.</p>
<p>To use the Lipo Tool we&#8217;ll need to create a &#8220;<strong>Run Script</strong>&#8221; at the &#8220;<strong>Build Phase</strong>&#8220;, you can create it in your previously Bundle Target, but my advice is to create another target. I say to create another target to avoid compiling errors. This script will need to use &#8220;Release-iphoneos&#8221; and &#8220;Release-iphonesimulator&#8221; folders, so if the folders or products inside them not exist yet, the compiler will generate errors.</p>
<p>Let&#8217;s add a new target, hit the &#8220;<strong>Add Target</strong>&#8221; button, just as you did with Bundle Target. At this time a good choice is the &#8220;Aggregate&#8221; target. It doesn&#8217;t create any product directly, its purposes is just to aggregate another targets and run some scripts, exactly what we want!</p>
<div id="attachment_1409" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_all.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_all.jpg" alt="Use the &quot;Aggregate&quot; target to construct a run script." title="xcode_build_all" width="600" class="size-full wp-image-1409" /></a><p class="wp-caption-text">Use the &quot;Aggregate&quot; target to construct a run script.</p></div>
<p><br/><a name="step_9"></a></p>
<h3>9. Lipo Tool Script:</h3>
<p><a href="#list_contents">top</a><br />
We are almost there, now it&#8217;s time to create the Run Script to use the Lipo Tool. Well, you probably will need to make some changes in the code bellow to fit it to your framework name or folders (if you set different folders to build for). Here is the script to use:</p>
<table width="675">
<tbody>
<tr>
<th>Xcode Script to Lipo Tool</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
if [ "${ACTION}" = "build" ]
then
# Set the target folders and the final framework product.
    INSTALL_DIR=${SYMROOT}/FI.framework
    DEVICE_DIR=${SYMROOT}/Release-iphoneos
    SIMULATOR_DIR=${SYMROOT}/Release-iphonesimulator

# Create and renews the final product folder.
    mkdir -p "${INSTALL_DIR}"
    rm -rf "${INSTALL_DIR}"
    rm -rf "${INSTALL_DIR}/FI"

# Copy the header files to the final product folder.
    ditto "${DEVICE_DIR}/FI.framework/Headers" "${INSTALL_DIR}/Headers"

# Use the Lipo Tool to merge both binary files (i386 + armv6/armv7) into one Universal final product.
    lipo -create "${DEVICE_DIR}/FI.framework/FI" "${SIMULATOR_DIR}/FI.framework/FI" -output "${INSTALL_DIR}/FI"
fi
.</pre>
<div id="attachment_1411" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_run_script.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_run_script.jpg" alt="Lipo script to join products for architectures i386 and armv6/armv7." title="xcode_run_script" width="600" class="size-full wp-image-1411" /></a><p class="wp-caption-text">Lipo script to join products for architectures i386 and armv6/armv7.</p></div>
<p>Now build the Aggregate target. At this time doesn&#8217;t matter if you build for iOS Device or Simulator, because all that it will make is run the script, nothing more. The above script creates the final Universal Framework at the ${SYMROOT} path, this is the same path of your Bundle target. So you can right click on the Framework product in the &#8220;Products&#8221; again and hit &#8220;Show in Finder&#8221;. Move to the level with &#8220;Release-iphoneos&#8221; and &#8220;Release-iphonesimulator&#8221; folders. Now, there is a new folder with the &#8220;.framework&#8221; extension, it&#8217;s your <strong>Universal Framework to iOS</strong>!</p>
<p><strong>Congratulations!</strong></p>
<p><br/><a name="testing"></a></p>
<h2><strong>Testing your Universal Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_10"></a><br />
<h3>10. Testing:</h3>
<p><a href="#list_contents">top</a><br />
To test your Universal Framework could be a good idea take it from that folder and place it in another one more easy to find, like the Desktop or ~/Library/Frameworks. Well, to avoid take it from that folder every time, you can change the Run Script above. Just change the &#8220;<strong>INSTALL_DIR</strong>&#8221; variable and set a path of your choice, make sure you choose a path with the write permissions. A good choice could be use the Xcode variable <strong>${SRCROOT}</strong> which represents your project folder root, so you can set <strong>${SRCROOT}/Products</strong> or something like that.</p>
<p>Anyway, with your Universal Framework in an &#8220;user friendly path&#8221;, create a new Xcode project, select the Application target and go to &#8220;<strong>Build Phase</strong>&#8221; tab. Open the section &#8220;<strong>Link Binary With Libraries</strong>&#8221; and hit the &#8220;<strong>+</strong>&#8221; to add a new Framework. Click the &#8220;<strong>Add Other&#8230;</strong>&#8221; button and select your Universal Framework. Remember, you must to select the &#8220;<strong>.framework</strong>&#8221; folder.</p>
<p>After the importing, Xcode will know everything about your custom framework. So try to write some code using your framework classes. Remember to import your Framework Principal Header as a framework notation. Xcode will use your public headers in the Code Completion.</p>
<div id="attachment_1414" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_framework_active.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_framework_active.jpg" alt="Xcode knows your public headers and can use them in the Code Completion." title="xcode_framework_active" width="600" class="size-full wp-image-1414" /></a><p class="wp-caption-text">Xcode knows your public headers and can use them in the Code Completion.</p></div>
<p>I like to use the Xcode Midnight Color Theme, so the classes of the project are green and the framework classes are blue. I love blue classes! <img src='http://db-in.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><br/><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p><a href="#list_contents">top</a><br />
Well done, my friends! As we are used, let&#8217;s make a final review and take care with some possible problems.</p>
<ul>
<li>In a common Xcode project, create a Bundle target.</li>
<li>Make the necessary setup, place your sources, headers and resources in it and finally change the its Schemes configuration.</li>
<li>Compile to iOS Device (armv6/armv7) and to Simulator (i386).</li>
<li>Create an Aggreate target and place a <strong>Run Script</strong> in it.</li>
<li>Enjoy your real <strong>Universal Framework to iOS</strong>!</li>
</ul>
<p>To finish I want to talk about some issues that I had:</p>
<ul>
<li>Take special care with the architectures. Don&#8217;t write the i386 directly in the <strong><em>Valid Architectures</em></strong> setting, always use the <strong>$(ARCHS_STANDARD_32_BIT)</strong>. Plus, always set the <strong><em>Build Active Architecture Only</em></strong> to <strong>NO</strong>.</li>
<li>Take care with your classes structure. If you set, for example, the ClassB.h as a Project or Private header, but in your code you import it into a Public header, this will cause conflicts.</li>
<li>Take care with the <strong><em>Install Directory</em></strong> and <strong><em>Skip Install</em></strong> settings. They can generate warning if the folders permissions or paths are not right set.</li>
<li>Finally, take a special care with the Lipo Tool script. It could generate warnings and/or errors if the paths was not found or the folder permissions was not right set.</li>
</ul>
<p>This is all, buddy.<br />
As I told you, the annoying thing is that you need build 3 times to generate a new Universal Framework: 2 x Bundle target (one to iOS Device and other to the Simulator) and 1x to the Aggregate target (which will run a script). But by my experience, this is not to much, you will create the final product only few times. At the great majority, you will test your Framework classes directly with the Application target in your Framework Xcode Project.</p>
<p>Enjoy your real Framework to iOS!</p>
<p>Thanks for reading,<br />
See you soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/05/creating-universal-framework-to-iphone-ios/feed/</wfw:commentRss>
		<slash:comments>46</slash:comments>
		</item>
		<item>
		<title>Khronos EGL and Apple EAGL</title>
		<link>http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/</link>
		<comments>http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 04:56:20 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[OpenGL ES]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=930</guid>
		<description><![CDATA[Hi again everybody! This will be a little article to give support to my full tutorial about OpenGL. In this article I&#8217;ll talk about the EGL API and the EAGL (the EGL API implemented by Apple). We&#8217;ll see how to set up an OpenGL&#8217;s application to comunicate with the device&#8217;s windowing system. I&#8217;ll focus on&#8230;]]></description>
			<content:encoded><![CDATA[<p>Hi again everybody!</p>
<p>This will be a little article to give support to my full tutorial about OpenGL. In this article I&#8217;ll talk about the EGL API and the EAGL (the EGL API implemented by Apple). We&#8217;ll see how to set up an OpenGL&#8217;s application to comunicate with the device&#8217;s windowing system.</p>
<p>I&#8217;ll focus on Objective-C and iOS, but I&#8217;ll talk about the setup in others devices and languages too. So let&#8217;s start!<br />
<span id="more-930"></span><br />
<br/></p>
<h2><strong>At a glance</strong></h2>
<p>As I said in the first part of my full tutorial about OpenGL (<a href="http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13/">click here to see</a>), OpenGL is not responsible by manage the windowing system of each device that support it. OpenGL relinquished this responsability. So, to make the bridge between OpenGL&#8217;s render output and the device&#8217;s screen, Khronos group created the EGL API.</p>
<p>Remember that EGL can be modified by the vendors to fit exactly what they need to their devices and windowing systems. So my big advice in this article is: ALWAYS CONSULT THE EGL INSTRUCTIONS FROM YOUR VENDORS.</p>
<p><br/></p>
<h2><strong>Setup EGL API</strong></h2>
<p>OK, now we&#8217;ll enter in a EGL&#8217;s comum area, independently to the vendors&#8217;s implementation, the EGL&#8217;s logics is always needed.</p>
<p>The first thing that EGL needs to know is where we want to display our content, normally it is done with the function <strong>eglGetDisplay</strong>, which returns a EGLDisplay data type. A constant EGL_DEFAULT_DISPLAY is always implemented by the vendors to return their default display. Right after this you call <strong>eglInitialize</strong> to initialize the EGL API, this function will return a boolean data type to inform the status. So normally you start with the code:</p>
<pre class="brush:csharp">
EGLDisplay display;

display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

if (eglInitialize(display, NULL, NULL))
{
    // Proceed with your code.
}
</pre>
<p>The NULL, NULL parameters are pointers, which you can get the major and minor version of the current EGL&#8217;s implementation. I don&#8217;t want to go deeply here, the important thing is understand this step. The EGL API need to know where is the display to initialize, just it!</p>
<p>OK, the next step is the configuration. Once EGL know the display, it can prepare the bridge between OpenGL&#8217;s output and the device&#8217;s screen. To start constructing this bridge, the EGL needs some configurations, which involve the color format, colors individually, the sizes, the transparency, the samples per pixel, pixel format and many others. By default EGL provide a lot of functions to this step, like <strong>eglGetConfigs</strong> or <strong>eglChooseConfigs</strong>. Here the interference of the vendors is more intense, because they need to provide a bunch of configurations about their systems and devices. I&#8217;ll not describe it here, there are so many systems and languages. So again, always consult your vendors.</p>
<p>The last step is more simple. After all configurations, you instruct EGL API to create a render surface, this means, the surface on which your OpenGL&#8217;s render output will be placed. You can choose between a On-Screen or a Off-Screen surface. The first means your render output will go directly to the device&#8217;s screen, the Off-Screen means that your render output will go to a buffer or to a image file, a snapshot, or anything like that. You can define the surface by using <strong>eglCreateWindowSurface</strong> or <strong>eglCreatePbufferSurface</strong>, both will return an EGLSurface.</p>
<p>But here a little advice, if you want to place your render&#8217;s output onto a Off-Screen surface, is better you use a frame buffer directly with OpenGL&#8217;s API instead to create a EGL&#8217;s PBuffer. Is faster and cost less for your application.</p>
<p>Are we ready now?</p>
<p>Not yet. This is just the platform&#8217;s side of the bridge, EGL has the other side of the bridge, the OpenGL&#8217;s side.</p>
<p><br/></p>
<h2><strong>EGL Context</strong></h2>
<p>Until now, EGL knows all that it need about the windowing system, but now EGL needs to know all about our OpenGL usage. Deeply, EGL works with 2 frame buffers. Do you remember what is frame buffer from the first part of OpenGL&#8217;s tutorial, right? (<a href="http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13#Buffers">click here if not</a>). The EGL API use these 2 frame buffer to place the OpenGL&#8217;s render output into your desired surface.</p>
<p>To make it properly, EGL needs to know where are the OpenGL&#8217;s buffers which you want to render. This step is very simple. All that we need is create a EGL context and make it the current context (yes, we can create many contexts). Once we made a context the current context, the subsequent Frame Buffer we use in OpenGL will be used by EGL context. Only one Frame Buffer can be used at time (the next part of OpenGL&#8217;s tutorial will talk deeply about this). Usually, the EGL functions to context are:</p>
<table width="675">
<tr>
<th>EGL Context</th>
</tr>
<tr>
<td>
<h5><strong>EGLContext eglCreateContext(EGLDisplay display, EGLConfig config, EGLContext shareContext, const EGLint* attribList)</strong></h5>
<p><br/></p>
<ul>
<li><strong>display</strong>: The previously get display.</li>
<li><strong>config</strong>: The previously set configuration.</li>
<li><strong>shareContext</strong>: Usually is EGL_NO_CONTEXT to share no context.</li>
<li><strong>attribList</strong>: To OpenGL ES, this parameter determines which version of OpenGL ES will be used. Value 1 represent a context of OpenGL ES 1.x and a value of 2 represent a context of OpenGL ES 2.x.</li>
</ul>
</td>
</tr>
<tr>
<td>
<h5><strong>EGLBoolean eglmakeCurrent(EGLDisplay display, EGLSurface draw, EGLSurface read, EGLContext context)</strong></h5>
<p><br/></p>
<ul>
<li><strong>display</strong>: The display obtained previously.</li>
<li><strong>draw</strong>: The surface obtained previously.</li>
<li><strong>read</strong>: The same value as draw.</li>
<li><strong>context</strong>: The context to be the current.</li>
</ul>
</td>
</tr>
</table>
<p>Seems a little confused? Don&#8217;t worry. I&#8217;m talking superficially about this. The point here is to you understand which an EGL&#8217;s Context represent the OpenGL&#8217;s side of the bridge. The most important advice I can give you is: Look for the vendors documentation of EGL API.</p>
<p><br/><a name="rendering"></a></p>
<h2><strong>Rendering with EGL Context</strong></h2>
<p>Once the EGL knows about the windowing system and has a context to know about our OpenGL application, we can make our render&#8217;s output be presented onto the desired surface.</p>
<p>The render step is very very simple. Do you remember I said EGL works with 2 internal frame buffers? Now is time to use that. All that we need is instruct the EGL to swap the buffers. Swap? Why?</p>
<p>While EGL present one frame buffer to your desired surface, the other one stay on back waiting for a new render output. The buffer on the back will be filled with all renders you did until the next call to EGL swap the buffers and when you do this, EGL brings the back buffer to the front and present the final render&#8217;s output onto the desired surface, while the old front buffer goes to the back to reinitiate the process.</p>
<p>This technique is a great boost on our application&#8217;s performance, because the our final surface will not be notified every time we execute a render command. The final surface will be notified only when we finish all the renders commands. Another improvement is because the buffer on the back will receive the render&#8217;s outputs faster than a device&#8217;s screen, for example.</p>
<div id="attachment_944" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/02/swap_buffers_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/02/swap_buffers_example.jpg" alt="EGL API swap the buffers to present the render onto the desired surface." title="swap_buffers_example" width="600" height="600" class="size-full wp-image-944" /></a><p class="wp-caption-text">EGL API swap the buffers to present the render onto the desired surface.</p></div>
<p>This is the function to swap the buffers and present the render output onto the desired surface.</p>
<table width="675">
<tr>
<th>Swap the EGL&#8217;s buffers</th>
</tr>
<tr>
<td>
<h5><strong>EGLBoolean eglSwapBuffers(EGLDisplay display, EGLSurface surface)</strong></h5>
<p><br/></p>
<ul>
<li><strong>display</strong>: The display obtained previously.</li>
<li><strong>surface</strong>: The surface obtained previously.</li>
</ul>
</td>
</tr>
</table>
<p>OK, this is all about the EGL making the bridge between the OpenGL&#8217;s core and the windowing systems. I know that seems many steps to just output a simple render. But look from far, is just a little setup:</p>
<ol>
<li>Initialize the EGL API with the display and surface given by your vendor.</li>
<li>Make the configurations to your desired surface.</li>
<li>Create a context and make it your current context.</li>
<li>Ask for your EGL context to swap its internal buffers.</li>
</ol>
<p>Now I&#8217;ll talk about EGL implementation by Apple, which has a lot of changes from the original, many changes!</p>
<p><br/></p>
<h2><strong>EAGL &#8211; The Apple&#8217;s EGL API</strong></h2>
<p><a href="http://db-in.com/blog/wp-content/uploads/2011/02/egl_eagl_apis.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/02/egl_eagl_apis-300x196.jpg" alt="" title="egl_eagl_apis" width="300" height="196" class="alignright size-medium wp-image-978" /></a>The EAGL (which we are used to pronounce Eagle) is the implementation by Apple of EGL API. The most important thing to know about EAGL is which the Apple doesn&#8217;t allow us to render directly to the screen. We must to work with frame and render buffers.</p>
<p>But why the Apple changed EGL so much? Well, you know the Apple&#8217;s approach, Cocoa Framework is almost like another language, it has infinities rules, hard rules! If you change the place of one little screw, all the framework will down! So the Apple made that changes to fit the EGL API into the Cocoa&#8217;s rules.</p>
<p>Using EAGL, we must to create a color render buffer and draw our render&#8217;s output into it. Plus, we must to bind that color render buffer to a special Apple&#8217;s layer called CAEAGLLayer. And finally to make a render, we need to ask the context to present that color render buffer. In deeply, this command will swap the buffer just like original EGL context, but our code changes a lot. Let&#8217;s see.</p>
<p><br/></p>
<h2>Setup EAGL API</h2>
<p>The first thing we need to do is create a sub-class from UIVIew. Inside this new class, we need to change its Core Animation layer. Doing this is equivalent in the original EGL API to initialize the API, take the display from the windowing system and define our surface. So, in this equivalence we&#8217;ll have <strong>EGLDisplay = the UIWindow which has our custom view</strong> and <strong>EGLSurface = our sub-class from UIView</strong>.</p>
<p>Our code will be like this:</p>
<pre class="brush:csharp">
#import &lt;UIKit/UIKit.h&gt;

@interface CustomView : UIView

@end

@implementation CustomView

// Overrides the layerClass from UIView.
+ (Class) layerClass
{
    // Instead to return a normal CALayer, we return the special CAEAGLLayer.
    // Inside this CAEAGLLayer the Apple did the most important part
    // of their custom EGL's implementation.
    return [CAEAGLLayer class];
}

@end
</pre>
<p>Now we need to make the step of configure the EGL API defining the color format, the sizes and others. In EAGL we do this step by setting the properties of our CAEAGLLayer. So let&#8217;s code:</p>
<pre class="brush:csharp">
@implementation CustomView

...

- (id) initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
	{
		// Assign a variable to be our CAEAGLLayer temporary.
		CAEAGLLayer *eaglLayer = (CAEAGLLayer *)[self layer];

		// Construct a dictionary with our configurations.
		NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
							 [NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking,
							 kEAGLColorFormatRGB565, kEAGLDrawablePropertyColorFormat,
							 nil];

		// Set the properties to CAEALLayer.
		[eaglLayer setOpaque:YES];
		[eaglLayer setDrawableProperties:dict];

		// Other initializations...
	}

    return self;
}

...

@end
</pre>
<p><br/></p>
<h2>EAGL Context</h2>
<p>Following the EGL API steps, the next one is about the context. Here again the Apple changes almost all to fit the EGL API into their Cocoa Framework. The EAGL API gives to us only two Objective-C classes, one of then is EAGLContext. The EAGLContext is equivalent to EGLContext.</p>
<p>Here I have to admit, even changing everything the Apple made this step easer than EGL API. All that you need is allocate a new instance of EAGLContext initializing it with your desired OpenGL ES&#8217;s version (1.x or 2.x) and call a method to make that context the current one. Here you don&#8217;t have to inform again the EGLDisplay, the EGLSurface, the EGLContext and the others annoying parameters as in the origial EGL API.</p>
<pre class="brush:csharp">
@interface CustomView : UIView
{
	EAGLContext *_context;
}

@end

@implementation CustomView

...

- (id) initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
	{
		// Other initializations...

		// Create a EAGLContext using the OpenGL ES 2.x.
		_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

		// Make our new context, the current context.
		[EAGLContext setCurrentContext:_context];
	}

    return self;
}

...

@end
</pre>
<p><br/><a name="renderingeagl"></a></p>
<h2>Rendering with EAGL Context</h2>
<p>Next step!<br />
By following the above EGL&#8217;s steps the next one is the swap the buffers (rendering). But here the Apple changed the thing a lot. As I said before, to use EAGL we must to create at least a color render buffer, this necessarily needs a frame buffer too. So in the reality the next step should be the buffers creations. I could describe this step here, but as this article is just a middle point between the first and the second part of my full tutorial, describe it is not my intention here. I&#8217;ll let this discussion to the next part of that tutorial.</p>
<p>So let&#8217;s go to the final EAGL&#8217;s step, the rendering.<br />
I told you Apple uses a color render buffer instead to directly swap the context&#8217;s buffers. By doing this, Apple simplified the last step, the swap of the buffers. Instead to swap the buffers informing the desired display and surface, we just ask our EAGLContext to present its render buffer.</p>
<pre class="brush:csharp">
@interface CustomView : UIView
{
	EAGLContext *_context;
}

- (void) makeRender;

@end

@implementation CustomView

...

- (void) makeRender
{
	[_context presentRenderbuffer:GL_RENDERBUFFER];
}

...

@end
</pre>
<p>The param GL_RENDERBUFFER to <strong>presentRenderbuffer</strong> is a constant and is just for internal usage. This call should occurs just after we perform all our changes to our 3D objects, like translates or rotations.</p>
<p>Well, this is all the basic instructions about EGL and EAGL APIs. Obviously using EAGL, you could take a more OOP approach, by separating your custom UIView of the other class which hold the EAGLContext instance and makes the final presentation.</p>
<p>Now, as we are used to, let&#8217;s remember the steps using the EAGL.</p>
<ol>
<li>Make a sub-class from UIView and override the layerClass method to return an instance of CAEAGLLayer;</li>
<li>Set up the properties to the CAEAGLLayer;</li>
<li>Create an instance from EAGLContext;</li>
<li>Present a color render buffer onto the screen by using the EAGLContext.</li>
</ol>
<p><br/></p>
<h2><strong>Conclusion</strong></h2>
<p>Well done, my friends.<br />
Think in this article like an abstract class! Is a little step, but is also so much annoying to cover this in the second part of my OpenGL&#8217;s tutorial.</p>
<p>If you were to save only a single sentence of this entire article, the phrase would be: &#8220;Consult the EGL instruction from your vendors!&#8221;. The vendors don&#8217;t interfere inside OpenGL, so I can talk about it independently from the system or language. But the EGL API is the bridge between a unified OpenGL API and all the systems which support OpenGL. So the interference from the vendors on the EGL is bigger! Just like the Apple did!</p>
<p>Thanks for reading!</p>
<p>See you in the next part of OpenGL&#8217;s tutorial!</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

