<?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</title>
	<atom:link href="http://db-in.com/blog/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>All about Shaders &#8211; (part 1/3)</title>
		<link>http://db-in.com/blog/2011/08/all-about-shaders-part-13/</link>
		<comments>http://db-in.com/blog/2011/08/all-about-shaders-part-13/#comments</comments>
		<pubDate>Thu, 11 Aug 2011 18:32:00 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Feature]]></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=1440</guid>
		<description><![CDATA[A series of  full tutorials about OpenGL ES Shader Language (GLSL ES) focused on iOS using Objective-C and Xcode.]]></description>
			<content:encoded><![CDATA[<p>Hello again, my friends!</p>
<p>Let&#8217;s start a new series of tutorials, at this time let&#8217;s go deep in shaders universe, the most exciting part of OpenGL programmable pipeline. We&#8217;ll treat about textures, lights, shadows, per-pixel effects, bump, reflections and more.</p>
<p>This series is composed by 3 parts:</p>
<ul>
<li>Part 1 &#8211; Basic concepts about GLSL ES (Beginners)</li>
<li>Part 2 &#8211; Shaders Effects (Intermediate)</li>
<li>Part 3 &#8211; Mastering effects with OpenGL Shader Language (Advanced)</li>
</ul>
<p><span id="more-1440"></span><br />
<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="#shading_types">Shading Types</a></li>
<li><a href="#opengl_shaders">OpenGL Shaders</a></li>
<li><a href="#normal">Normal Vector</a>
<ul>
<li><a href="#smooth_angle">Normal&#8217;s Smooth Angle</a></li>
</ul>
</li>
<li><a href="#tangent">Tangent Space</a></li>
<li><a href="#texcoord">Texture Coordinates</a></li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
</td>
</tr>
</table>
<p><br/></p>
<h2><strong>At a glance</strong></h2>
<p><a href="http://db-in.com/blog/wp-content/uploads/2011/07/glsles_featured.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/07/glsles_featured-300x300.jpg" alt="" title="glsles_featured" width="300" height="300" class="alignleft size-medium wp-image-1453" /></a>We&#8217;ll study in-depth the shaders language (more specifically the GLSL ES, the shader language for Embedded Systems) and let&#8217;s make great effects using the shaders like specular lights and reflections, bump maps, refractions, reflections and more.</p>
<p>In this first part I&#8217;ll cover the basic concepts sobre shaders and GLSL ES. We&#8217;ll need to drill deep in something called Tangent Space, which is an intermediate level, so I&#8217;ll create an article between the part 1 and 2 specific to treat Tangent Space concepts and its creation.</p>
<p>In the second part let&#8217;s start creating some interesting effects like specular lights, reflections and refractions. Besides, on the second one let&#8217;s create the environment mappings by using the cube texture.</p>
<p>Finally in the last part let&#8217;s make the most advanced effect, the bump mapping and see what is the difference between Normal Mapping, Bump Mapping and Parallax Mapping.</p>
<p>Hands to work!</p>
<p><br/><a name="shading_types"></a></p>
<h2><strong>Shading Types</strong></h2>
<p><a href="#list_contents">top</a><br />
First off, we need to understand the evolution of that we call shader. Today we have many computations on the GPU and several shader techniques that achieve really good results, but how did we get here?</p>
<p>Once upon a time, there was a single shading technique, called <strong>Flat Shading</strong>. It defines that light is computed with the normal vector and each FACE of the mesh has a normal vector. The term &#8220;FACE&#8221; here means a polygon (usually a triangle).</p>
<div id="attachment_1449" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/07/shader_techniques_flat.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/07/shader_techniques_flat.jpg" alt="Flat Shading" title="shader_techniques_flat" width="600" height="503" class="size-full wp-image-1449" /></a><p class="wp-caption-text">Flat Shading</p></div>
<p>With the evolution of the hardwares we start to process values for each vertex, this improvement took us into a new level, making more light effects. This shading technique was called <strong>Goraud Shading</strong>.</p>
<div id="attachment_1450" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/07/shader_techniques_goraud.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/07/shader_techniques_goraud.jpg" alt="Goraud Shading" title="shader_techniques_goraud" width="600" height="503" class="size-full wp-image-1450" /></a><p class="wp-caption-text">Goraud Shading</p></div>
<p>Then we discovered something that produces really nice results, the <em>interpolation</em>. It&#8217;s a process which we calculate all the intermediate points between two other points. We use it all the time. For example, if a point A has a texture coordinate U:1 V:2 and a point B has U:2 V:5, the interpolation will calculate all the middle points from 1,2 to 2,5. This is know as <strong>Phong Shading</strong>.</p>
<div id="attachment_1451" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/07/shader_techniques_phong.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/07/shader_techniques_phong.jpg" alt="Phong Shading" title="shader_techniques_phong" width="600" height="503" class="size-full wp-image-1451" /></a><p class="wp-caption-text">Phong Shading</p></div>
<p>But for many reasons, to simulate the real world, we need more than a linear interpolation. Surfaces have many details that change the way the light and shadow reacts. So we discovered a way to produce infinities values over a surface using less processing time. This technique was called <strong>Bump Shading</strong>.</p>
<div id="attachment_1452" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/07/shader_techniques_bump.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/07/shader_techniques_bump.jpg" alt="Bump Shading" title="shader_techniques_bump" width="600" height="503" class="size-full wp-image-1452" /></a><p class="wp-caption-text">Bump Shading</p></div>
<p>Today we have some advanced Bump&#8217;s techniques, but all of them have the same basic concept: store each value surface deformation value as a set of RGB color. So, basically, the Bump Shading takes advantage of a texture map that store coordinates within a RGB format. The coordinates in there can be used for many things: Normals, Tangents, Bitangents, Vertices positions or anything else we want. Usually the textures for <strong>Bump Shading</strong> is called Normal Maps, because we store the Normal Vector value in it.</p>
<p>By default, OpenGL uses the Phong Shading, making the interpolations between the Vertex Shader&#8217;s outputs and Fragment Shader&#8217;s inputs. This information is very important, so I&#8217;ll repeat: &#8220;Vertex Shader&#8217;s outputs are interpolated to Fragment Shader&#8217;s inputs&#8221;. Technically, this is what happens:</p>
<table style="text-align:center;">
<tr>
<th colspan="3">Interpolation Table</th>
</tr>
<tr>
<th>&nbsp;</th>
<th>Vertex Shader</th>
<th>Fragment Shader</th>
</tr>
<tr>
<th>Vertex A</th>
<td>0.0</td>
<td>0.0</td>
</tr>
<tr>
<th>&nbsp;</th>
<td>-</td>
<td>0.25</td>
</tr>
<tr>
<th>&nbsp;</th>
<td>-</td>
<td>0.50</td>
</tr>
<tr>
<th>&nbsp;</th>
<td>-</td>
<td>0.75</td>
</tr>
<tr>
<th>Vertex B</th>
<td>1.0</td>
<td>1.0</td>
</tr>
</table>
<p><br/><a name="opengl_shaders"></a></p>
<h2><strong>OpenGL Shaders</strong></h2>
<p><a href="#list_contents">top</a><br />
Here is a brief review about the shaders that we&#8217;ve seen on previous tutorials:</p>
<ul>
<li>Shader is the way to calculate everything related to our 3D objects by our own (from the vertices positions to the most complex light equations).</li>
<li>Vertex Shaders (VSH) are processed one time for each object&#8217;s vertex. Fragment Shader (FSH) are processed one time for each fragment (not necessarely a pixel) of the visible object (<a href="http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13/" title="All about OpenGL ES (2/3)" target="_blank">http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13/</a>).</li>
<li>You can set constant values for Uniforms to work throughout the VSH and FSH processing (<a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/" title="All about OpenGL ES (2/3)" target="_blank">http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/</a>).</li>
<li>Dynamic variables can be assigned only to the Attribute kind, which is exclusive of VSH. You can send a variable from VSH to FSH via Varyings, but remember that those values will be <span style="color:#FF0000"><strong>interpolated</strong></span>!</li>
</ul>
<p>The shaders are small pieces of code that will be processed directly in the GPU. Unfortunately, even in these days (2011) our hardwares are very poor and slow if compared with the real amount of calculations that exist in the real world. The most advanced hardware trying to calculate a real phenomenon of the sun light passing through the water in a pool could take days to calculate a single frame. In the other hand, the real nature calculates all physical phenomenon instantly (OK, the mother nature makes a kind of &#8220;calculation&#8221;, not exactly an equation).</p>
<p>While we stay on the &#8220;Era of Bits&#8221; we can&#8217;t try to calculate the real phenomenons (I wrote an article about the &#8220;<a href="http://db-in.com/blog/2011/05/binary-world/" target="_blank">Binary World</a>&#8221; where I talked about the new Era of Quantum computers, maybe there, in the &#8220;Era of Quantums&#8221;, we&#8217;ll be able to reproduce our 3D world closest from the reality).</p>
<p>Anyway, what I meant is that the shaders are something trying to reproduce the real world with a very very abstractly code, making a bunch of simplifications of the real world. So if you want to mastering the shader, you must learn to extract some abstract pieces of code from the real world phenomenons. But don&#8217;t worry too much about it now, in the right time you&#8217;ll see that it&#8217;s an easy task and can be cool as well.</p>
<p>It&#8217;s important to start thinking in the concept of &#8220;Shader Program&#8221;. It&#8217;s a set of 2 (and only 2) shaders: a vertex shader and a fragment shader. So, we must think in the render as 2 different steps (vertex and fragment). Usually the Fragment shader is processed a lot of times more than the Vertex one. If a mesh has 10.000 vertices that means its Vertex Shader will generate 10.000 outputs to the Fragment Shader. Remember that those outputs will always be interpolated to the Fragment processing. So, to increase the performance we always try to place hard calculus in the Vertex Shader. Obviously there are calculus that we can&#8217;t accept interpolation to their values, like the bump effect, just in these cases we make the calculus inside the Fragment Shader.</p>
<p>However, make sure you got the correct distinction between the concept of making the calculus inside the Vertex Shader and another thing called Per-Vertex/Per-Fragment Light. We&#8217;ll see those concept in-depth later on, but just to clarify:</p>
<ul>
<li><strong>Per-Vertex Light</strong> means you have all the light calculus inside the Vertex Shader and them you interpolate the result to Fragment Shader.</li>
<li><strong>Per-Fragment Light</strong> means you have all last light calculus (the output value) inside the Fragment Shader, independent if the first steps was made in the Vertex or in the Fragment Shader.</li>
</ul>
<p>The interpolation happens on all Vertex Attributes, like the Texture Coordinates. As shown above in the Interpolation Table, the interpolated values from a texture coordinate can retrieve all the pixels from a texture. The Texture Coordinates usually is defined by a technique called &#8220;UV Map&#8221; or &#8220;UV Unwrap Map&#8221;, which is an artistic job, actually is almost impossible to create detailed UV Maps only with the code. Often a professional 3D software export the Texture Coordinates values within the model coordinates, based on definitions from an user friendly UV editor.</p>
<p>But there is another per-vertex Attribute very important to 3D world. With the shaders we calculate lights, shadows, reflections, refractions and any other effects we want. All of them need something in common, a <strong>Normal</strong> vector.</p>
<p><br/><a name="normal"></a></p>
<h2><strong>Normal Vector</strong></h2>
<p><a href="#list_contents">top</a><br />
This is one of the most important per-vertex attributes and its concept is very easy to understand. In the real world, basically, there are two things that can alter how the light rays affect a surface: the material (reflectiveness, refraction, specularity, shininess, etc.) and the surface&#8217;s angle. Well, actually, the point of view (the viewer&#8217;s eyes) also affect how we see the light, but let&#8217;s focus on the first two things. The normal vector is related to the surface&#8217;s angle. As the performance is something crucial to us, instead to re-calculate the angle of each surface (triangle) at every shader processing, we are used to pre-calculate a normal vector to every surface (triangle).</p>
<p>In simple words, the normal vector is an unit vector (magnitude equals to 1.0 and all axis range vary between [0.0, 1.0]) which represents the surface&#8217;s angle. Nice, now, how we can calculate it?</p>
<p>Well, that&#8217;s not an easy task, my friend. I had to read/watch/try a bunch of tutorials until I found the right formula. There are many people trying to teach how to calculate the normals. Some say that you must calculate per-face normals and store them into a buffer, others say to calculate the averaged normals between adjacent faces, some even say that you need to calculate each surface area to include in your final calculation. But no one gave me the right formula! I had to find it by my self, with the help of a great 3D software called MODO (by the way, I love it!).</p>
<p>Unfortunately, I&#8217;ll not explain how to calculate the normals in this first tutorial. I&#8217;ll create a separated article to show you how to get the right formula to calculate the normals. The normals deserve more attention than a simple subject inside one tutorial.</p>
<p>The most valuable point here is you understand that the Normal is an unit vector and visualize how the normals work together and how they fit into our shaders&#8217; context.</p>
<p><br/><a name="smooth_angle"></a></p>
<h3>Normal&#8217;s Smooth Angle</h3>
<p><a href="#list_contents">top</a><br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/08/shaders_bowling_example.jpeg"><img src="http://db-in.com/blog/wp-content/uploads/2011/08/shaders_bowling_example-300x240.jpg" alt="" title="shaders_bowling_example" width="300" height="240" class="alignright size-medium wp-image-1455" /></a>As we always make an abstraction of the real world, trying to simplify it, we have created a concept that does not exist in the real world: the Smooth Angle. Imagine this: in the real world the surfaces has infinities vertices, take for example the image of an sphere, maybe a bowling ball.</p>
<p>Try to imagine the smallest face/triangle that composes that bowling ball. Even if we try to use a microscope, we never will see a faceted area. Now take a look at our virtual spheres, even if we create a 3D mesh using a stupidly high resolution of 8 millions polygons, we&#8217;ll stay very very far from the perfection of the real world. By the way, for our 3D applications and games, we must work around thousands polygons, not millions. Does that means our 3D lights will seem ugly on low meshes? Fortunately we have a solution.</p>
<div id="attachment_1454" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/08/shaders_sphere_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/08/shaders_sphere_example.jpg" alt="Our 3D world always will have imperfections." title="shaders_sphere_example" width="600" height="570" class="size-full wp-image-1454" /></a><p class="wp-caption-text">Our 3D world always will have imperfections.</p></div>
<p>This problem can be solved with the Normal&#8217;s Smooth Angle. With simple words, it represents the maximum angle on which the light will looks continuous when reflected by a surface. The following picture helps us to understand this point better:</p>
<div id="attachment_1456" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/08/shaders_smooth_angle.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/08/shaders_smooth_angle.jpg" alt="The Smooth Angle is the angle between two adjacent faces." title="shaders_smooth_angle" width="600" height="600" class="size-full wp-image-1456" /></a><p class="wp-caption-text">The Smooth Angle is the angle between two adjacent faces.</p></div>
<p>Remember that smooth angle should be calculated when we calculate the Normals, so any post-change to the smooth angle will affect the entire Normals. I&#8217;ll talk more about the smooth angle in the article of the Normals calculations.</p>
<p><br/><a name="tangent"></a></p>
<h2><strong>Tangent Space</strong></h2>
<p><a href="#list_contents">top</a><br />
The Tangent Space is composed by two different components, actually there are three properties, the third one is the Normal Vector. As we&#8217;ve talked about the normals, let&#8217;s focus on the other two: Tangent and Bitangent (also known as Binormal, but the term &#8220;Binormal&#8221; is a mistake).</p>
<p>The Tangent and Bitangent are unit vectors, just as the Normal, the combination of these three components must form an Orthogonal and Orthonormal set. Before we go ahead, let me explain in simple words these two concepts:</p>
<ul>
<li><strong>Orthogonal</strong>: Two vectors that are perpendicular (form an angle of 90 degrees).</li>
<li><strong>Orthonormal</strong>: A set of vectors that are all Orthogonals and unit vectors.</li>
</ul>
<p>OK, these set of three vectors called Tangent Space is defined per-vertex. It&#8217;s purpose is define a local space for each face/vertex, which will be used to interpret the surface&#8217;s imperfection (bump map). The bump map (also known as normal map) is a RGB map that defines each relief of the surface.</p>
<p>It could sound confused to a text explanation. Just try to imagine this, as we always optimize everything in 3D world, the bump map is a technique that stores the surface&#8217;s deformations into a single image file. The Tangent Space is a set of vectors that allow us to parse the bump informations for each fragment, independent of the mesh&#8217;s rotation, position or scale. The following image illustrate the Tangent Space and its connection with the Texture Coordinates.</p>
<div id="attachment_1457" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/08/tangent_space_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/08/tangent_space_example.jpg" alt="The Tangent Space is a set of 3 vectors." title="tangent_space_example" width="600" height="600" class="size-full wp-image-1457" /></a><p class="wp-caption-text">The Tangent Space is a set of 3 vectors.</p></div>
<p>Basically the Tangent Vector points to where the &#8220;<strong>S</strong>&#8221; coordinate increases (S Tangent) and the Bitangent points to where the &#8220;<strong>T</strong>&#8221; coordinate increases (T Tangent).</p>
<p>It&#8217;s possible to exist more than a Tangent Space for a single vertex, in this case the vertex will break into two or more vertices with the same value for position, actually there are other important concepts in Tanget Space, but I&#8217;ll not bother you with the details in here. Just as the Normal&#8217;s calculations, I&#8217;ll let this complex part to another article dedicated to that subject. The important thing here is to you understand what is the bump maps and how the Tangent Space is important to make bump effects.</p>
<p><br/><a name="texcoord"></a></p>
<h2><strong>Texture Coordinates</strong></h2>
<p><a href="#list_contents">top</a><br />
This is the most common vector component for shaders. It&#8217;s responsible to place an image on a mesh&#8217;s surface. The Texture Coordinates (texcoord for short), is defined per-vertex. It&#8217;ll be interpolated along two vertices to achieve a per-fragment result. The texcoord is usually given in the range [0.0, 1.0], representing the order [S, T], which are the normalized values from the [U, V] notation.</p>
<p>The texcoord have more to do with the artistic work than with our code, usually the 3D softwares are responsible for generating it. The texcoord will directly affects how the texture image file should be created, I mean, the image of the texture must be created based on the texcoord positions. There are some 3D softwares that accept multiple texcoord channels. It could be good for some situations which multiple designers are working together, but it&#8217;s not good to the performance and optimization. There is nothing that multiple texcoord channels can make that a single channel can&#8217;t. So, keep it simple, always try to work with a single texcoord channel.</p>
<p>The texcoord is very important to create the Tangent Space. Multiple texcoord channels will need multiple Tangent Spaces as well. So, multiple channels is never a good idea.</p>
<p><br/><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p><a href="#list_contents">top</a><br />
OK, my friends, I don&#8217;t want to make this first tutorial too long, so these are the basic concepts about the Shader. Now you know how the shaders work, what are their limitations, where is their power and what we need to have before enter in the shaders&#8217; world.</p>
<p>In this tutorial you saw:</p>
<ul>
<li>The Shaders are responsible for all the visual results of our 3D world, including lights, shadows, reflections, refractions, etc.</li>
<li>There are four shading techniques most used: Flat Shading, Goraud Shading, Phong Shading and Bump Shading. OpenGL by default will use the Phong Shading.</li>
<li>The values from Vertex Shader to Fragment Shader will always be interpolated.</li>
<li>We have 3 very important per-vertex vectors: Position, Normal and Texture Coordinate.</li>
<li>The Normal Vector + 2 others form the Tangent Space, fundamental concept to produce the Bump Shading and any other displacement technique (like the Parallax Mapping).</li>
<li>Always try to use only one texcoord channel.</li>
</ul>
<p>Well done!<br />
My next article will not be the second part of this series, instead, it&#8217;ll be a short article covering how to calculate the Normal Vector and the Tangent Space. We&#8217;ll need to have those vectors very correct before enter in the real calculus inside the shaders&#8217; world.</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>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/08/all-about-shaders-part-13/feed/</wfw:commentRss>
		<slash:comments>8</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>All about OpenGL ES 2.x – (part 3/3)</title>
		<link>http://db-in.com/blog/2011/05/all-about-opengl-es-2-x-part-33/</link>
		<comments>http://db-in.com/blog/2011/05/all-about-opengl-es-2-x-part-33/#comments</comments>
		<pubDate>Thu, 05 May 2011 18:01:35 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[OpenGL ES]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1369</guid>
		<description><![CDATA[A full tutorial about OpenGL ES 2.x to iPhone, iPad, iPod using Objective-C and Xcode.]]></description>
			<content:encoded><![CDATA[<p><a href="http://db-in.com/blog/wp-content/uploads/2011/05/opengl_part3.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/opengl_part3.png" alt="" title="opengl_part3" width="300" height="352" class="alignright size-full wp-image-1417" /></a><br />
Here we are for the final part of this serie of tutorial!<br />
Welcome back, my friends.</p>
<p>Is time to dive in advanced knowledges about OpenGL and 3D world. In this tutorial we&#8217;ll see many things about the 2D graphics, multisampling, textures, render to off-screen surfaces and let&#8217;s try to optimize at maximum our applications&#8217; performance.</p>
<p>Is very important to you already know about all the concepts covered in the other 2 parts of this serie, if you miss something, here is a list:</p>
<p>This serie is composed by 3 parts:</p>
<ul>
<li><a href="http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13/" target="_blank">Part 1 &#8211; Basic concepts of 3D world and OpenGL (Beginners)</a></li>
<li><a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/" target="_blank">Part 2 &#8211; OpenGL ES 2.0 in-depth (Intermediate)</a></li>
<li>Part 3 &#8211; Jedi skills in OpenGL ES 2.0 and 2D graphics (Advanced)</li>
</ul>
<p><span id="more-1369"></span></p>
<p>At this time I imagine you know a lot of things about OpenGL and 3D world. You probably already created some applications using OpenGL, discovered many cool things, found some problems, even maybe your own engine/framework is under construction and I&#8217;m very glad in see you coming back.</p>
<p>As I&#8217;ve read once in a book: &#8220;One day you didn&#8217;t know to walk. Then you learned how to stand up and walk. Now is time to run, jump and swim!&#8221;&#8230; and why not &#8220;to fly&#8221;. With OpenGL our imagination has no limits, we can fly.</p>
<p>Let&#8217;s start.</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="#2d_graphics">2D graphics with OpenGL</a></li>
<li><a href="#grid">The Grid Concept</a></li>
<li><a href="#depth_buffer_2d">The Depth Render Buffer in 2D</a></li>
<li><a href="#cameras_2d">The Cameras with 2D</a></li>
<li><a href="#multisampling">The Multisampling</a></li>
<li><a href="#more_texture">More About Textures</a>
<ul>
<li><a href="#bpp">Bytes per Pixel</a></li>
<li><a href="#pvrtc"> PVRTC</a></li>
</ul>
</li>
<li><a href="#tips_tricks">Tips and Tricks</a>
<ul>
<li><a href="#cache">The Cache</a></li>
<li><a href="#store_values"> Store the Values</a></li>
<li><a href="#c_fastest"> C is Always the Fastest Language</a></li>
</ul>
</li>
<li><a href="#conclusion"> Conclusion</a></li>
</ul>
</td>
</tr>
</table>
<p><br/><br />
<h2><strong>At a glance</strong></h2>
<p>Remembering everything until here:</p>
<ol>
<li>OpenGL’s logic is composed by just 3 simple concepts: Primitives, Buffers and Rasterize.</li>
<li>OpenGL ES 2.x works with programmable pipeline, which is synonymous of Shaders.</li>
<li>OpenGL isn&#8217;t aware of the output device, platform or output surface. To make the bridge between OpenGL&#8217;s core and our devices, we must use EGL (or EAGL in iOS).</li>
<li>The textures are crucial and should have a specific pixel format and order to fit within OpenGL.</li>
<li>We start the render process by calling <strong>glDraw*</strong>. The first steps will pass through the Vertex Shader, several checks will conclude if the processed vertex could enter in the Fragment Shader.</li>
<li>The original structure of our meshes should never change. We just create transformations matrices to produce the desired results.</li>
</ol>
<p>First I&#8217;ll talk about 2D graphics, then let&#8217;s see what is the multisampling/antialias filter, personally I don&#8217;t like the cost x benefit of this kind of technique. Many times an application could run nicely without multisampling, but a simple multisampling filter can completely destroy the performance of that application. Anyway, sometimes, it&#8217;s really necessary to make temporary multisampling to produce smooth images.</p>
<p>Later I&#8217;ll talk about textures in deep and its optimization 2 bytes per pixel data format. Also let&#8217;s see PVRTC and how to place it in an OpenGL&#8217;s texture, besides render to an off-screen surface.</p>
<p>And finally I&#8217;ll talk a briefly about some performances gains that I discovered by my self. Some tips and tricks which really help me a lot today and I want to share this with you.</p>
<p>Let&#8217;s go!</p>
<p><br/><a name="2d_graphics"></a></p>
<h2><strong>2D graphics with OpenGL</strong></h2>
<p><a href="#list_contents">top</a><br />
Using 2D graphics with OpenGL is not necessary limited to the use of lines or points primitives. The three primitives (triangles, lines and points) are good to use with 3D and 2D. The first thing about 2D graphics is the Z depth. All our work becomes two dimensions, excluding the Z axis to translations and scales and also excluding X and Y to rotations. It implies that we don&#8217;t need to use the Depth Render Buffer anymore, because everything we draw will be made on the same Z position (usually the 0.0).</p>
<p>A question comes up: &#8220;So how the OpenGL will know which object should be drawn on the front (or top) of the other ones?&#8221; It&#8217;s very simple, by drawing the objects in the order that we want (objects at the background should be drawn first). OpenGL also offers a feature called Polygon Offset, but it&#8217;s more like an adjustment than a real ordering.</p>
<p>OK, now we can think in 2D graphics at three ways:</p>
<ol>
<li>Many squares on the same Z position.</li>
<li>Many points on the same Z position.</li>
<li>All above.</li>
</ol>
<div id="attachment_1372" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/2d_orthographic_example.jpg"><img class="size-full wp-image-1372" title="2d_orthographic_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/2d_orthographic_example.jpg" alt="This is how a 2D graphics looks like for OpenGL using squares." width="600" height="497" /></a><p class="wp-caption-text">This is how a 2D graphics looks like for OpenGL.</p></div>
<div id="attachment_1373" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/2d_scene_example.jpg"><img class="size-full wp-image-1373" title="2d_scene_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/2d_scene_example.jpg" alt="How a 2D scene will appear on the screen." width="600" height="497" /></a><p class="wp-caption-text">How a 2D scene will appear on the screen.</p></div>
<p>You could imagine how easy it&#8217;s to OpenGL, a state machine prepared to work with millions of triangles, to deal with those few triangles. In extreme situations, 2D graphics  works with hundreds of triangles.</p>
<p>With simple words, everything will be textures. So most of our work with 2D will be on the textures. Many people feel compelled to create an API to work with texture Non-POT, that means, work with texture of dimensions like 36 x 18, 51 x 39, etc. My advice here is: &#8220;Don&#8217;t do that!&#8221;. It&#8217;s not a good idea to work with 2D graphics using Non-POT textures. As you&#8217;ve seen in the last image above, it&#8217;s always a good idea work with a imaginary grid, which should be POT, a good choice could be 16&#215;16 or 32&#215;32.</p>
<p>If you are planing to use PVRTC compressed image files, could be good to use a grid of 8&#215;8, because PVRTC minimum size is 8. I don&#8217;t advice make grids less than 8&#215;8, because it&#8217;s unnecessary precise and could increase your work developing, also it compromise your application&#8217;s performance. Grids with 8&#215;8 size are very precise, we&#8217;ll see soon the diferences between the grids and when and how to use them. Let&#8217;s talk a little bit more about the grid.</p>
<p><br/><a name="grid"></a></p>
<h2><strong>The Grid Concept</strong></h2>
<p><a href="#list_contents">top</a><br />
I think this is the most important part in the planing of a 2D application. In a 3D game, for example, to determine where a character can walk we must create a collision detector. This detector could be a box (bounding box) or a mesh (bounding mesh, a simple copy from the original). In both cases, the calculations are very important and expensive. But in a 2D application it&#8217;s very very easy to find the collisions areas if you are using a grid, because you have only a square area using X and Y coordinates!</p>
<p>This is just one reason because the grid is so important. I know you can come up with many other advantages of the grid, like the organization, the precision on the calculations, the precision of the objects on the screen, etc. About 10 year ago (or maybe more) I worked with a tiny program to produce RPG games with 2D graphics. The idea of grid was very well stablished there. The following images show how everything can be fitted into the grid:</p>
<div id="attachment_1374" class="wp-caption alignleft" style="width: 310px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/rpg_maker_example1.jpg"><img class="size-medium wp-image-1374" title="rpg_maker_example1" src="http://db-in.com/blog/wp-content/uploads/2011/04/rpg_maker_example1-300x227.jpg" alt="Grid in the RPG Maker. (click to enlarge)" width="300" height="227" /></a><p class="wp-caption-text">Grid in the RPG Maker. (click to enlarge)</p></div>
<p>I know, I know&#8230; it&#8217;s the &#8220;Fuckwindons&#8221; system, sorry for that&#8230; as I told you, it was a decade ago&#8230; OK, let&#8217;s understand the important features about the grid. You can click on the side image to enlarge it. The first thing I want you notice is the about the overlap of the images. Notice that the left side of the window is reserved to a kind of library. At the top of this library you can see little square images (32&#215;32 in this case). Those squares are reserved to the floor of the scenario (in our OpenGL language, it would be the background). The other images in that library are transparent images (PNG) wich can be placed on top of the floor squares. You can see this difference looking at the big trees placed on the grid.</p>
<p>Now find the &#8220;hero&#8221; on the grid. He&#8217;s at the right side near a tree, it shows a little face with redhead inside a box. This is the second important point about the grid. That hero doesn&#8217;t occupies only one little square on the grid, he could be bigger, but to the grid, the action delimitator represents only one square. Confused? Well, it&#8217;s always a good idea to use only one grid&#8217;s square to deal with the actions, because it let your code much more organized than other approaches. To create areas of actions you can duplicate the action square, just like the exit of the the village on the right top area of the grid in this side image.</p>
<p>I&#8217;m sure you can imagine how easy is to create a control class to deal with the actions in your 2D application and then create view classes referencing the control classes, so you can prepare the view classes to get the collision detection on many squares on the grid. So you have 1 action &#8211; N grid squares detectors. At this way you can take all advantages of the grid and also an incredible boost in your application&#8217;s performance.</p>
<p>By using the grid you can easy define the collision areas which are impossible to the character pass through, like the walls. Another great advantage of using the grid is define &#8220;top areas&#8221;, that means, areas which always will be drawn on top, like the up side of the trees. So if the character pass through these areas, he will be displayed behind.</p>
<p>The following image shows a final scene which uses all these concepts of the grid. Notice how many images can be overlapped by others, pay attention of how the character deals with the action square and its own top areas. And notice the most top effects overlapping everything, like the clouds shadows or the yellow light coming from the sun.</p>
<div id="attachment_1375" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/rpg_maker_example2.jpg"><img class="size-full wp-image-1375" title="rpg_maker_example2" src="http://db-in.com/blog/wp-content/uploads/2011/04/rpg_maker_example2.jpg" alt="RPG Maker final scene." width="600" height="450" /></a><p class="wp-caption-text">RPG Maker final scene.</p></div>
<p>Summarizing the points taken, the grid is really the most important part of planning a 2D application. The grid is not a real thing in OpenGL, so you have to be careful about using this concept, because everything will be imaginary. Well, just to let you know, an extra information: the grid concept is so important that the OpenGL internally works with a grid concept to construct the Fragments.</p>
<p>Great, this is everything about the grid. Now you would say: &#8220;OK, but this is not what I wanted, I want a game with a projection like Diablo, Sin City or even the We Rule does!&#8221;. Oh right, so let&#8217;s make things more complex and bring back the Depth Render Buffer and Cameras to our 2D application.</p>
<p><br/><a name="depth_buffer_2d"></a></p>
<h2><strong>The Depth Render Buffer in 2D</strong></h2>
<p><a href="#list_contents">top</a><br />
Knowing how the 2D graphics goes with OpenGL, we can think in more refined approach, like use the Depth Buffer even in 2D applications.</p>
<div id="attachment_1376" class="wp-caption alignleft" style="width: 320px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/grid_depth_example.jpg"><img class="size-medium wp-image-1376" title="grid_depth_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/grid_depth_example-300x200.jpg" alt="&quot;2D game&quot; using OpenGL with Depth Render Buffer. (click to enlarge)" width="310" height="205" /></a><p class="wp-caption-text">&quot;2D game&quot; using OpenGL with Depth Render Buffer. (click to enlarge)</p></div>
<div id="attachment_1377" class="wp-caption alignright" style="width: 320px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/grid_normal_example.jpg"><img class="size-medium wp-image-1377" title="grid_normal_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/grid_normal_example-300x200.jpg" alt="&quot;2D game&quot; using OpenGL without Depth Render Buffer. (click to enlarge)" width="310" height="205" /></a><p class="wp-caption-text">&quot;2D game&quot; using OpenGL without Depth Render Buffer. (click to enlarge)</p></div>
<p>By clicking on the images above, you can notice the difference between them. Both screenshot are from famous games from iOS, both use OpenGL and both are known as 2D games. Although they use OpenGL ES 1.1, we can understand the concept of Grid + Depth Render Buffer. The game on the left (<em>Gun Bros</em>) makes use of a very small grid, exactly 8&#215;8 pixels, this kind of grid gives to the game a incredible precision to place the objects on the grid, but to improve the user experience you need to make a set of grid squares to deal with the actions, in this case a good choice could be arranging 4 ou 8 grid squares to each action detector. Now the game on the right, it&#8217;s called <em>Inotia</em>, by the way, Inotia is today in its 3th edition. Since the first edition, Inotia always used a big grid, 32&#215;32 pixels. As Gun Bros, Inotia uses OpenGL ES 1.1.</p>
<p>There are many differences between those two grid types (8&#215;8 and 32&#215;32). The first one (8&#215;8) is much more precisely and could seem to be the best choice, but remember that this choice will increase too much your processing. The Inotia game has a light processing demand, something absolutely unimpressive to the iOS&#8217; hardwares. You need to make the best choice to fit within the application you are planning to use.</p>
<p>Now, talking about the Depth Render Buffer, the great thing about it is that you can use 3D models in your application. Look, without Depth Render Buffer you must use only squares, or another primitive geometric form, with textures. By doing this you must create one different texture to each position of your animation, specially to characters animation, obviously a great idea is make use of texture atlas:</p>
<div id="attachment_1378" class="wp-caption alignleft" style="width: 179px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/texture_atlas_example.png"><img class="size-medium wp-image-1378" title="texture_atlas_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/texture_atlas_example-169x300.png" alt="Character texture atlas from Ragnarok." width="169" height="300" /></a><p class="wp-caption-text">Character texture atlas from Ragnarok.</p></div>
<p>The image of Inotia game above has a similar texture altas to each character that appear in the game. Looking at that image you can see that the three character on the screen can turn just to four directions. Now, take another look to the Gun Bros image above.</p>
<p>Notice that the characters can turn to all directions. Why? Well, by using a Depth Render Buffer you are free to use 3D models in your 2D application. So you can rotate, scale and translate the 3D models respecting the grid and the 2D concepts (no Z translate). The result is much much better, but as any improvements, it has a great cost for performance compared to 2D squares, of couse.</p>
<p>But there is another important thing about mixing 3D and 2D concepts: the use of cameras. Instead of creating a single plane right in front of the screen, locking the Z translations, you can create a great plane along the Z axis, place your objects just as in a 3D application and create a camera with orthographic projection. You remember what it is and how to do it, right? (<a href="http://db-in.com/blog/2011/04/cameras-on-opengl-es-2-x/#projections" target="_blank">click here to check the article about cameras</a>).</p>
<p>Before going further into the cameras and Depth Render Buffer with 2D graphics, it&#8217;s important to know that at this point it has no real difference, at the code level, between 2D and 3D graphics since everything comes from your own planning and organization. So the code to use the Depth buffer is the same we saw in the last part (<a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/#render_buffers" target="_blank">click here to see the last tutorial</a>).</p>
<p>Now let&#8217;s talk about the cameras with 2D graphics.</p>
<p><br/><a name="cameras_2d"></a></p>
<h2><strong>The Cameras with 2D</strong></h2>
<p><a href="#list_contents">top</a><br />
OK, I&#8217;m sure you know how to create a camera and an orthographic projection now, as you&#8217;ve seen it at the tutorial about cameras, right? (<a href="http://db-in.com/blog/2011/04/cameras-on-opengl-es-2-x/#projections" target="_blank">click here to check the cameras tutorial</a>). Now a question comes up: &#8220;Where is the best place and approach to use cameras and depth render buffer in the 2D graphics?&#8221;. The following image could help more than 1.000 words:</p>
<div id="attachment_1379" class="wp-caption alignright" style="width: 310px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/cameras_projection_example.jpg"><img class="size-medium wp-image-1379" title="cameras_projection_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/cameras_projection_example-300x240.jpg" alt="Same camera in both projections. (click to enlarge)" width="300" height="240" /></a><p class="wp-caption-text">Same camera in both projections. (click to enlarge)</p></div>
<p>This image shows a scene like Diablo Game style, with a camera in the similar position. You can notice clearly the difference between both projections. Notice the red lines across the picture, with the Orthographic projection those lines are parallels, but with the Perspective projection those lines are not really parallels and can touch at the infinity.</p>
<p>Now focus on the grey scale picture at the bottom right. That is the scene with the objects. As you can see, they are really 3D objects, but with an orthographic projection you can create scenes like Diablo, Sim City, Starcraft and other best sellers, giving a 2D look to your 3D application.</p>
<p>If you take another look at that image of Gun Bros game, you can see that it&#8217;s exactly what they do, there is a camera with orthographic projection and real 3D objects placed on the scene.</p>
<p>So the best approach is to create a camera in your desired position, construct all your scene in a 3D world, set the camera to use orthographic projection and guide your space changes by using the grid concept.</p>
<div id="attachment_1380" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/cameras_grid_example.jpg"><img class="size-full wp-image-1380" title="cameras_grid_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/cameras_grid_example.jpg" alt="The grid concept is very important even with cameras and Depth Render Buffer." width="600" height="447" /></a><p class="wp-caption-text">The grid concept is very important even with cameras and Depth Render Buffer.</p></div>
<p>I have one last advice about this subject, well&#8230; it&#8217;s not really an advice, it&#8217;s more like a warning. Perspective and Orthographic projections are completely different. So the same configuration of focal point, angle of view, near and far produces completely different results. So you need to find a configuration to the Orthographic projection different of that you were using with Perspective projection. Probably if you have a perspective projection which is working, when you change to orthographic projection you won&#8217;t see anything. This is not a bug, it&#8217;s just the differences between perspective and orthographic calculations.</p>
<p>OK, these are the most important concepts about 2D graphics with OpenGL. Let&#8217;s make a little review of them.</p>
<ul>
<li>There are two ways of using 2D graphics with OpenGL: by using or not the Depth Render Buffer.</li>
<li>Without Depth Render Buffer you can construct everything like a rectangle on the screen, forget the Z axis position at this way. Your job here will be laborious on textures. Although, by this way, you can have the best performance with OpenGL.</li>
<li>By using the Depth Render Buffer you can use real 3D objects and probably you will want to use a camera with orthographic projection.</li>
<li>Independent of the way you choose, always use the Grid concept when working on 2D graphics. It&#8217;s the best way to organize your world and optimize your application performance.</li>
</ul>
<p>Now is time to go back into the 3D world and talk a little about the multisampling and antialias filter.</p>
<p><br/><a name="multisampling"></a></p>
<h2><strong>The Multisampling</strong></h2>
<p><a href="#list_contents">top</a><br />
I&#8217;m sure you already noticed that every 3D application, which have a real time render, have their objects&#8217; edges aliased. I&#8217;m talking about 3D world in general, like 3D softwares or games, whatever&#8230; the edges always (I mean, in majority of the cases) looks like it&#8217;s kind aliased. That doesn&#8217;t happen due a lack of well developed techniques to fit that but rather it&#8217;s because our hardwares are not so powerful yet to deal with pixel blend in real time too fast.</p>
<p>So, the first thing I want to say about the Anti-Alias filter is: &#8220;it&#8217;s expensive!&#8221;. In the majority of cases this little problem (aliased edges) doesn&#8217;t matter. But there are some situations that your 3D application needs to looks better. The most simple and common example is the render in 3D softwares. When we hit the render button on our 3D software we expect to see gorgeous images, not jagged edges.</p>
<p>With simple words, the OpenGL primitives get rasterized onto a grid (yes, like our grid concept), and their edges may become deformed. OpenGL ES 2.0 supports something called <em>multisampling</em>. It&#8217;s a technique of Anti-Alias filter which each pixel is divided into few samples, each of these samples are treated like a mini-pixel in the rasterization process. Each sample has its own information about color, depth and stencil. When you ask the OpenGL for the final image on the Frame Buffer, it will resolve and mix all the samples. This process produces more smooth edges. OpenGL ES 2.0 is always configured to multisampling technique, even if the number of samples is equal 1, that means 1 pixel = 1 sample. Looks very simple in theory, but remember that OpenGL doesn&#8217;t know anything about the device&#8217;s surface, consequently, anything about device&#8217;s pixel and color.</p>
<p>The bridge between OpenGL and the device is made by the EGL. So the device color informations, pixel informations and surface informations are responsibility of EGL and consequentially the multisampling could not be implemented only by the OpenGL, it needs a plugin, which is responsibility of the vendors. Each vendors must create a plugin to EGL instructing about the necessary information, by doing this the OpenGL can really resolve the multi samples. The default EGL API offers a multisampling configuration, but commonly the vendors make some changes on it.</p>
<p>In the case of Apple, this plugin is called &#8220;Multisample APPLE&#8221; and it&#8217;s located at the OpenGL Extensions Header (glext.h). To correctly implement the Apple Multisample you need 2 Frame Buffer and 4 Render Buffer! 1 Frame Buffer is the normal provided by OpenGL, the another one is the Multisample Framebuffer. The Render Buffers are Color and Depth.</p>
<p>There are three new functions in the glext.h to deal with Multisample APPLE:</p>
<table width="675">
<tr>
<th>Multisample APPLE</th>
</tr>
<tr>
<td>
<h5><strong>GLvoid glRenderbufferStorageMultisampleAPPLE(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)</strong></h5>
<p><br/></p>
<ul>
<li><strong>target</strong>: The target always will be <strong>GL_RENDERBUFFER</strong>, this is just an internal convention for OpenGL.</li>
<li><strong>samples</strong>: This is the number of samples which the Multisample filter will make.</li>
<li><strong>internalformat</strong>: This specifies what kind of render buffer we want and what color format this temporary image will use. This parameter can be:
<ul>
<li><strong>GL_RGBA4</strong>, <strong>GL_RGB5_A1</strong>, <strong>GL_RGB56</strong>, <strong>GL_RGB8_OES</strong> or <strong>GL_RGBA8_OES</strong> to a render buffer with final colors.</li>
<li><strong>GL_DEPTH_COMPONENT16</strong> or <strong>GL_DEPTH_COMPONENT24_OES</strong> to a render buffer with Z depth.</li>
</ul>
</li>
<li><strong>width</strong>: The final width of a render buffer.</li>
<li><strong>height</strong>: The final height of a render buffer.</li>
</ul>
</td>
</tr>
<tr>
<td>
<h5><strong>GLvoid glResolveMultisampleFramebufferAPPLE(void)</strong></h5>
<p><br/></p>
<ul>
<li>This function doesn&#8217;t need any parameter. This function will just resolve the last two frame buffer bound to <strong>GL_DRAW_FRAMEBUFFER_APPLE</strong> and <strong>GL_READ_FRAMEBUFFER_APPLE</strong>, respectively.</li>
</ul>
</td>
</tr>
<tr>
<td>
<h5><strong>GLvoid glDiscardFramebufferEXT(GLenum target, GLsizei numAttachments, const GLenum *attachments)</strong></h5>
<p><br/></p>
<ul>
<li><strong>target</strong>: Usually the target will be <strong>GL_READ_FRAMEBUFFER_APPLE</strong>.</li>
<li><strong>numAttachments</strong>: The number of Render Buffer attachments to discard in the target Frame Buffer. Usually this will be 2, to discard the Color and Depth Render Buffers.</li>
<li><strong>attachments</strong>: A pointer to an array containing the type of Render Buffer to discard. Usually that array will be <strong>{GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT}</strong>.</li>
</ul>
</td>
</tr>
</table>
<p>Before checking the code, let&#8217;s understand a little bit more about these new functions. The first function (<strong>glRenderbufferStorageMultisampleAPPLE</strong>) is intended to replace that function that set the properties to the Render Buffer, the <strong>glRenderbufferStorage</strong>. The big new in this function is the number of samples, it will define how many samples each pixel will has.</p>
<p>The second one (<strong>glResolveMultisampleFramebufferAPPLE</strong>) is used to take the informations from the original frame buffer, place it in the Multisample Frame Buffer, resolve the samples of each pixel and then draw the resulting image to our original Frame Buffer again. In simple words, this is the core of Multisample APPLE, this is the function which makes all the job.</p>
<p>The last one (<strong>glDiscardFramebufferEXT</strong>) is another clearing function. As you imagine, after the <strong>glResolveMultisampleFramebufferAPPLE</strong> makes all the processing, the Multisample Frame Buffer will be with many informations in it, so it&#8217;s time to clear all that memory. To do that, we call the <strong>glDiscardFramebufferEXT</strong> informing what we want to clear from where.</p>
<p>Now, here is the full code to use Multisample APPLE:</p>
<table width="675">
<tbody>
<tr>
<th>Multisample Framebuffer APPLE</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// EAGL
// Assume that _eaglLayer is a CAEAGLLayer data type and was already defined.
// Assume that _context is an EAGLContext data type and was already defined.

// Dimensions
int _width, _height;

// Normal Buffers
GLuint _frameBuffer, _colorBuffer, _depthBuffer;

// Multisample Buffers
GLuint _msaaFrameBuffer, _msaaColorBuffer, _msaaDepthBuffer;
int _sample = 4; // This represents the number of samples.

// Normal Frame Buffer
glGenFramebuffers(1, &amp;_frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);

// Normal Color Render Buffer
glGenRenderbuffers(1, &amp;_colorBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _colorBuffer);
[_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _colorBuffer);

// Retrieves the width and height to the EAGL Layer, just necessary if the width and height was not informed.
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &amp; _width);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &amp; _height);

// Normal Depth Render Buffer
glGenRenderbuffers(1, &amp;_depthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _depthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, _width, _height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthBuffer);
glEnable(GL_DEPTH_TEST);

// Multisample Frame Buffer
glGenFramebuffers(1, &amp;_msaaFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, _msaaFrameBuffer);

// Multisample  Color Render Buffer
glGenRenderbuffers(1, &amp;_msaaColorBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _msaaColorBuffer);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, _samples, GL_RGBA8_OES, _width, _height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _msaaColorBuffer);

// Multisample Depth Render Buffer
glGenRenderbuffers(1, &amp;_msaaDepthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _msaaDepthBuffer);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, _samples, GL_DEPTH_COMPONENT16, _width, _height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _msaaDepthBuffer);
.</pre>
<p>Yes, many lines to a basic configuration. Once all those 6 buffers have been defined, we also need to make the render by a different approach. Here is the necessary code:</p>
<table width="675">
<tbody>
<tr>
<th>Rendering with Multisample APPLE</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
//-------------------------
//	Pre-Render
//-------------------------
// Clears normal Frame Buffer
glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Clears multisample Frame Buffer
glBindFramebuffer(GL_FRAMEBUFFER, _msaaFrameBuffer);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//-------------------------
//	Drawing
//-------------------------
//...
// Draw all your content.
//...

//-------------------------
//	Render
//-------------------------
// Resolving Multisample Frame Buffer.
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, _frameBuffer);
glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, _msaaFrameBuffer);
glResolveMultisampleFramebufferAPPLE();

// Apple (and the khronos group) encourages you to discard
// render buffer contents whenever is possible.
GLenum attachments[] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT};
glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments);

