<?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>Games from Within &#187; Graphics</title>
	<atom:link href="http://gamesfromwithin.com/category/graphics/feed" rel="self" type="application/rss+xml" />
	<link>http://gamesfromwithin.com</link>
	<description>Living the indie life</description>
	<lastBuildDate>Mon, 16 Jan 2012 20:37:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Quick Tip: Working With Shaders On iOS</title>
		<link>http://gamesfromwithin.com/quick-tip-working-with-shaders-on-ios</link>
		<comments>http://gamesfromwithin.com/quick-tip-working-with-shaders-on-ios#comments</comments>
		<pubDate>Fri, 06 Jan 2012 19:13:09 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1607</guid>
		<description><![CDATA[I&#8217;m taking a couple of days to upgrade some of my libraries for doing prototyping both in 2D and 3D. One of the many overdue things I wanted to do, was to finally ditch OpenGL ES 1.1 and move to &#8230; <a href="http://gamesfromwithin.com/quick-tip-working-with-shaders-on-ios">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m taking a couple of days to upgrade some of my libraries for doing prototyping both in 2D and 3D. One of the many overdue things I wanted to do, was to finally ditch OpenGL ES 1.1 and move to 2.0 exclusively. Yes, even if you&#8217;re only doing a 2D game, OpenGL ES 2.0 is way worth it. </p>
<p>There were even a couple of cases during Casey&#8217;s Contraptions that we wanted a particular effect, and couldn&#8217;t get it quite right, but it would have been trivial to whip up a shader if we had been using OpenGL ES 2.0. In the end, we had to resort to <a href="http://gamesfromwithin.com/customizable-color-sections-with-opengl-es-1-1">texture combiners</a> (yuck), and it wasn&#8217;t exactly what we had in mind.<span id="more-1607"></span>OpenGL ES 2.0 requires that you write shaders for any different kind of &#8220;thing&#8221; you render, whether it&#8217;s a simple 2D quad, or a fancy skinned character. I wanted to provide at least a basic 2D rendering shader in my graphics library, but the workflow was a bit awkward.</p>
<p>First of all, shaders on iOS are compiled at runtime <a href="#1">[1]</a>, so we need to access the shader source and compile it. Initially I was thinking of having the shader source files as text in the graphics library, but for the game to access those files, it would have to explicitly add them to its resources so they can be copied during the build phase. That&#8217;s error prone (I would always forget to do that with every new project) and just plain ugly.</p>
<p>Another possibility would be to include the source text as a string in the library. That would simplify things, but it would mean that:</p>
<ol>
<li>You would lose shader syntax highlighting.</li>
<li>You would need to have the annoying \ at the end of every line.</li>
</ol>
<p>After <a href="https://twitter.com/#!/noel_llopis/status/155072436113649665">asking on Twitter and getting some good suggestions</a>, I decided the easiest way would be to use <a href="http://linuxcommand.org/man_pages/xxd1.html">xxd</a>. It&#8217;s a shell tool that comes preinstalled in all Macs (and Linux) that takes a file and converts it into a C array that can be included in a program directly.</p>
<p>I liked xxd even better than the old standby of <a href="http://wiki.wxwidgets.org/Embedding_PNG_Images-Bin2c_In_Python">bin2c</a> because it already comes installed, and it generates the whole file, not just an array that then needs to be included from another file. Yes, it would be easy enough to modify, but why bother when you have a perfect tool for the job already?</p>
<p>Now, I can set up a custom rule in Xcode 4 like this:</p>
<div style="text-align:center;"><img  src="http://gamesfromwithin.com/wp-content/uploads/2012/01/custom_rule1.png" alt="Custom rule" border="0" width="600" height="288" /></div>
<p><b>Update:</b> The array generated by xxd isn&#8217;t null-terminated, so we need to add a zero to the array. The easiest way is to use sed. Thanks to <a href="http://twitter.com/#!/SixEchoStudios">SixEcho Studios</a> for the heads up. Also, I updated it to use the varaibles INPUT_FILE_DIR and INPUT_FILE_NAME thanks to <a href="http://twitter.com/#!/mysterycoconut">Miguel&#8217;s</a> comments.</p>
<p>Now, whenever the shader source changes, it generates a header file like this:</p>
<pre>
unsigned char PassThrough_fsh[] = {
  0x0a, 0x0a, 0x76, 0x61, 0x72, 0x79, 0x69, 0x6e, 0x67, 0x20, 0x6c, 0x6f,
  0x77, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x44, 0x65, 0x73, 0x74,
  0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6c, 0x6f, 0x72,
  0x3b, 0x0a, 0x0a, 0x76, 0x6f, 0x69, 0x64, 0x20, 0x6d, 0x61, 0x69, 0x6e,
  0x28, 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x67, 0x6c, 0x5f,
  0x46, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20,
  0x44, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43,
  0x6f, 0x6c, 0x6f, 0x72, 0x3b, 0x0a, 0x7d
,0x00};
unsigned int PassThrough_fsh_len = 91;
</pre>
<p>To compile that shader in the game, all I have to add is two lines:</p>
<pre>
#include <Graphics/Shaders/PassThrough.fsh.h>
//...
const int fs = ShaderUtils::CompileShader(PassThrough_fsh, GL_FRAGMENT_SHADER);
</pre>
<p>Done! Clean, simple, and minimal cruft. </p>
<p><b>Update:</b> I haven&#8217;t tried it yet because I haven&#8217;t had the need for any expensive shaders, but I hear really good things about Aras Pranckevičius GLSL optimizer. In that case, I would add it before the xxd step. You would still use the shader the same way, but it would be optimized and perform faster.</p>
<p><br/></p>
<p><a name="1"></a>[1] That&#8217;s a huge mistake and I hope Apple fixes that ASAP. <a href="https://github.com/aras-p/glsl-load-speed">Loading times for any amount of non-trivial shaders adds up really quickly</a>. That&#8217;s the last thing you want on a mobile device! The OpenGL ES 2.0 standard provides an optional way to load binary shaders, and all that Apple has to do is provide a tool that will compile shaders for the iOS hardware. To be completely future-proof, you they can even mandate that if the binary load fails, you still need to compile from source.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/quick-tip-working-with-shaders-on-ios/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Trying Out Multisampling On iOS</title>
		<link>http://gamesfromwithin.com/trying-out-multisampling-on-ios</link>
		<comments>http://gamesfromwithin.com/trying-out-multisampling-on-ios#comments</comments>
		<pubDate>Fri, 16 Dec 2011 21:03:33 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iDevBlogADay]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[flower garden]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1578</guid>
		<description><![CDATA[I only recently broke free of iOS3.x for Flower Garden, so I&#8217;m finally adding all the features I had been itching to add that required higher OS support. I had already added some iOS4+ features, but I was keeping them &#8230; <a href="http://gamesfromwithin.com/trying-out-multisampling-on-ios">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I only recently broke free of iOS3.x for Flower Garden, so I&#8217;m finally adding all the features I had been itching to add that required higher OS support. I had already added some iOS4+ features, but I was keeping them to a minimum because it&#8217;s always a huge cause of bugs to target multiple versions of the OS at once.</p>
<p>One of the first features I looked into adding was <a href="http://en.wikipedia.org/wiki/Multisample_anti-aliasing">multisample antialiasing (MSAA)</a> support for OpenGL, which was originally introduced in iOS 4.0. The geometry generated for the petals in Flower Garden is fairly high contrast, and since it&#8217;s not like the textures were carefully created and laid out by an artist, the result is pretty bad aliasing around the edges. Perfect candidate for multisampling!<span id="more-1578"></span>I based everything on the <a href="http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html#//apple_ref/doc/uid/TP40008793-CH103-SW12">Apple documentation on multisampling</a>. It was very straightforward and it works for both off-screen and view-based render targets. It was also extremely helpful to keep both the ability to use regular and multisampled render targets. That way I can easily run performance and visual comparisons, and, if necessary, I can disable multisampling on a particular device. </p>
<p>The main gotcha was making sure I used the GL_RGBA8_OES color format on the multisampling color buffer (otherwise it won&#8217;t work, and all you&#8217;ll get are 1282 &#8220;invalid operation&#8221; OpenGL errors). Also, if you&#8217;re in the same boat as Flower Garden, which uses OpenGL ES 1.1 and the fixed function pipeline, you&#8217;ll have to add _OES to just about every constant in the documentation.</p>
<h2>Visual results</h2>
<p>I will let the screenshots speak for themselves.</p>
<div style="text-align:center;"><img  src="http://gamesfromwithin.com/wp-content/uploads/2011/12/multisample.png" alt="Multisample" border="0" width="600" height="451" /></div>
<p>In this screenshot you can see the rendering of the pots using off-screen render targets.</p>
<div style="text-align:center;"><img  src="http://gamesfromwithin.com/wp-content/uploads/2011/12/multisample2.png" alt="Multisample2" border="0" width="600" height="450" /></div>
<p>Pretty impressive improvement, even if I say so myself! The improvement is even more striking in-game because the animation of the flowers moving in the wind doesn&#8217;t have jaggies popping in and out.</p>
<p>The improvements are more noticeable on the iPad because the pixels are bigger, and, not surprisingly, less so on retina-display iPhones. But even on the retina displays, jaggies are less noticeable during the flower wind-swaying animations.</p>
<h2>Performance</h2>
<p>So, no doubt: They look pretty. But how about performance? Under the hood, the rasterizer is generating four samples for every pixel, and then combining them at the end in a separate step. <strike>So you&#8217;ll get more of a performance hit with complex pixel shaders</strike>. <b>Edit:</b> My bad. I spaced out and I forgot that MSAA only evaluates the pixel shader once, so performance doesn&#8217;t depend on pixel shader complexity. Instead, the performance hit probably comes from the extra writes (four per pixel) to the render target, and should be fairly similar between games.</p>
<p>It turns out that Flower Garden is still using OpenGL ES 1.1, which is implemented using shaders at the driver level. Fortunately, even though I&#8217;m using some texture combiner operations and several input textures, those pixel shaders aren&#8217;t all that complex.</p>
<p>These are the frames per second I recorded with one particular flower pot on the different devices I have for testing. Notice that the lowest device I have listed is the iPhone 3GS. That&#8217;s because I have also stopped supporting arm6 CPUs to keep things simpler (and the market share is minimal).</p>
<p><b>Update:</b> I was only running the game loop at 30 fps, so the initial performance numbers I had listed are pretty meaningless. Here are the correct numbers running at a max of 60 fps.</p>
<table>
<tr>
<th>Device</th>
<th>Without MSAA</th>
<th>With MSAA</th>
</tr>
<tr>
<td>iPhone 3GS</td>
<td align="center">39 fps (25.6 ms)</td>
<td align="center">37 fps (27.0 ms)</td>
</tr>
<tr>
<td>iPhone 4</td>
<td align="center">48 fps (20.8 ms)</td>
<td align="center">23 fps (43.5 ms)</td>
</tr>
<tr>
<td>iPhone 4S</td>
<td align="center">60 fps (16.7 ms)</td>
<td align="center">60 fps (16.7 ms)</td>
</tr>
<tr>
<td>iPad 1</td>
<td align="center">60 fps (16.7 ms)</td>
<td align="center">18 fps (55.6 ms)</td>
</tr>
<tr>
<td>iPad 2</td>
<td align="center">60 fps (16.7 ms)</td>
<td align="center">60 fps (16.7 ms)</td>
</tr>
</table>
<p>Of the devices I tested, MSAA didn&#8217;t slow down things much on the iPhone 3GS, and the iPhone 4S was maxed out at 60 fps both ways. The iPad 1 was a different story, and performance crashed from 60 fps to 18 fps. Like Rory pointed in the comments, looking at the actual time instead of the fps gives a better insight. Using MSAA adds 38.9 ms to each frame! The iPhone 4 also suffered from a big performance hit due to all the extra pixels in the retina display. I don&#8217;t care how pretty the flowers are, that&#8217;s just not acceptable (and no, I&#8217;m not adding user-tweakable graphics settings like PC games).</p>
<p>I should also add that Flower Garden is hugely CPU bound. It generates all that geometry every frame on the CPU, and that&#8217;s a lot of vector transforms. So if your game is GPU bound, you&#8217;re likely to see higher performance hits.</p>
<p>I was initially very surprised to see that the performance on the simulator tanked big time (as in, going from 30 fps to 5 fps). This was news to me, but apparently the iOS simulator runs completely in software, so the quadrupling of pixels brings it to its knees. I&#8217;m really, really, impressed at how smoothly it usually runs for being in software though. It had me fooled thinking it was using OpenGL under the hood!</p>
<p>As far as memory goes, after an <a href="https://twitter.com/#!/Frogblast/status/144811240177405952">animated discussion on Twitter</a>, it seems that the iPhone does create full buffers for the multisample frame buffers, so there is a significant increase in memory usage. It&#8217;s not something easy to track because it all happens at the driver level, but it&#8217;s something to be aware of. Because of this, I might consider turning multisampling off on retina displays, since the improvement is not mind-blowing (and the extra memory is very significant because of the amount of pixels). I&#8217;ll also probably turn it off in the simulator so I can achieve a decent frame rate during development.</p>
<h2>Conclusions</h2>
<p>Multisampling only required adding a few lines of code and resulted in an impressive visual improvement and minimal performance impact in some devices. It&#8217;s a no-brainer on the 3GS and iPad 2. I&#8217;m wishing I had implemented it earlier!</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/trying-out-multisampling-on-ios/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Customizable Color Sections With OpenGL ES 1.1</title>
		<link>http://gamesfromwithin.com/customizable-color-sections-with-opengl-es-1-1</link>
		<comments>http://gamesfromwithin.com/customizable-color-sections-with-opengl-es-1-1#comments</comments>
		<pubDate>Thu, 19 Aug 2010 18:38:03 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iDevBlogADay]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[flower garden]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1124</guid>
		<description><![CDATA[One of the items in my ever-growing list of things to write about, is the rendering techniques I used in Flower Garden. In the end, it would make for a post with lots of pretty pictures, but there&#8217;s nothing particularly &#8230; <a href="http://gamesfromwithin.com/customizable-color-sections-with-opengl-es-1-1">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the items in my ever-growing list of things to write about, is the rendering techniques I used in Flower Garden. In the end, it would make for a post with lots of pretty pictures, but there&#8217;s nothing particularly ground-breaking. After all, it&#8217;s all limited to OpenGL ES 1.1 on the iPhone, which means only two texture units and a two-stage texture combiner. As a result, more interesting ideas keep bubbling up to the top of the list and the poor rendering idea keeps getting passed over.</p>
<p>Every so often, something happens that bumps up the priority of one of the items in my list. Maybe it&#8217;s another related blog post, or a game coming out with something relevant to what I wanted to write about. In this case it was <a href="http://twitter.com/madgarden/status/20999821267">a tweet from Paul Pridham</a> <a href="#1">[1]</a>:</p>
<p><center><a href="http://twitter.com/madgarden/status/20999821267"><img src="http://gamesfromwithin.com/wp-content/uploads/2010/08/tweet.png" alt="tweet.png" border="0" width="300" height="133" /></a></center></p>
<p>Customizing colors in a sprite or texture is very frequent in games, from changing player characters into blue and red teams, to creating color variations of an armor piece, to letting the player pick the exact shade for their pet&#8217;s fur color. Or, in the case of Flower Garden, to change the colors of the petals on the fly.</p>
<p>There are two requirements for this:</p>
<ul>
<li>We want to change colors dynamically.</li>
<li>We only want to affect certain areas of the original texture.</li>
</ul>
<p>That rules out creating texture variations ahead of time, although that might be a valid approach sometimes if you have lots of art resources, don&#8217;t mind increasing the download size, and you have a fixed number of variation to deal with. It also rules out modulating/blending the texture by a particular color because it would tint all the texture, and we want to limit the effect to particular areas (leave the player&#8217;s arms their normal color, but change their shirt color).</p>
<p>This is one of those funny cases that it was a lot easier to do many years ago, when we used palletized color modes. You could set all the custom color areas to a particular palette entry, and then update that entry on the fly. Ah, all the <a href="http://ahefner.livejournal.com/11670.html">awesome tricks</a> palettes opened up the door to! I still miss them to this day.</p>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/08/color.jpg" alt="color.jpg" border="0" width="256" height="476" />In modern hardware it&#8217;s also really easy to do with a shader, but Paul wanted to use it across any iPhone device, and the majority of them are still stuck on OpenGL ES 1.1, so fixed-function pipeline it is.</p>
<p>The simplest approach would be to just render the model twice: First pass renders the texture, and second pass renders the custom color bits (you can render them with a white texture modulated by the global color to get the right color). The main drawbacks are that you&#8217;re doubling the number of draw calls, and, with 3D objects, it gets a bit tricker because the second pass needs to use the glDepthFunc(GL_EQUAL) depth comparison function.</p>
<p>The better way to do this is using the <a href="http://www.opengl.org/wiki/Texture_Combiners">texture combiners</a>. Texture combiners allow us to perform a limited number of operations to control the final look of a pixel. We can add two textures, or multiply them, or even do a few <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/glTexEnv.xml">more complex operations</a>. The true power of the combiners is that they can be chained together, so the output from one feeds into the input of another, allowing us to create much more complex operations.</p>
<p>The iPhone 3G is limited two two texture combiner units <a href="#2">[2]</a>, but even two combiners are good to create a good range of effects.</p>
<p>Let&#8217;s think about what we want to accomplish. We want to leave some parts of the texture completely alone and display the original pixel value. In some other parts of the texture, we want to replace the pixels there with a custom color. Actually even better, we probably want to multiply those pixels by a custom color. That way we can author the part of the texture that is going to change with grayscale details, and our color adds the tint to it.</p>
<p>Let&#8217;s express it mathematically. Let&#8217;s make a function M that is 1 for every pixel we want to color, and 0 for the ones where the original texture is supposed to be displayed. Our desired color is c and the texture it t. In that case, the final pixel color (p) is:</p>
<p>p = M*(c*t) + (1 &#8211; M)*t</p>
<p><center><br />
<img src="http://gamesfromwithin.com/wp-content/uploads/2010/08/texture.jpg" alt="texture.jpg" style="padding : 10px;" border="0" width="128" height="128" /><img src="http://gamesfromwithin.com/wp-content/uploads/2010/08/mask.jpg" alt="mask.jpg" style="padding : 10px;"border="0" width="128" height="128" /></center></p>
<p>We could express that with two combiners: The first one is a modulate (multiply) operation with c and t, and the second one an interpolation operation between the result of the previous combiner and the original texture, based on the function M.</p>
<p>Obviously M is just a mask texture. We can paint it white where we want to color the texture, and black elsewhere. We could even use the alpha channel of the original texture, but there&#8217;s one big thing to watch out for: If you have your texture as a png and process it through the default iPhone resource operations, the image will be premultiplied for you (whether you want it or not), so your color information will be set to zero everywhere that the alpha channel is zero. Oops. You&#8217;ll probably want to use the alpha channel to store transparency anyway, so we&#8217;ll keep the mask separate. If not, make sure you encode the image yourself (as raw or PVRT formats) so it&#8217;s not premultiplied ahead of time.</p>
<p>Are we ready transfer that formula to the texture combiners? Not quite. Apparently (and this was just trial and error, I haven&#8217;t seen it documented), the texture assigned to a combiner can only be the one at that stage. If you look at the second combiner, we would need to have the first texture as one of the parameters, in addition to the mask.</p>
<p>So instead, we can reorganize the function above like this:</p>
<p>p = c*(M*t) + (t &#8211; M*t)</p>
<p>What did we gain by that? The color is what&#8217;s going to change dynamically, but the mask and the texture always stay the same. We could precompute the M*t term by simply multiplying the texture and the mask. We can call that new term A. We can do the same thing with the (t &#8211; M*t) term, which just means turning black all the pixels in the texture where mask will go. That one will be B. The easiest way to &#8220;precompute&#8221; those values is just doing it in Photoshop and exporting it as a new png.</p>
<p><center><img src="http://gamesfromwithin.com/wp-content/uploads/2010/08/A.jpg" alt="A.jpg" style="padding : 10px;" border="0" width="128" height="128" /><img src="http://gamesfromwithin.com/wp-content/uploads/2010/08/B.jpg" alt="B.jpg" style="padding : 10px;" border="0" width="128" height="128" /></center></p>
<p>Our new formula is now:</p>
<p>p = c*A + B</p>
<p>Nice and simple! Now we can really add that to the texture combiners like this:</p>
<pre>
// c
glColor4f(m_customColor.r, m_customColor.g, m_customColor.b, 1);

glActiveTexture(GL_TEXTURE0);
// A = M*t (precomputed)
glBindTexture(GL_TEXTURE_2D, m_maskHandle);
glEnable(GL_TEXTURE_2D);
// c*A
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

glActiveTexture(GL_TEXTURE1);
// B = t - M*t (precomputed)
glBindTexture(GL_TEXTURE_2D, m_textureHandle);
glEnable(GL_TEXTURE_2D);

// c*A + B
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_ADD);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_TEXTURE);
</pre>
<p>One more thing to watch out for: Because we&#8217;re using two textures, you need to have two sets of texture coordinates. In this case, we want them to be the same, so we can just point them to the same set of data:</p>
<pre>
glClientActiveTexture(GL_TEXTURE0);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &#038;vertices[0].u);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glClientActiveTexture(GL_TEXTURE1);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &#038;vertices[0].u);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
</pre>
<p>That&#8217;s it! You can see the results in the included project and play with the register combiners to achieve different operations.</p>
<p>At this point I was going to describe the texture combiner setup I use in Flower Garden to render the petals, but this post ended up taking longer than I had hoped for (I&#8217;m trying to shoot for an hour per post, but this has taken me already two hours between the code and the the post itself), so I&#8217;ll save that for another time.</p>
<ul>
<li><a href="http://gamesfromwithin.com/wp-content/uploads/2010/08/CustomColor.zip" title="CustomColor.zip">Demo source code</a>. Released under the MIT license.
</ul>
<p><br/></p>
<p><a name="1"></a>[1] Paul developed <a href="http://itunes.apple.com/us/app/sword-of-fargoal/id343242870?mt=8">Sword of Fargoal</a>, by far my favorite iPhone RPG.<br />
<a name="2"></a>[2] The 3GS allows up to eight I believe.</p>
<p><br/></p>
<p><i>This post is part of <a href="http://idevblogaday.com/">iDevBlogADay</a>, a group of indie iPhone development blogs featuring two posts per day. You can keep up with iDevBlogADay through the <a href="http://idevblogaday.com/">web site</a>, <a href="http://feeds.feedburner.com/idevblogaday">RSS feed</a>, or <a href="http://twitter.com/#search?q=%23idevblogaday">Twitter</a>.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/customizable-color-sections-with-opengl-es-1-1/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>OpenGL And UIKit Demo</title>
		<link>http://gamesfromwithin.com/opengl-and-uikit-demo</link>
		<comments>http://gamesfromwithin.com/opengl-and-uikit-demo#comments</comments>
		<pubDate>Sat, 10 Apr 2010 22:37:51 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[opengl]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=876</guid>
		<description><![CDATA[This coming Monday I&#8217;ll be giving a presentation at 360iDev titled &#8220;All You Wanted To Know About Mixing OpenGL with UIKit (And More)&#8221;. It&#8217;s an extended version of my talk at this year&#8217;s GDC iPhone Summit. It&#8217;s going to be &#8230; <a href="http://gamesfromwithin.com/opengl-and-uikit-demo">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/04/uikit_demo.png" alt="uikit_demo.png" border="0" width="200" height="300"/>This coming Monday I&#8217;ll be giving a presentation at <a href="http://360idev.com">360iDev</a> titled &#8220;All You Wanted To Know About Mixing OpenGL with UIKit (And More)&#8221;. It&#8217;s an extended version of <a href="http://gamesfromwithin.com/gdc-2010-the-best-of-both-worlds-using-uikit-with-opengl">my talk</a> at this year&#8217;s <a href="http://www.gdconf.com/conference/iphone.html">GDC iPhone Summit</a>. It&#8217;s going to be 1h 20min long instead of just half an hour.</p>
<p>The main difference is that I&#8217;m going to go in detail about each of the different cases of mixing OpenGL and UIKit, and what better way to do that than with a live demo. I&#8217;ll be switching back and forth between Keynote and XCode and going over the details, which is where a lot of the tricky parts are.</p>
<p><a href="http://gamesfromwithin.com/wp-content/uploads/2010/04/OpenGLUIKit.zip" title="OpenGLUIKit.zip">Here is the source code for the demo</a>. That way you can look at it now and come to the session prepared with more questions, or ready to discuss what works and what doesn&#8217;t work for you. I love to have interactive sessions, so definitely come ready to ask questions.</p>
<p>If you&#8217;re not coming to 360iDev&#8230; shame on you! It&#8217;s the best iPhone conference around. You&#8217;ll be missing not just my session, but tons of other great talks, and the <a href="http://iphonegamejam.com">iPhone Game Jam</a> (sponsored by <a href="http://toucharcade.com">TouchArcade</a> this year). If you can&#8217;t make it this time, make a note on your calendar for next time!</p>
<ul>
<li><a href="http://gamesfromwithin.com/wp-content/uploads/2010/04/OpenGLUIKit.zip" title="OpenGLUIKit.zip">Demo source code</a>. Released under the MIT license.
</ul>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/opengl-and-uikit-demo/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>GDC 2010: The Best of Both Worlds: Using UIKit with OpenGL</title>
		<link>http://gamesfromwithin.com/gdc-2010-the-best-of-both-worlds-using-uikit-with-opengl</link>
		<comments>http://gamesfromwithin.com/gdc-2010-the-best-of-both-worlds-using-uikit-with-opengl#comments</comments>
		<pubDate>Sat, 13 Mar 2010 18:32:31 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[opengl]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=866</guid>
		<description><![CDATA[Here are the slides for my session at the GDC iPhone Summit, The Best of Both Worlds: Using UIKit With OpenGL. It was a 30-minute slot, so the material is pretty condensed without the chance to expand on the topics. &#8230; <a href="http://gamesfromwithin.com/gdc-2010-the-best-of-both-worlds-using-uikit-with-opengl">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/03/borg-701632.jpg" alt="borg-701632.jpg" border="0" width="200" height="200"/>Here are the slides for my session at the <a href="http://www.gdconf.com/conference/iphone.html">GDC iPhone Summit</a>, <a href="https://www.cmpevents.com/GD10/a.asp?option=C&#038;V=11&#038;SessID=10541">The Best of Both Worlds: Using UIKit With OpenGL</a>.</p>
<p>It was a 30-minute slot, so the material is pretty condensed without the chance to expand on the topics. I&#8217;m giving an extended version of this talk at <a href="http://www.360idev.com/">360iDev</a> in a few weeks, so I&#8217;ll be able to get into more details then and have a cool sample app that shows off all those concepts.</p>
<p>It was great seeing a bunch of you at my session and at around the iPhone and Indie Summits. It was a great couple of days!</p>
<ul>
<li><a href="http://www.slideshare.net/llopis/the-best-of-both-worlds-mixing-uikit-with-opengl">Presentation slides</a> (<a href="http://gamesfromwithin.com/wp-content/uploads/2010/03/GDC10_uikit_opengl.pdf">pdf format</a>)</li>
<li><a href="http://gamesfromwithin.com/opengl-and-uikit-demo">Sample code</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/gdc-2010-the-best-of-both-worlds-using-uikit-with-opengl/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting Started With Shaders On The iPhone 3GS</title>
		<link>http://gamesfromwithin.com/getting-started-writing-shaders-on-the-iphone-3gs</link>
		<comments>http://gamesfromwithin.com/getting-started-writing-shaders-on-the-iphone-3gs#comments</comments>
		<pubDate>Mon, 24 Aug 2009 23:25:41 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=611</guid>
		<description><![CDATA[I just wrote an article for Mobile Orchard on how to get started with OpenGL ES 2.0 on the iPhone 3GS. It goes over all the steps necessary to set up a barebones project that renders a quad on screen &#8230; <a href="http://gamesfromwithin.com/getting-started-writing-shaders-on-the-iphone-3gs">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://gamesfromwithin.com/wp-content/uploads/2009/08/shader.jpg"><img class="alignright size-full wp-image-616" title="shader" src="http://gamesfromwithin.com/wp-content/uploads/2009/08/shader.jpg" alt="shader" width="140" height="140" /></a>I just wrote <a href="http://www.mobileorchard.com/getting-started-with-opengl-es-20-on-the-iphone-3gs">an article for Mobile Orchard</a> on how to get started with OpenGL ES 2.0 on the iPhone 3GS. It goes over all the steps necessary to set up a barebones project that renders a quad on screen using a vertex and a fragment shader. It&#8217;s not the most stunning thing ever visually, but I think it makes for a good starting point for OpenGL ES 2.0 projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/getting-started-writing-shaders-on-the-iphone-3gs/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Environment Mapping Demo With OpenGL ES 1.1</title>
		<link>http://gamesfromwithin.com/environment-mapping-demo-with-opengl-es-1-1</link>
		<comments>http://gamesfromwithin.com/environment-mapping-demo-with-opengl-es-1-1#comments</comments>
		<pubDate>Sat, 01 Aug 2009 15:16:04 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[demo]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=561</guid>
		<description><![CDATA[I just finished creating a graphics demo for a chapter I&#8217;m writing for the book iPhone Advanced Projects edited by Dave Mark. In the chapter I go over a few different lighting techniques and go in detail on how to &#8230; <a href="http://gamesfromwithin.com/environment-mapping-demo-with-opengl-es-1-1">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://gamesfromwithin.com/wp-content/uploads/2009/08/Car.jpg"><img class="alignright size-full wp-image-562" title="Car" src="http://gamesfromwithin.com/wp-content/uploads/2009/08/Car.jpg" alt="Car" width="300" height="200" /></a>I just finished creating a graphics demo for a chapter I&#8217;m writing for the book <a href="http://www.amazon.com/iPhone-Advanced-Projects-Joachim-Bondo/dp/1430224037">iPhone Advanced Projects</a> edited by Dave Mark. In the chapter I go over a few different lighting techniques and go in detail on how to do masked environment mapping on an iPhone 3G with OpenGL ES 1.1.</p>
<p>The demo ended up looking pretty good, so I decided to upload a quick video showing the different lighting modes:</p>
<ul>
<li>Diffuse texture only</li>
<li>Diffuse texture plus ambient and diffuse lighting</li>
<li>Diffuse texture plus ambient, diffuse, and specular lighting (as usually, per-vertex lighting looks pretty bad, even though this is a relatively high-poly model)</li>
<li>Fully reflective environment map (using the normal environment map technique)</li>
<li>Environment map added to the diffuse texture and lighting</li>
<li>Environment map with a reflection mask plus diffuse texture and lighting (two passes on an iPhone 3G&#8211;or one pass if you&#8217;re not using the diffuse alpha channel)</li>
</ul>
<p>The chapter in the book will go in detail into each of those techniques, building up to the last one. Full source code will be included as well.</p>
<p>Some of these techniques will also be covered in my upcoming <a href="http://www.mobileorchard.com/iphone-opengl-programming-training-class/">Two Day iPhone OpenGL Class</a> organized in collaboration with <a href="http://www.mobileorchard.com/">Mobile Orchard</a>.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" height="340" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/uLavvowfsDE&amp;hl=en&amp;fs=1&amp;" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="560" height="340" src="http://www.youtube.com/v/uLavvowfsDE&amp;hl=en&amp;fs=1&amp;" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/environment-mapping-demo-with-opengl-es-1-1/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Teaching a Two-Day OpenGL iPhone Class. Register Now!</title>
		<link>http://gamesfromwithin.com/teaching-a-two-day-opengl-iphone-class-register-now</link>
		<comments>http://gamesfromwithin.com/teaching-a-two-day-opengl-iphone-class-register-now#comments</comments>
		<pubDate>Thu, 23 Jul 2009 09:11:40 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Announcements]]></category>
		<category><![CDATA[Conferences and events]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=514</guid>
		<description><![CDATA[I&#8217;m excited to announce the intensive, two-day class on OpenGL for the iPhone that I&#8217;ll be teaching. The class will be held September 26th-27th, in Denver, right before the 360iDev conference, and it&#8217;s part of the Mobile Orchard Workshops. The &#8230; <a href="http://gamesfromwithin.com/teaching-a-two-day-opengl-iphone-class-register-now">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-516" title="opengl" src="http://gamesfromwithin.com/wp-content/uploads/2009/07/opengl.jpg" alt="opengl" width="256" height="132" />I&#8217;m excited to announce the <a href="http://www.mobileorchard.com/iphone-opengl-programming-training-class/">intensive, two-day class on OpenGL for the iPhone</a> that I&#8217;ll be teaching. The class will be held September 26th-27th, in Denver, right before the <a href="http://www.360idev.com/">360iDev conference</a>, and it&#8217;s part of the <a href="http://www.mobileorchard.com/">Mobile Orchard Workshops</a>.</p>
<p>The class is aimed at iPhone developers without previous OpenGL experience. It&#8217;s going to be very hands-on, and you&#8217;ll create both 2D and 3D applications during the weekend. You&#8217;ll learn all the basics: cameras, transforms, and how to draw meshes, but we&#8217;ll also cover some more advanced topics such as lighting, multitexturing, point sprites, and even render targets. Most importantly, you&#8217;ll walk away with a solid understanding of the basis, which will allow you to continue learning OpenGL and advanced computer graphics on your own from the docs, samples, or even browsing the API directly.</p>
<p>The main requirement for the class is that you&#8217;re familiar with the iPhone development environment and that you have basic knowledge of the C language. Beyond that, to the the most out of the course, you should be familiar with the basics of linear algebra (vector, matrices, and dot products). Anything else, we&#8217;ll cover it all during the class.</p>
<p>Registration is now open, and you can get some great discounts by registering early and attending the 360iDev conference. For more details, check <a href="http://www.mobileorchard.com/iphone-opengl-programming-training-class/">the official announcement page</a>.</p>
<p>Hope to see some of you there!</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/teaching-a-two-day-opengl-iphone-class-register-now/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>A Huge Leap Forward: Graphics on The iPhone 3G S</title>
		<link>http://gamesfromwithin.com/a-huge-leap-forward-graphics-on-the-iphone-3g-s</link>
		<comments>http://gamesfromwithin.com/a-huge-leap-forward-graphics-on-the-iphone-3g-s#comments</comments>
		<pubDate>Sat, 20 Jun 2009 17:31:55 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=495</guid>
		<description><![CDATA[I just wrote an article over at Mobile Orchard about the new graphics capabilities on the new iPhone 3G S. Check it out to find out the details, and what those new features might mean for us developers.]]></description>
			<content:encoded><![CDATA[<p>I just wrote an article over at <a href="http://www.mobileorchard.com">Mobile Orchard</a> about <a href="http://www.mobileorchard.com/a-huge-leap-forward-graphics-on-the-iphone-3gs">the new graphics capabilities on the new iPhone 3G S</a>. Check it out to find out the details, and what those new features might mean for us developers.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/a-huge-leap-forward-graphics-on-the-iphone-3g-s/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remixing OpenGL and UIKit</title>
		<link>http://gamesfromwithin.com/remixing-opengl-and-uikit</link>
		<comments>http://gamesfromwithin.com/remixing-opengl-and-uikit#comments</comments>
		<pubDate>Fri, 30 Jan 2009 17:46:10 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=326</guid>
		<description><![CDATA[Yesterday I wrote about OpenGL views, and how they can be integrated into a complex UI with multiple view controllers. There&#8217;s another interesting aspect of integrating OpenGL and UIKit, and that&#8217;s moving images back and forth between the two systems. &#8230; <a href="http://gamesfromwithin.com/remixing-opengl-and-uikit">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Yesterday I wrote about <a href="http://gamesfromwithin.com/?p=318">OpenGL views</a>, and how they can be integrated into a complex UI with multiple view controllers. There&#8217;s another interesting aspect of integrating OpenGL and UIKit, and that&#8217;s moving images back and forth between the two systems. In both cases, the key enabler is the CGContext class.</p>
<h2>From UIKit to OpenGL</h2>
<p>This is definitely the most common way of sharing image data. Loading an image from disk in almost any format is extremely easy with Cocoa Touch. In fact, it couldn&#8217;t get any easier:</p>
<pre>UIImage* image = [UIImage imageNamed:filename];</pre>
<p>After being used to image libraries like <a href="http://openil.sourceforge.net/">DevIL</a>, it&#8217;s quite a relief to be able to load a file with a single line of code and no chance of screwing anything up. So it makes a lot of sense to use this as a starting point for loading OpenGL textures. So far we have a UIImage. How do we get from there to a texture?</p>
<p>All we have to do is create a CGContext with the appropriate parameters, and draw the image onto it:</p>
<pre>byte* textureData = (byte *)malloc(m_width * m_height * 4);
CGContext* textureContext = CGBitmapContextCreate(textureData, m_width, m_height, 8, m_width * 4,
            CGImageGetColorSpace(image), kCGImageAlphaPremultipliedLast);
CGContextDrawImage(textureContext, CGRectMake(0.0, 0.0, (CGFloat)m_width, (CGFloat)m_height), image);
CGContextRelease(textureContext);</pre>
<p>At that point, we&#8217;ll have the image information, fully uncompressed in RGBA format in textureData. Creating an OpenGL texture from that is done like we always do:</p>
<pre>glGenTextures(1, &amp;m_handle);
glBindTexture(GL_TEXTURE_2D, m_handle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);</pre>
<p>And we&#8217;re done.</p>
<p>A word of advice: This is a quick way to load textures and get started, but it&#8217;s not the ideal way I would recommend for a shipping product. This code is doing a lot of work behind the scenes: loading the file, decompressing the image into an RGBA array, allocating memory, copying it over to OpenGL, and, if you set the option, generating mipmaps. All of this at load time. Ouch! If you have more than a handful of textures, that&#8217;s going to be a pretty noticeable delay while loading.</p>
<p>Instead, it would be much more efficient to perform all the work offline, and prepare the image into the final format that you want to use with OpenGL. Then you can load that data directly into memory and call glTextImage2D on it directly. Not as good as having direct access to video memory and loading it there directly, but that&#8217;s as good as it&#8217;s going to get on the iPhone. Fortunately Apple provides a command-line tool called texturetool that does exactly that, including generating mipmaps.</p>
<p>Another use of transferring image data from UIKit to OpenGL beyond loading textures is to use the beautiful and full-featured font rendering in UIKit in OpenGL applications. To do that, we render a string into the CGContext:</p>
<pre>CGColorSpaceRef    colorSpace = CGColorSpaceCreateDeviceGray();
int sizeInBytes = height*width;
void* data = malloc(sizeInBytes);
memset(data, 0, sizeInBytes);
CGContextRef context = CGBitmapContextCreate(data, width, height, 8, width, colorSpace, kCGImageAlphaNone);
CGColorSpaceRelease(colorSpace);
CGContextSetGrayFillColor(context, grayColor, 1.0);
CGContextTranslateCTM(context, 0.0, height);
CGContextScaleCTM(context, 1.0, -1.0);
UIGraphicsPushContext(context);
    [txt drawInRect:CGRectMake(destRect.left, destRect.bottom, destRect.Width(), destRect.Height()) withFont:font
                                lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
UIGraphicsPopContext();</pre>
<p>There are a couple things that are a bit different about this. First of all, notice that we&#8217;re using a gray color space. That&#8217;s because we&#8217;re rendering the text into a grayscale, alpha-only texture. Otherwise, a full RGBA texture would be a waste. Then there&#8217;s all the transform stuff thrown in the middle. That&#8217;s because the coordinate system for OpenGL is flipped with respect to UIKit, so we need to inverse the y.</p>
<p>Finally, we can create a new texture from that data, or update an existing texture:</p>
<pre>glBindTexture(GL_TEXTURE_2D, m_handle);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0,0, m_width, m_height, GL_ALPHA, GL_UNSIGNED_BYTE, data);</pre>
<h2>From OpenGL to UIKit</h2>
<p>This is definitely the more uncommon way of transferring image data. You would use this when saving something rendered with OpenGL back to disk (like game screenshots), or even when using OpenGL-rendered images on UIKit user interface elements, like I&#8217;m doing in my project.</p>
<p>The process is very similar to the one we just went over, but backwards, with a CGContext as the middleman.</p>
<p>We first start by rendering whatever image we want. You can do this from the back buffer, or from a different render target. I don&#8217;t know that it makes a difference in performance either way (these are not fast operations, so don&#8217;t try to do them every frame!). Then you capture the pixels from the image you just rendered into a plain array:</p>
<pre>unsigned char buffer[width*(height+30)*4];
glReadPixels(0,0,width,height,GL_RGBA,GL_UNSIGNED_BYTE, &amp;buffer);</pre>
<p>By the way, notice the total awesomeness of the array declaration with non-constant variables. Thank you <a href="http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html">C99</a> (and gcc). Of course, that might not be the best thing to do with large images, since you might blow the stack size, but that&#8217;s another issue.</p>
<p>Anyway, once you have those pixels, you need to go through the slightly convoluted CGContext again to put it in a format that can be consumed directly by UIImage like this:</p>
<pre>CGImageRef iref = CGImageCreate(width,height,8,32,width*4,CGColorSpaceCreateDeviceRGB(),
                            kCGBitmapByteOrderDefault,ref,NULL, true, kCGRenderingIntentDefault);
uint32_t* pixels = (uint32_t *)malloc(imageSize);
CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width*4, CGImageGetColorSpace(iref),
                            kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Big);
CGContextTranslateCTM(context, 0.0, height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0.0, 0.0, width, height), iref);   
CGImageRef outputRef = CGBitmapContextCreateImage(context);
UIImage* image = [[UIImage alloc] initWithCGImage:outputRef];
free(pixels);</pre>
<p>Again, we do the same flip of the y axis to avoid having inverted images.</p>
<p>Here the trickiest part was getting the color spaces correct. Apparently, even though it looks very flexible, the actual combinations supported in <span class="entry-content">CGBitmapContextCreate <a href="http://developer.apple.com/qa/qa2001/qa1037.html">are pretty limited</a>. I kept getting errors because I kept passing an alpha channel combination that it didn&#8217;t like.</span></p>
<p>At this point, you&#8217;ll have the OpenGL image loaded an a UIImage, and you can do anything you want with it: Slap it on a button, save it to disk, or anything that strikes your fancy.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/remixing-opengl-and-uikit/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using Multiple OpenGL Views And UIKit</title>
		<link>http://gamesfromwithin.com/using-multiple-opengl-views-and-uikit</link>
		<comments>http://gamesfromwithin.com/using-multiple-opengl-views-and-uikit#comments</comments>
		<pubDate>Fri, 30 Jan 2009 04:28:48 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=318</guid>
		<description><![CDATA[The iPhone includes OpenGL ES for graphics rendering (thank you Apple for not coming up with a custom API!). Specifically, it uses OpenGL ES 1.1 plus a few extensions. It's all very familiar and standard, except for the actual setup, which requires some integration with the iPhone UI.

The now gone CrashLander sample, in spite of some atrocious code, was the best example on how to get a simple, OpenGL app on the iPhone. It covered the basics: creating an OpenGL frame buffer, loading some textures, drawing some polys, and presenting the result to the screen. It was very useful because it was a very small and concise and it made for a great starting point for any OpenGL-based app.

Unfortunately, because it was so basic, it didn't show how OpenGL can play with the rest of UIKit user interface. Instead, it took the approach from many games of taking control of the full screen and viewing it a a single resource. That's fine as long as you're making those kind of games, but I found myself having to mix OpenGL and UIKit quite a bit in my current project. And eventually, I even had to use multiple OpenGL views in different parts of the app. <a href="http://gamesfromwithin.com/using-multiple-opengl-views-and-uikit">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The iPhone includes OpenGL ES for graphics rendering (thank you Apple for not coming up with a custom API!). Specifically, it uses <a href="http://www.khronos.org/opengles/sdk/1.1/docs/man/">OpenGL ES 1.1</a> plus a few extensions. It&#8217;s all very familiar and standard, except for the actual setup, which requires some integration with the iPhone UI.</p>
<p>The now gone CrashLander sample, in spite of some atrocious code, was the best example on how to get a simple, OpenGL app on the iPhone. It covered the basics: creating an OpenGL frame buffer, loading some textures, drawing some polys, and presenting the result to the screen. It was very useful because it was a very small and concise and it made for a great starting point for any OpenGL-based app.</p>
<p>Unfortunately, because it was so basic, it didn&#8217;t show how OpenGL can play with the rest of UIKit user interface. Instead, it took the approach from many games of taking control of the full screen and viewing it a a single resource. That&#8217;s fine as long as you&#8217;re making those kind of games, but I found myself having to mix OpenGL and UIKit quite a bit in my current project. And eventually, I even had to use multiple OpenGL views in different parts of the app.</p>
<h2>Single OpenGL View</h2>
<p>To render with OpenGL to a view, you have to first set the class-static method +layerClass so it creates the right type of layer. Specifically, we need a CAEAGLLayer:</p>
<pre>+ (Class)layerClass
{
    return [CAEAGLLayer class];
}</pre>
<p>You can create a view of that type in code, or you can lay it out on the Interface Builder. I actually like the Interface Builder quite a bit, so that&#8217;s how I end up creating all of mine.</p>
<p>Then, you need to create an OpenGL context:</p>
<pre>    m_eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
    [EAGLContext setCurrentContext:m_eaglContext];</pre>
<p>Finally, you need to create a valid frame buffer object from the CAEAGLLayer from the view you just created:</p>
<pre>    glGenFramebuffersOES(1, &amp;buffer.m_frameBufferHandle);
    glGenRenderbuffersOES(1, &amp;buffer.m_colorBufferHandle);
    glGenRenderbuffersOES(1, &amp;buffer.m_depthBufferHandle);

    glBindRenderbufferOES(GL_RENDERBUFFER_OES, buffer.m_colorBufferHandle);
    [m_eaglContext renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:drawable];
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &amp;buffer.m_width);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &amp;buffer.m_height);

    glBindRenderbufferOES(GL_RENDERBUFFER_OES, buffer.m_depthBufferHandle);
    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, buffer.m_width, buffer.m_height);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, buffer.m_colorBufferHandle);

    glBindFramebufferOES(GL_FRAMEBUFFER_OES, buffer.m_frameBufferHandle);
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, buffer.m_colorBufferHandle); 
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, buffer.m_depthBufferHandle)</pre>
<p>It&#8217;s all pretty standard frame buffer OpenGL stuff. The renderBufferStorage:fromDrawable function is the one that actually allocates buffer storage for that particular view.</p>
<p>After that, you&#8217;re home free and you can use OpenGL the way you&#8217;ve always done. The only difference is that to present, you call this functions instead:</p>
<pre>    [m_eaglContext presentRenderbuffer:GL_RENDERBUFFER_OES];</pre>
<p>Done.</p>
<h2>Integrating OpenGL and UIKit</h2>
<p>After you have the basic OpenGL app set up, you can treat it as a full-screen, exclusive resource and do all your output through it. That works fine for a lot of games, but there are a lot of games and apps that benefit from using some amount of UIKit functionality. After all, UIKit is a great UI API, and it seems like a shame to reinvent it all if it&#8217;s not necessary.</p>
<p>The good news is that OpenGL rendering is happen in a view, so you can do everything you can do with views: Animate it, do fancy transitions, add them to nav bars or tab bars, etc. The bad news is that, unless you&#8217;re careful, performance will suffer.</p>
<p>Apple has some best practices on what to do with OpenGL views, but it comes down to avoid doing transforms on them (instead, use the transforms in OpenGL), and avoid putting other UIKit elements on top of it, especially transparent ones. Although, I seem to be able to get away with small buttons and such without affecting the frame rate, so that&#8217;s always a plus.</p>
<p>So having realized that, now you can make your application transition between the OpenGL view, and other views. Maybe you have a table view with settings, or some sort of UIKit dialog box, or a high-score table. You can safely do all of that with UIKit (and add your own graphics and custom rendering if you want to give it a totally different look).</p>
<p>One thing to watch out for: Whenever your OpenGL view isn&#8217;t visible, make sure to stop doing frame updates (for simulation and rendering). Otherwise, the rest of the UI is going to be very unresponsive (and you might not find that out until you run it on the device, because the simulator is very fast). The UIViewController viewWillAppear and viewDidDisappear functions are perfect to find out when you should start and stop frame updates.</p>
<h2>Multiple Views</h2>
<p>Things get more complicated when you want to have multiple views with OpenGL rendering. I don&#8217;t mean multiple viewports in the same screen, but multiple views in the sense of multiple UIViews. My current project, for example, has different views connected with a UITabBarController. Some of the are custom UIViews and some of them are OpenGL views.</p>
<p>My first thought was to try to have different OpenGL contexts for each view, but that would complicate things because I wanted to share the same textures and other resources. I know there&#8217;s a shared groups option, but that was definitely not the way to go.</p>
<p>The best solution I found was to use multiple frame buffers, binding each of them to the correct OpenGL view. That way, when I switch views, I switch frame buffers and everything works correctly.</p>
<p>On the -viewDidLoad function for each view controller with an OpenGL view, I call the function listed above to create a new frame buffer bound to that view, and it returns an index. Then, in the -viewWillAppear function, I set the frame buffer corresponding to that index:</p>
<pre>    const FrameBuffer&amp; buffer = m_frameBuffers[bufferIndex];
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, buffer.m_frameBufferHandle);   
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, buffer.m_colorBufferHandle);
    glViewport(....);</pre>
<p>That&#8217;s it. Now you can switch between different OpenGL views and UIKit views without any problems. Just make sure to only render the visible views! That can be trickier than it sounds because the viewWillAppear and viewDidDisappear functions only get called for views that were layed out in the Interface Builder. If you added them by hand, you need to call those methods yourself (why??!?!). So keep tabs on that, otherwise everything will slow down to a halt.</p>
<h2>And To Wrap It Up&#8230;</h2>
<p>You thought I had forgotten about the promise to slowly unveil art from my current project, uh? Fear not, here comes the next teaser. This is an actually screenshot taken a minute ago. Incidentally, this is not one of the views using OpenGL. We&#8217;ll have to save those for another day <img src='http://gamesfromwithin.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><img class="size-full wp-image-320 alignnone" title="screenshot" src="http://gamesfromwithin.com/wp-content/uploads/2009/01/screenshot.jpg" alt="screenshot" width="160" height="215" /></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/using-multiple-opengl-views-and-uikit/feed</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
	</channel>
</rss>