// Presents the final result at the screen.
glBindRenderbuffer(GL_RENDERBUFFER, _colorBuffer);
[_context presentRenderbuffer:GL_RENDERBUFFER];
.</pre>
<p>If you want to remember something about the EAGL (the EGL implementation by Apple), check it here: <a href="http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/" target="_blank">article about EGL and EAGL</a>. OpenGL also offers some configurations to multisampling, <strong>glSampleCoverage</strong> and few configurations with <strong>glEnable</strong>. I&#8217;ll not talk in deep about these configurations here, because I don&#8217;t believe multisampling is a good thing to spend our time on. As I told you, the result is not a big deal, it&#8217;s just a little bit more refined. In my opinion, the performance cost is too much compared to the final result:</p>
<div id="attachment_1392" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/multisample_result_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/multisample_result_example.jpg" alt="Same 3D model rendered without and with Anti-Alias filter." title="multisample_result_example" width="600" height="470" class="size-full wp-image-1392" /></a><p class="wp-caption-text">Same 3D model rendered without and with Anti-Alias filter.</p></div>
<p>OK, now it&#8217;s time to talk more about the textures in OpenGL.</p>
<p><br/><a name="more_texture"></a></p>
<h2><strong>More About Textures</strong></h2>
<p><a href="#list_contents">top</a><br />
We already know many things about textures from the second part of this serie (<a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/#textures" target="_blank">All About OpenGL ES 2.x &#8211; Textures</a>).  First, let&#8217;s talk about the optimized types. It&#8217;s a great boost on our application&#8217;s performance and is very easy to implement. I&#8217;m talking about the bytes per pixel of our images.</p>
<p><br/><a name="bpp"></a></p>
<h2>Bytes per Pixel</h2>
<p><a href="#list_contents">top</a><br />
Usually the images has 4 bytes per pixel, one byte for each channel, RGBA. Some images without alpha, like JPG file format, has only 3 bytes per pixel (RGB). Each byte could be represented by an hexadecimal color in the format 0xFF, it&#8217;s called hexadecimal because each decimal house has the range 0 &#8211; F (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F), so when you make a combination of two hexadecimal numbers you get one byte (16 x 16 = 256). As a convention, we describe a hexadecimal color as 0xFFFFFF, where each set of two number represent one color channel (RGB). For images with alpha channel, like PNG format, we are used to say 0xFFFFFF + 0xFF, that means (RGB + A).</p>
<p>My next article will be about binary programming, so I&#8217;ll not talk in deep about binaries here. All that we need for now is to know that 1 byte = 1 color channel. The OpenGL can also work with more compressed format, which uses only 2 bytes per pixel. What that means? It means that each byte will store two color channels, including alpha. In very simple words, let&#8217;s reduce the color&#8217;s range of the image.</p>
<p>The OpenGL offers to us 3 compressed data types: <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong>, <strong>GL_UNSIGNED_SHORT_5_5_5_1</strong>, <strong>GL_UNSIGNED_SHORT_5_6_5</strong>. The first two should be used when you have alpha channel and the last one it&#8217;s only for situations without alpha. These 3 names tell us something about the pixel data. The numbers at the right instruct us about the number of bits (not bytes) that must be used in each channel (RGBA). Oh, and just to make it clear, each byte is composed by 8 bits. So in the first case 4 bits per channel with a total of 2 bytes per pixel. The second one, 5 bits to RGB channels and 1 bit to alpha with a total of 2 bytes per pixel. And the last one, 5 bits to R, 6 bits to G and 5 bits to B with a total of 2 bytes per pixel.</p>
<p>Here I want to make a warning: The type <strong>GL_UNSIGNED_SHORT_5_5_5_1</strong> is not really useful, because only 1 bit to alpha is the same as give it a Boolean data type, I mean, 1 bit to alpha means visible YES or NOT, just it. So this type is not really useful, it has less bits on Green channel than <strong>GL_UNSIGNED_SHORT_5_6_5</strong> and even can&#8217;t produce real transparent effects like <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong>. So if you need the alpha channel, make use of <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong>, if not, make use of <strong>GL_UNSIGNED_SHORT_5_6_5</strong>.</p>
<p>A little thing to know about the <strong>GL_UNSIGNED_SHORT_5_6_5</strong>. As the human eye has more sensibility to the green colors, the channel with more bits is exactly the Green channel. At this way, even with a less color range, the resulting image to the final user will not seem to be that different.</p>
<p>Now let&#8217;s take a look at the difference between both compressions.<br />
<div id="attachment_1393" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/texture_compression_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/texture_compression_example.jpg" alt="OpenGL optimized 2 bytes per pixel (bpp) data types." title="texture_compression_example" width="600" height="470" class="size-full wp-image-1393" /></a><p class="wp-caption-text">OpenGL optimized 2 bytes per pixel (bpp) data types.</p></div></p>
<p>As you saw, by using <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong> could really be ugly in some situations. But the <strong>GL_UNSIGNED_SHORT_5_6_5</strong> looks very nice. Why? I&#8217;ll explain in details at the next article about binaries, but in very simple words, by using <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong> we have only 16 tonalities for each channel, including 16 tonalities to alpha. But with <strong>GL_UNSIGNED_SHORT_5_6_5</strong> we have 32 tonalities to Red and Blue and 96 tonalities of Green spectrum. It still far from the human eye&#8217;s capacity, but remember that by using these optimizations we reduce 2 bytes per pixel in all our images, this represents much more performance to our renders.</p>
<p>Now it&#8217;s time to learn how to convert our traditional images to these formats. Normally, when you extract the binary informations from an image you get it pixel by pixel, so probably each pixel will be composed by an &#8220;unsigned int&#8221; data type, which has 4 bytes. Each programming language provides a method(s) to extract the binary information from the pixels. Once you have your array of pixel data (array of unsigned int) you can use the following code to convert that data to the <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong> or <strong>GL_UNSIGNED_SHORT_5_6_5</strong>.</p>
<table width="675">
<tbody>
<tr>
<th>Converting 4bpp to 2bpp</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
typedef enum
{
	ColorFormatRGB565,
	ColorFormatRGBA4444,
} ColorFormat;

static void optimizePixelData(ColorFormat color, int pixelDataLength, void *pixelData)
{
	int i;
	int length = pixelDataLength;

	void *newData;

	// Pointer to pixel information of 32 bits (R8 + G8 + B8 + A8).
	// 4 bytes per pixel.
	unsigned int *inPixel32;

	// Pointer to new pixel information of 16 bits (R5 + G6 + B5)
	// or (R4 + G4 + B4 + A4).
	// 2 bytes per pixel.
	unsigned short *outPixel16;

	newData = malloc(length * sizeof(unsigned short));
	inPixel32 = (unsigned int *)pixelData;
	outPixel16 = (unsigned short *)newData;

	if(color == ColorFormatRGB565)
	{
		// Using pointer arithmetic, move the pointer over the original data.
		for(i = 0; i < length; ++i, ++inPixel32)
		{
			// Makes the convertion, ignoring the alpha channel, as following:
			// 1 -	Isolates the Red channel, discards 3 bits (8 - 3), then pushes to the final position.
			// 2 -	Isolates the Green channel, discards 2 bits (8 - 2), then pushes to the final position.
			// 3 -	Isolates the Blue channel, discards 3 bits (8 - 3), then pushes to the final position.
			*outPixel16++ = (((( *inPixel32 >> 0 ) &#038; 0xFF ) >> 3 ) << 11 ) |
							(((( *inPixel32 >> 8 ) &#038; 0xFF ) >> 2 ) << 5 ) |
							(((( *inPixel32 >> 16 ) &#038; 0xFF ) >> 3 ) << 0 );
		}
	}
	else if(color == ColorFormatRGBA4444)
	{
		// Using pointer arithmetic, move the pointer over the original data.
		for(i = 0; i < length; ++i, ++inPixel32)
		{
			// Makes the convertion, as following:
			// 1 -	Isolates the Red channel, discards 4 bits (8 - 4), then pushes to the final position.
			// 2 -	Isolates the Green channel, discards 4 bits (8 - 4), then pushes to the final position.
			// 3 -	Isolates the Blue channel, discards 4 bits (8 - 4), then pushes to the final position.
			// 4 -	Isolates the Alpha channel, discards 4 bits (8 - 4), then pushes to the final position.
			*outPixel16++ = (((( *inPixel32 >> 0 ) &#038; 0xFF ) >> 4 ) << 12 ) |
							(((( *inPixel32 >> 8 ) &#038; 0xFF ) >> 4 ) << 8 ) |
							(((( *inPixel32 >> 16 ) &#038; 0xFF ) >> 4 ) << 4 ) |
							(((( *inPixel32 >> 24 ) &#038; 0xFF ) >> 4 ) << 0 );
		}
	}

	free(pixelData);

	pixelData = newData;
}
.</pre>
<p>The routine above assumes the channel order as RGBA. Although is not common, your image could have the pixels composed by another channel order, like ARGB or BGR. In these cases you must change the routine above or change the channel order at when extracting binary informations from each pixel. Another important thing is about the binary order. I don't want to confuse your mind if you don't know too much about binaries, but just as an advice: you probably will get the pixel data in little endian format, the traditional, but if your programming language get the binary informations as a big endian, the above routine will not work properly, so make sure your pixel data is in little endian format.</p>
<p><br/><a name="pvrtc"></a></p>
<h2>PVRTC</h2>
<p><a href="#list_contents">top</a><br />
I sure you've heard about the texture compression format PVRTC, if you already feel confortable about this topic, just skip to the next one. PVRTC is a binary format created by "<a href="http://www.imgtec.com/" target="_blank">Imagination Technology</a>", also called "<em>Imgtec</em>". This format uses the channel order as ARGB instead the traditional RGBA. To say the truth, its optimization is not about the file's size, if we look only to the size, any JPG is more compressed or even a PNG can be lighter. The PVRTC is optimized about its processing, its pixels can be already in the format 2 bytes per pixel (2bpp) or 4 bytes per pixel (4bpp). The data  inside PVRTC is OpenGL friendly and also can store Mipmap levels. So, could it be a good idea to always make use of PVRTC? Well, not exactly... let's see why.</p>
<p>The PVRTC format is not supported by default in OpenGL ES 2.0, there are informations that OpenGL ES 2.1 will come with native support to PVRTC textures, but what we have for now is just the OpenGL ES 2.0. To use PVRTC on it, just as the Multisampling, you need a vendors plug-in. In the case of Apple, this plugin has four new constant values. OpenGL provides a function to upload pixel data from the compressed formats, like PVRTC:</p>
<table width="675">
<tr>
<th>Uploading PVRTC</th>
</tr>
<tr>
<td>
<h5><strong>GLvoid glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data)</strong></h5>
<p><br/></p>
<ul>
<li><strong>target</strong>: The target always will be GL_TEXTURE_2D, this is just an internal convention for OpenGL.</li>
<li><strong>level</strong>: The number of Mipmap levels in the file.</li>
<li><strong>internalformat</strong>: The format of the PVRTC. This parameter can be:
<ul>
<li><strong>GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG</strong>: Files using the 4bpp without the alpha channel.</li>
<li><strong>GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG</strong>: Files using 4bpp and the alpha channel.</li>
<li><strong>GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG</strong>: Files using 2bpp without the alpha channel.</li>
<li><strong>GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG</strong>: Files using 2bpp and the alpha channel.</li>
</ul>
</li>
<li><strong>width</strong>: The width of the image.</li>
<li><strong>height</strong>: The height of the image.</li>
<li><strong>border</strong>: This parameter is ignored in OpenGL ES. Always use the value 0. This is just an internal constant to conserve the compatibly with the desktop versions.</li>
<li><strong>imageSize</strong>: The number of the bytes in the binary data.</li>
<li><strong>data</strong>: The binary data for the image.</li>
</td>
</tr>
</table>
<p>As you can imagine, the data format <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong> or <strong>GL_UNSIGNED_SHORT_5_6_5</strong> is chosen based on the file format, RGB or RGBA with 2bpp or 4bpp, depends on.</p>
<p>To generate the PVRTC you have many options. The two most common is the Imgtec Tools or the Apple's Texture Tool. Here you can find the <a href="http://www.imgtec.com/powervr/insider/powervr-utilities.asp" target="_blank">Imgtec Tools</a>.  The Apple tool comes with iPhone SDK, it's located at the path "<em><Xcode Folder>/iPhoneOS.platform/Developer/usr/bin</em>" the name is "<em>texturetool</em>", you can find all informations about it at <a href="http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/TextureTool/TextureTool.html" target="_blank">Apple Texture Tool</a>.</p>
<p>I'll explain how to use the Apple tool here. Follow these steps:</p>
<ul>
<li>Open the Terminal.app (usually it is in /Applications/Utilities/Terminal.app)</li>
<li>Click on <strong>texturetool</strong> in Finder and drag &#038; drop it on Terminal window. Well, you also can write the full path "<em><Xcode Folder>/iPhoneOS.platform/Developer/usr/bin/texturetool</em>", I preffer drag &#038; drop.</li>
<li>Write in front of texture tool path: " -e PVRTC --channel-weighting-linear --bits-per-pixel-2 -o "</li>
<li>Now you should write the output path, again, I prefer drag &#038; drop the file from the Finder to the Terminal window and rename its extension. The extension really doesn't matter, but my advice is to write something that let you identify the file format, like pvrl2 for Channel Weighting Linear with 2bpp.</li>
<li>Finally, add an space and write the input file. Guess... I prefer to drag &#038; drop from the Finder. The input files must be PNG or JPG files only.</li>
<li>Hit "Enter"</li>
</ul>
<table width="675">
<tbody>
<tr>
<th>Terminal Script to Generate PVRTC with Texturetool</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/texturetool
 -e PVRTC --channel-weighting-linear --bits-per-pixel-2 -o
/Texture/Output/Path/Texture.pvrl2 /Texture/Intput/Path/Texture.jpg
.</pre>
<p>Good, now you have a PVRTC file. The problem with the Apple tool is that it doesn't generate the traditional PVRTC binary header. It's composed by 52 bytes at the beginning of the file and gives instructions about the height and width of the image, number of Mipmaps on it, bpp, channels order, alpha, etc. In the traditional PVRTC files, this is the header format:</p>
<ul>
<li><strong>unsigned int (4 bytes)</strong>: Header Length in Bytes. Old PVRTC has a header of 44 bytes instead 52.</li>
<li><strong>unsigned int (4 bytes)</strong>: Height of the image. PVRTC only accepts squared images (width = height) and POT sizes (Power of Two)</li>
<li><strong>unsigned int (4 bytes)</strong>: Width of the image. PVRTC only accepts squared images (width = height) and POT sizes (Power of Two).</li>
<li><strong>unsigned int (4 bytes)</strong>: Number of Mipmaps.</li>
<li><strong>unsigned int (4 bytes)</strong>: Flags.</li>
<li><strong>unsigned int (4 bytes)</strong>: Data Length of the image.</li>
<li><strong>unsigned int (4 bytes)</strong>: The bpp.</li>
<li><strong>unsigned int (4 bytes)</strong>: Bitmask Red.</li>
<li><strong>unsigned int (4 bytes)</strong>: Bitmask Green.</li>
<li><strong>unsigned int (4 bytes)</strong>: Bitmask Blue.</li>
<li><strong>unsigned int (4 bytes)</strong>: Bitmask Alpha.</li>
<li><strong>unsigned int (4 bytes)</strong>: The PVR Tag.</li>
<li><strong>unsigned int (4 bytes)</strong>: Number of Surfaces.</li>
</ul>
<p>But, using the Apple Texture Tool we don't have the file header and without that header we can't find neither the width nor height of the file from our code. So to use PVRTC from Apple tool you should know about bpp, width, height and alpha. Kind of annoying, no?</p>
<p>Well... I have good news for you. I found a way, a trick, to extract informations from the PVRTC generated by Apple tool. This trick works fine, but it can't identify informations about the Mipmap, but this is not a problem, because Apple tool doesn't generate Mipmaps anyway.</p>
<table width="675">
<tbody>
<tr>
<th>Extracting Infos From PVRTC Without Header</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// Supposing the bpp of the image is 4, calculates its squared size.
float size = sqrtf([data length] * 8 / 4);

// Checks if the bpp is really 4 by comparing the rest of division by 8,
// the minimum size of PVRTC, if the rest is zero then this image really
// has 4 bpp, otherwise, it has 2 bpp.
bpp = ((int)size % 8 == 0) ? 4 : 2;

// Knowing the bpp, calculates the width and height
// based on the data size.
width = sqrtf([data length] * 8 / bpp);
height = sqrtf([data length] * 8 / bpp);
length = [data length];
.</pre>
<p>The PVRTC files made from Texturetool doesn't have any header, so its image data starts in the first byte of the file. And what about the alpha? Could you ask. Well, the alpha will be more dependent of your EAGL context configuration. If you are using RGBA8, assume the alpha exist and use the <strong>GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG</strong> or <strong>GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG</strong>, based on the informations that you extract from the code above. If your EAGL context uses RGB565, so assume <strong>GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG</strong> or <strong>GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG</strong>.</p>
<p>Now to use your PVRTC on OpenGL ES 2.0, it's very simple, you don't need to change almost anything, you will create your texture normally, just replace the call to <strong>glTexImage2D</strong> by <strong>glCompressedTexImage2D</strong> function.</p>
<table width="675">
<tbody>
<tr>
<th>Uploading PVRTC to OpenGL</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// format = one of the GL_COMPRESSED_RGB* constants.
// width = width extract from the code above.
// height = height extract from the code above.
// length = length extract from the code above.
// data = the array of pixel data loaded via NSData or any other binary class.

// You probably will use NSData to load the PVRTC file.
// By using "dataWithContentsOfFile" or similar NSData methods.

glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, length, data);
.</pre>
<p>Well done, this is all about PVRTC. But my last advice about this topic is, always avoid to use PVRTC. The cost X benefit is not so good. Remember you just need to parse an image file once to OpenGL, so PVRTC doesn't offers a great optimization.</p>
<p><br/><a name="off-screen"></a></p>
<h2><strong>The Off-Screen Render</strong></h2>
<p>Until now we've just talked about render to the screen, "on the screen", "on the device", but we also have another surface to render, the off-screen surfaces. You remember it from the EGL article, right? (<a href="http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/" target="_blank">EGL and EAGL article</a>).</p>
<p>What is the utility of  an off-screen render? We can take a snapshot from the current frame and save it as an image file, but the most important thing about off-screen renders is to create an OpenGL texture with the current frame and then use this new internal texture to make a reflection map, a real-time reflection. I'll not talk about the reflections here, this subject is more appropriated to a tutorial specific about the shaders and lights, let's focus only about how to render to an off-screen surface. We'll need to know a new function:</p>
<table width="675">
<tr>
<th>Off-Screen Render</th>
</tr>
<tr>
<td>
<h5><strong>GLvoid glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)</strong></h5>
<p><br/></p>
<ul>
<li><strong>target</strong>: The target always will be <strong>GL_FRAMEBUFFER</strong>, this is just an internal convention for OpenGL.</li>
<li><strong>attachment</strong>: This specifies what kind of render buffer we want to render for This parameter can be:
<ul>
<li><strong>GL_COLOR_ATTACHMENT0</strong> to the Color Render Buffer.</li>
<li><strong>GL_DEPTH_ATTACHMENT</strong> to a Depth Render Buffer.</li>
</ul>
</li>
<li><strong>textarget</strong>: The type of texture, to 2D texture this parameter always will be <strong>GL_TEXTURE_2D</strong>. If your texture is a 3D texture (Cube Map), you can use one of its faces as this parameter: GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y or GL_TEXTURE_CUBE_MAP_NEGATIVE_Z.</li>
<li><strong>texture</strong>: The texture object target.</li>
<li><strong>level</strong>: Specifies the Mipmap level for the texture.</li>
</ul>
</td>
</tr>
</table>
<p>To use this function we need to first create the target texture. We can do it just as before (<a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/#textures" target="_blank">check out the texture functions here</a>). Then we call <strong>glFramebufferTexture2D</strong> and proceed normally with our render routine. After drawing something (glDraw* callings) that texture object will be filled and you can use it for anything you want. Here is an example:</p>
<table width="675">
<tbody>
<tr>
<th>Drawing to Off-Screen Surface</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// Create and bind the Frame Buffer.
// Create and attach the Render Buffers, except the render buffer which will
// receive the texture as attachment.

GLuint _texture;
glGenTextures(1, &#038;_texture);
glBindTexture(GL_TEXTURE_2D, _texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,  textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture, 0);
.</pre>
<p>Differently than creating a texture for a pixel data, at this time you set the texture data to <strong>NULL</strong>. Because they will be filled up dynamically later on. If you intend to use the output image as a texture for another draw, remember first to draw the objects that will fill the output texture.</p>
<p>Well, as any Frame Buffer operation, it's a good idea to check <strong>glCheckFramebufferStatus</strong> to see if everything was attached OK. A new question comes up: "If I want to save the resulting texture to a file, how could I retrieve the pixel data from the texture?", OpenGL is a good mother, she gives us this function:</p>
<table width="675">
<tr>
<th>Getting Pixel Data from Texture</th>
</tr>
<tr>
<td>
<h5><strong>GLvoid glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels)</strong></h5>
<p><br/></p>
<ul>
<li><strong>x</strong>: The X position to start getting pixel data. Remember that the pixel order in the OpenGL starts in the lower left corner and goes to up right corner.</li>
<li><strong>y</strong>: The Y position to start getting pixel data.  Remember that the pixel order in the OpenGL starts in the lower left corner and goes to up right corner.</li>
<li><strong>width</strong>: The Width to get the pixel data. Can't be greater than the original render buffer.</li>
<li><strong>height</strong>: The Width to get the pixel data. Can't be greater than the original render buffer.</li>
<li><strong>format</strong>: Always use <strong>GL_RGB</strong>, there are other formats, but it is implementation dependent and can vary depending on your vendors. For example, to get Alpha information, it depends on your EGL context configuration, which is vendors dependent.</li>
<li><strong>type</strong>: Always use <strong>GL_UNSIGNED_BYTE,</strong>, there are other formats, but it is implementation dependent and can vary depending on your vendors.</li>
<li><strong>pixels</strong>: A pointer to return the pixel data.</li>
</ul>
</td>
</tr>
</table>
<p>As you've saw, the function is very easy, you can call it any time you want. Just remember a very important thing: "OpenGL Pixel Order!", it starts in the lower left corner and goes to the up right corner. To a traditional image file, that means the image is flipped vertically, so if you want to save to a file, take care with it.</p>
<p>Now you must to do the invert path you are used to when import a texture. Now you have the pixel data and want to construct a file. Fortunately many languages offers a simple way to construct an imagem from pixel data. For example, with Cocoa Touch (Objective-C), we can use NSData + UIImage, at this way:</p>
<table width="675">
<tbody>
<tr>
<th>Drawing to Off-Screen Surface</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// The pixelData variable is a "void *" initialized with memory allocated.

glReadPixels (0, 0, 256, 256, GL_RGB, GL_UNSIGNED_BYTE, pixelData);
UIImage *image = [UIImage imageWithData:[NSData dataWithBytes:pixelData length:256 * 256]];

// Now you can save the image as JPG or PNG.
[UIImageJPEGRepresentation(image, 100) writeToFile:@"A path to save the file" atomically:YES];
.</pre>
<p>Just a little question, <strong> glReadPixels </strong> will read from where? OpenGL State Machine, do you remember? <strong> glReadPixels </strong> will read the pixels from the "last Frame Buffer bound".</p>
<p>Now it's time to talk more about optimization.</p>
<p><br/><a name="tips_tricks"></a></p>
<h2><strong>Tips and Tricks</strong></h2>
<p><a href="#list_contents">top</a><br />
I want to talk now about some tips and tricks to boost your application. I don't want to talk about little optimizations which make you gain 0.001 secs, no. I want to talk about real optimizations. That ones which can boost 0.5 secs or even increase your render frame rate.</p>
<p><br/><a name="cache"></a></p>
<h3>The Cache</h3>
<p><a href="#list_contents">top</a><br />
This is very important, I really love it, I'm used to use it on everything, it's great! Imagine this situation, the user touch the objects on the screen to make a rotation. Now the user touch another object, but the first doesn't change anything. So it would be great to make the first object's transformation matrix a cached matrix, instead to recalculating the first object's matrix at each frame.</p>
<p>The cached concept extends even to other areas, like cameras, lights and quaternions. Instead to recalculate something at each frame, use a little BOOL data type to check if a matrix or even a value is cached or not. The following pseudo-code shows how is simple to work with cache concept.</p>
<table width="675">
<tbody>
<tr>
<th>Cache Concept</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
bool _matrixCached;
float _changeValue;
float *_matrix;

float *matrix(void)
{
    if (!_matrixCached)
    {
        // Do changes into _matrix.

        _matrixCached = TRUE;
    }

    return _matrix;
}

void setChange(float value)
{
    // Change the _changeValue which will affect the matrix.

    _matrixCached = FALSE;
}
.</pre>
<p><br/><a name="store_values"></a></p>
<h3>Store the Values</h3>
<p><a href="#list_contents">top</a><br />
We are used to change the matrix (or the quaternion) every time that occurs transformation. For example, if our code make the changes: translate X - we change the resulting matrix, translate Y - we change the matrix, rotate Z - change the matrix and scale Y - change the matrix. Some 3D engines and people do not even hold on a value to those transformations, so if the code need to retrieve those values, they extract the values directly from the resulting matrix. But this is not the best approach. A great optimization could be reached if we store the values independently, like translations X,Y and Z, rotations X,Y and Z and scales X,Y and Z.</p>
<p>By storing the values you can make a single change into the resulting matrix, making the calculations once per frame instead of making the calculus at every transformation. The following pseudo-code can help you to understand the Store concept better:</p>
<table width="675">
<tbody>
<tr>
<th>Store Concept</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
float _x;
float _y;
float _z;

float x(void) { return _x; }
float setX(float value)
{
    _x = value;
}

float y(void) { return _y; }
float setY(float value)
{
    _y = value;
}

float z(void) { return _z; }
float setZ(float value)
{
    _z = value;
}

float *matrix(void)
{
    // This function will be called once per frame.
    // Make the changes to the matrix based on _x, _y and _z.
}
.</pre>
<p><br/><a name="c_fastest"></a></p>
<h3>C is always the fast language</h3>
<p><a href="#list_contents">top</a><br />
This tip is just something to remember. You probably know that, but it's very important to reinforce. C is always the fastest language. No other language can be faster than C. It's the most basic language and it's the great father of almost all computer languages. So always try to use C in the most critical parts of the code. Specially for render routines.</p>
<p>String comparisons with C is around 4x faster than Objective-C comparisons. So if you need to check some string value at the render time, prefer to convert it from NSString to C string (char *) and make the comparison, even if you need re-convert from C string to NSString again, even in these cases C string is faster. To compare C strings you know, just use <strong>if (strcmp(string1, string2) == 0)</strong>.</p>
<p>Specially for numbers, always use basic C data types (<strong>float</strong>, <strong>int</strong>, <strong>short</strong>, <strong>char</strong> and their unsigned versions). Besides, avoid at maximum value that use 64 bits, like <strong>long</strong> or <strong>double</strong> data type. Remember that OpenGL ES doesn't support, by default, 64 bits data types.</p>
<p><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p><a href="#list_contents">top</a><br />
OK dudes, we're at the end of our objective with this serie. I'm sure now you know a lot of things about OpenGL and 3D world. I have covered almost all about the OpenGL in those 3 tutorials of this serie. I hope you learned all the concepts about the subjects covered in these tutorials.</p>
<p>Now, as we are used, let's remember everything:</p>
<ul>
<li>2D graphics with OpenGL can be done by two ways: with or without Depth Render Buffer.</li>
<li>When using Depth Render Buffer, it could also be good to make use of a camera with Orthographic projection.</li>
<li>Independent of the way you choose, always use the Grid concept with 2D graphics.</li>
<li>The Multisampling filter is a plug-in that depends the vendors implementation. Multisampling always has a big cost on performance, use it only in special situations.</li>
<li>Always try to optimize your textures to a 2bpp data format.</li>
<li>You can use PVRTC in your application to save some time when creating an OpenGL texture from a file.</li>
<li>Always try to use the Cache concept when working with matrices.</li>
<li>Make use of the Store Values concept to save CPU processing.</li>
<li>Prefer basic C language on the critical render routines.</li>
</ul>
<p>Well, you know, if you have some doubt, just ask me, let a comment bellow and if I can help I'll be glad.</p>
<p><br/></p>
<h2><strong>From here and beyond</strong></h2>
<p>Well, and now? Is this all? No. It will never be enough! The points and lines deserve a special article. With points in can make particles and some cool effects. As I told at the beginning of this tutorial, you can use points with 2D graphics instead squares, in case of no Depth Render Buffer.</p>
<p>And about the shaders? In deep? The Programmable Pipeline gives us a whole new world of programming. We should talk about the Surface Normals VS Vertex Normals, about the tangent space, the normal bump effect, the reflection and refraction effect. To say the truth... I think we need a new serie of tutorial called "All About OpenGL Shaders". Well, this could be my next serie.</p>
<p>But I want to hear from you, tell me here or on Twitter what you want to know more about.<br />
Just Tweet me:<br />
<a href="http://twitter.com/share" class="twitter-share-button" data-text="Hey @dineybomfim talk more about: " data-count="none" data-url="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></p>
<p>Thanks again for reading.<br />
See you in the next tutorial!</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/05/all-about-opengl-es-2-x-part-33/feed/</wfw:commentRss>
		<slash:comments>20</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>NinevehGL Features</title>
		<link>http://db-in.com/blog/2011/04/ninevehgl-features/</link>
		<comments>http://db-in.com/blog/2011/04/ninevehgl-features/#comments</comments>
		<pubDate>Tue, 26 Apr 2011 15:12:36 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Frameworks]]></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[NinevehGL]]></category>
		<category><![CDATA[OpenGL ES]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1381</guid>
		<description><![CDATA[The time for the NinevehGL is coming. Check now its features and what you could expect from.]]></description>
			<content:encoded><![CDATA[<p><a href="http://db-in.com/blog/wp-content/uploads/2011/04/ngl_feather.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/ngl_feather.png" alt="" title="ngl_feather" width="130" height="200" class="alignleft size-full wp-image-1390" /></a>Hello everyone!</p>
<p>Today I want to talk about the NinevehGL. Talk more about the features and about what it can offer to us. NinevehGL is almost done, I want to be as fast as possible, but I don&#8217;t want to launch it without everything seems great: the documentation, the tutorials, the official website and obviously, the NinevehGL itself.</p>
<p>Soon I&#8217;ll start posting videos and many divulgations about it, but right now in this article let&#8217;s see some images taken directly from the NinevehGL running.</p>
<p>Let&#8217;s start!</p>
<p><span id="more-1381"></span><br />
<br/></p>
<h2><strong>At a glance</strong></h2>
<p>The NinevehGL is a 3D engine fully made with the most pure Objective-C, right on top of Cocoa Touch Framework. So at the first moment, the NinevehGL is a 3D engine only for iOS. I intend to port NinevehGL to MacOSX (desktops with Obj-C) and also for ActionScript 3.0, using the new great API code named Molehill. ActionScript is my old programming language, today I don&#8217;t hold much lover for it, but I know that there are many people that still loving Flash. Another important step is to port NinevehGL to JavaScript to work with WebGL. But at the beginning, NinevehGL will work only with OpenGL ES 2.x for iOS.</p>
<p>Now the most important question: &#8220;Why NinevehGL instead of PowerVR, Oolong, SIO2, Torque, Ogre, UDK, Unity, Wolfenstein, Shiva, Galaxy, or any other? Why should I choose NinevehGL instead any other 3D engine?&#8221;.</p>
<p>I always tried to convince everyone to buy what I was selling, trying to convince everybody from my point of view. But not this time, I don&#8217;t want to sell anything, I don&#8217;t want to convince you. If you are using some other engine and glad with that, just continue with it, you don&#8217;t have to change. Also, if you are a great OpenGL programmer and have your very own model and structure, continue with it, don&#8217;t change anything. Because, again, I don&#8217;t want to convince anyone at this time. Just as OpenGL, I&#8217;ll focus on the most important thing to me: development!</p>
<p>I took everything that I&#8217;ve seen of worst in other engines and I&#8217;ve tried to make it better in NinevehGL. I took all my frustations with the actual engines, all my luggage as developer, all my knowledge about 3D world and put all of them in the NinevehGL. So, if you are like me and you have some insatisfaction with the other engines, for you, NinevehGL could really nice for you! I know I&#8217;m telling this every time, but I love this concept:&#8221;Keep it simple!&#8221; This is the NinevehGL&#8217;s main principle, everything was made to be simple. There are no commands that need more than one single line of code. If you want to make one thing, you need one line, nothing else.</p>
<p>Now I&#8217;ll describe in details the most important features of NinevehGL. Remember, I don&#8217;t want to convince you of anything. I&#8217;m sure you are an advanced programmer and can form your own opinion about what&#8217;s coming next. If you like it, great! If don&#8217;t, it&#8217;s great as well! Just tell me why and I&#8217;ll try to make better.</p>
<p>Here is a features&#8217; list.</p>
<table width="675">
<tr>
<th>NinevehGL Features</th>
</tr>
<tr>
<td>Imports OBJ file.</td>
</tr>
<tr>
<td>Imports DAE (COLLADA) file.</td>
</tr>
<tr>
<td>Works with NGL binary file (exclusive of NinevehGL).</td>
</tr>
<tr>
<td>Cache 3D files to optimize the loading in next times (around 95% less loading time).</td>
</tr>
<tr>
<td>Works with OpenGL ES 2.x (programmable pipeline).</td>
</tr>
<tr>
<td>Full integrations with custom Shaders.</td>
</tr>
<tr>
<td>Supports 3D and 2D application.</td>
</tr>
<tr>
<td>Programming interface is 100% User Friendly and totally independent of OpenGL version.</td>
</tr>
<tr>
<td>Absolutely oriented to performance and minimum size (NinevehGL is 10% &#8211; 60% faster than any other engine).</td>
</tr>
<tr>
<td>Full support for PVRTC (even to without header generated by MacOS).</td>
</tr>
<tr>
<td>Automatically calculates normals and tangent space to work with lights and bump maps.</td>
</tr>
</table>
<p><br/><a name="importing"></a></p>
<h2><strong>Importing 3D files</strong></h2>
<p>This is the most problematic topic to me considering other engines. As OpenGL doesn&#8217;t import 3D files directly, you must use an engine that imports a file good for you or use one of the files accepted by that engine, like POD to PowerVR engine.</p>
<p>This is the first problem that NinevehGL works to solve, it can import the two most popular 3D file formats: COLLADA and WaveFront OBJ. You know what a mess the 3D imports with 3D softwares are. Each software has its own file format and implements its importing routines at its own way. So it&#8217;s not hard to export an OBJ from 3DS Max and when you try to import in Maya, BOOM, error! To tell the truth, the incompatibility with the files when exporting from a 3D software to another is common.</p>
<p>The NinevehGL has a full importing routine. What that means? If your OBJ file has informations about the specular, the bump map, the reflection map or anything supported by OBJ file, NinevehGL will import and parse everything for you with no losses. The same is true for COLLADA files.<br />
<div id="attachment_1383" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/importing_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/importing_example.jpg" alt="NinevehGL supports OBJ and DAE files." title="importing_example" width="600" height="600" class="size-full wp-image-1383" /></a><p class="wp-caption-text">NinevehGL supports OBJ and DAE files.</p></div></p>
<p><br/><a name="caching"></a></p>
<h2><strong>Caching 3D files</strong></h2>
<p>This is the greatest feature in my opinion. NinevehGL works with a third kind of file, the NGL binary file. It&#8217;s a binary file containing a full 3D model with all informations necessary to NinevehGL and also OpenGL. This file is loaded through streaming, so it&#8217;s extremely fast. There are no 3D softwares that can export it, it&#8217;s exclusive from NinevehGL. So how you can use it? There are two ways: First, you can convert your OBJ or COLLADA file on-line! Yes, you read it right, on-line convertion! No plugins, no installations, no complex things, you can generate NGL file on-line! Just access the NinevehGL website, choose the files on your machine and hit the button!</p>
<p>The other way, is the most fascinating one. NGL file is generated automatically by NinevehGL at the first time you load a new file from OBJ or COLLADA. This file will be stored locally in the device under the folder <em><Application_Home>/Library/NinevehGL</em>. What is great here, is that this folder is fully backed up by iTunes. So imagine this:</p>
<ol>
<li>You make an APP, which loads OBJ and COLLADA files.</li>
<li>An user make the download of your APP from the APP Store.</li>
<li>The user runs your APP at the first time, the NinevehGL loads around 20 3D file in 12 secs, let&#8217;s suppose.</li>
<li>The next times that this user runs your APP, the loading time will be 0.12 secs, for example.</li>
</ol>
<p>What happened???<br />
It&#8217;s great! At the second run, the NinevehGL automatically identified  that those 20 3D files were already parsed before, so it will use the cached NGL binary files instead the original ones!</p>
<p>But this feature doesn&#8217;t stop here! Remember, NinevehGL was made to make everything be simple! So, let&#8217;s suppose your application loads the 3D files through the internet connection instead loading it locally. No problems! NinevehGL compares the modification date of the files and choose the most recent. Imagine this:</p>
<ol>
<li>Your APP loads the 3D files from the internet, because you want to make updates without submeting a new APP to APP Store.</li>
<li>An User downloads your APP. First run, 20 3D files in 12 secs.</li>
<li>In the next times, NinevehGL will use NGL binary files, loading them in 0.12 secs.</li>
<li>You make an update and upload some new 3D files.</li>
<li>All the users that have your APP will receive the update, with 10 new 3D files replacing the old ones, so NinevehGL will parse the new downloaded files in 10 secs and it&#8217;ll generate new NGL binary files.</li>
<li>In the next runs of your application, NinevehGL will use the new generated NGL files and the loads will happen in 0.08 secs.</li>
</ol>
<p>I cry of happiness every time I explain this routine. It&#8217;s amazing, wonderful, outstanding, great, it&#8217;s&#8230; it&#8217;s&#8230;  &#8220;magical&#8221;! Well, this is just my opinion about it. But I&#8217;m sure you can imagine how great would be to the final user: &#8220;At the first run, a loading of few seconds, next times, no loading? Where is the loading of this APP?&#8221;. The loading happens in a snap.</p>
<div id="attachment_1384" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/importing_ngl_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/importing_ngl_example.jpg" alt="NinevehGL automatically saves NGL binary files locally." title="importing_ngl_example" width="600" height="600" class="size-full wp-image-1384" /></a><p class="wp-caption-text">NinevehGL automatically saves NGL binary files locally.</p></div>
<p>The last thing I want to say about this feature is the optimization. Again, the NinevehGL was made to be EXTREMELY FAST! So, if you load a NGL binary file directly, it will not create a cache file to it, because it is already optimized, it&#8217;ll just create cache from non optimized files (OBJ and COLLADA). Now you know how to convert your 3D models to NGL binary file, you can convert them on-line, at the official NinevehGL website, or can just run your application in the simulator and take the binary file generated at the first run and find the file at <em><Application_Home>/Library/NinevehGL</em>!</p>
<p>In order to avoid confusion, it&#8217;s important to say that NinevehGL will not be responsible to manage the internet connection for the file downloading. So you can&#8217;t inform an URL to load a 3D file. What the NinevehGL will make is manage the files locally.</p>
<p><br/><a name="shaders"></a></p>
<h2><strong>Custom Shaders</strong></h2>
<p>The NinevehGL was made to work with OpenGL programmable pipeline. So obviously it&#8217;ll create its own shaders, based on the materials (loaded from 3D files or materials created directly in the code). Well, the most fun part of the programmable pipeline is exactly the shaders, so will NinevehGL block us of using our own shaders? Of course NOT! NinevehGL is absolutely user friendly, it&#8217;s flexible!</p>
<p>The other engines working with programmable pipeline are used to give to us only two choices. Working only with your very own shaders or working only with their shaders! Well, this is not a choice, but rather it&#8217;s a dilema! But, the NinevehGL offers another way, a third way: &#8220;all of above&#8221;! Yes, your read it right, NinevehGL has an API Shader capable to integrate two or more shaders into only one program. WOW, what that means?</p>
<p>That means you can create your own shaders, just as you are used to, implementing your own lights effects, materials or anything else you want. Then you pass your shaders to the NinevehGL and it&#8217;ll integrate your custom shaders with the shaders generated by the NinevehGL materials. No conflicts, everything works fine together!</p>
<p>This works for Vertex Shader and/or Fragment Shader. An important thing to say is that there are no special constraints, you can even use a shader that you already have, with many variables inside, many functions and the main function. The NinevehGL Shader API will interpretate the code inside the shaders and will fuse all together.</p>
<div id="attachment_1385" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/importing_shaders_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/importing_shaders_example.jpg" alt="NinevehGL can merge your custom shader with its own shaders." title="importing_shaders_example" width="600" height="326" class="size-full wp-image-1385" /></a><p class="wp-caption-text">NinevehGL can merge your custom shader with its own shaders.</p></div>
<p><br/><a name="tangent_space"></a></p>
<h2><strong>Calculating Normals and Tangent Space</strong></h2>
<p>This is the robust side of NinevehGL. It&#8217;s very fast even in the hard processing scopes, like calculations of normals and tangent space for imported models. Normals and tangent space are very important to generate real time lights, reflections, bump effects and many other things. NinevehGL automatically calculates the normals and generates the tangent space for each mesh that needs it.</p>
<div id="attachment_1386" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/tangent_space_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/tangent_space_example.jpg" alt="NinevehGL automatically generates normals and tangent space, if needed." title="tangent_space_example" width="600" height="600" class="size-full wp-image-1386" /></a><p class="wp-caption-text">NinevehGL automatically generates normals and tangent space, if needed.</p></div>
<p>NinevehGL can automatically generate some effects, like specular lights, ambient light, emissive light, bump map, reflections and other ones specified by NinevehGL materials. NinevehGL doesn&#8217;t impose any limitations to you, it just works around the limits of the OpenGL. So, in the iOS, for example, you can work with very high mesh models. Obviously this is not a common situation, but sometimes it could be better to see high mesh models on the screen. Even to these high meshes, NinevehGL will continue to produce the normals, tangent space, specular lights, bump maps, reflections and everything else you need.</p>
<div id="attachment_1388" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/specular_light_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/specular_light_example.jpg" alt="NinevehGL also works with very high mesh models." title="specular_light_example" width="600" height="600" class="size-full wp-image-1388" /></a><p class="wp-caption-text">NinevehGL also works with very high mesh models.</p></div>
<p>Now I want to show you some other features that are also great, but I&#8217;ll not talk in deep here.</p>
<p><br/><a name="textures"></a></p>
<h2><strong>Optimizing Textures</strong></h2>
<p>Just to keep it fresh on our minds, NinevehGL was made to operate in the maximum performance. So even the loaded textures will be optimized. If you choose to work with an opaque OpenGL Layer (the default), the textures could be optimized to the format RGB_5_6_5, which is the best choice without alpha channel. If you choose to work with transparent layer, the textures could be optimized to the format RGBA_4_4_4_4.</p>
<p>The optimization process will happens automatically and you don&#8217;t need to worry about it. Even to PVRTC compressed texture format, these optimization could happen, if needed to. The textures, as any other external file, can be loaded from any path locally and the NinevehGL is ready to manage the local paths to you.</p>
<p>Plus, just as the 3D files, textures has a kind of &#8220;cache&#8221;, that means if you load an image more than one time, the NinevehGL will manage the load locally and will not spend more memory with the same cached image. This is a very important optimization, mostly in cases when a 3D file use the same image for many things, like to the ambient, diffuse and specular maps.</p>
<p><br/><a name="more"></a></p>
<h2><strong>Many other things</strong></h2>
<p>There are in NinevehGL many other important features, but I&#8217;ll just point it because other engines also have these features, so it&#8217;s not that exclusive. Like:</p>
<ul>
<li>Cameras with projections (perspective and orthographic).</li>
<li>Customizations of OpenGL behaviors, like the render buffers.</li>
<li>Simple API to make 3D transformations (like obj.rotateX += 1.0).</li>
<li>Always use OpenGL optimization features, as Buffer Objects, array of structures, optimized texture formats, etc.</li>
</ul>
<p>One great thing to talk a little bit more is about the auto-corrections. It&#8217;s very common that the 3D modelers create their models with different scales, I mean, a 3D file which contains a spoon could has the range of vertices going through -1000.0 to 1000.0 and other file which contains a house with the range of -0.5 to 0.7, for example. By placing both files in a 3D softwares you probably will see a house at the side of the empire state in format of a spoon.</p>
<p>For a 3D softwares this is not a big deal, because there are an infinity work space and you can simply reorganize your objects visually. But for a programming language, this is a problem and gets even bigger if the object is so big or so far that you can&#8217;t even see it on the screen.</p>
<p>The NinevehGL auto-correction can solve this problem for you, because it can normalize the vertices positions to fit on the screen (or in a specific range you want). By doing so you can control the size of your models without having to export it again from the 3D software. So in the case of the house and the spoon you could set the auto-correction to fit the house at the range -10.0 to 10.0 and the spoon to -0.1 and 0.1, simple as that (one line of code).</p>
<p><br/><a name="outside"></a></p>
<h2><strong>Outside the Scope</strong></h2>
<p>What you should not expect from NinevehGL? Here is a list:</p>
<ul>
<li>The NinevehGL is not a game engine, it&#8217;s a 3D engine.</li>
<li>So you shouldn&#8217;t expect physics controllers or sound controllers. You should construct this kind of stuff by yourself.</li>
<li>No animation, YET! Animations is very important in the 3D world, but the first version of NinevehGL will not come with this feature. (Animations = Character Rigging + Bones)</li>
<li>No collisions, YET! There are two techniques to deal with collision, bounding box and bounding mesh. In this version, NinevehGL will not implement any of those.</li>
</ul>
<p>Obviously any item in this list can change, because the NinevehGL is flexible. Consider the above list as an &#8220;out of scope&#8221; list only for the first version of the NinevehGL.</p>
<p><br/><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p>I&#8217;m sure you have now a solid opinion about NinevehGL, good or not, so let me know what you think, post a comment bellow, send me an email, tweet me&#8230; anything.</p>
<p>Again, I don&#8217;t want to make promisses, but I really want to see this engine released soon. So I&#8217;m sure it will come in the first half of this year (2011). I&#8217;m just finishing some details now and organizing everything for the first release.</p>
<p>Thanks for reading,</p>
<p>And see you very soon!</p>
<div id="attachment_1382" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/ninevehgl_featured.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/ninevehgl_featured.jpg" alt="NinevehGL will come in the first half of 2011." title="ninevehgl_featured" width="600" height="475" class="size-full wp-image-1382" /></a><p class="wp-caption-text">NinevehGL will come in the first half of 2011.</p></div>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/04/ninevehgl-features/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

