<?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>Hook - Labs</title>
	<atom:link href="http://labs.byhook.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://labs.byhook.com</link>
	<description>Flash Scripts, Tools &#38; Methods Developed During Production at Hook</description>
	<lastBuildDate>Mon, 26 Sep 2011 14:37:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Vector Metaballs</title>
		<link>http://labs.byhook.com/2011/09/26/vector-metaballs/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=vector-metaballs</link>
		<comments>http://labs.byhook.com/2011/09/26/vector-metaballs/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 14:36:51 +0000</pubDate>
		<dc:creator>Parker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Actionscript 3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Meta Balls]]></category>
		<category><![CDATA[Vectors]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1659</guid>
		<description><![CDATA[Metaballs, everyone's favorite computer-generated globby blobs , have been around for a while. They're the product of a rush of innovation in computer graphics during the 1980's by the likes of <a href="http://en.wikipedia.org/wiki/Ken_Perlin">Ken Perlin</a>, <a href="http://en.wikipedia.org/wiki/Bui_Tuong_Phong">Bui Tuong Phong</a>, and <a href="http://en.wikipedia.org/wiki/Jim_Blinn">Jim Blinn</a>, when computer graphics began recognizing the need for organic shapes and shaders. The algorithm has been implemented countless times and can be astoundingly efficient and simple; the hardest part is finding something useful for them. Here is our take on it.]]></description>
			<content:encoded><![CDATA[<p>Metaballs, everyone&#8217;s favorite computer-generated globby blobs , have been around for a while. They&#8217;re the product of a rush of innovation in computer graphics during the 1980&#8242;s by the likes of <a href="http://en.wikipedia.org/wiki/Ken_Perlin">Ken Perlin</a>, <a href="http://en.wikipedia.org/wiki/Bui_Tuong_Phong">Bui Tuong Phong</a>, and <a href="http://en.wikipedia.org/wiki/Jim_Blinn">Jim Blinn</a>, when computer graphics began recognizing the need for organic shapes and shaders. The algorithm has been implemented countless times and can be astoundingly efficient and simple; the hardest part is finding something useful for them. Here is our take on it.</p>
<p><span id="more-1659"></span></p>
<h4>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_MetaballDemo_2080300040"
			class="flashmovie"
			width="900"
			height="540">
	<param name="movie" value="http://labs.byhook.com/meta/flash/MetaballDemo.swf" />
	<param name="bgcolor" value="#ffffff" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://labs.byhook.com/meta/flash/MetaballDemo.swf"
			name="fm_MetaballDemo_2080300040"
			width="900"
			height="540">
		<param name="bgcolor" value="#ffffff" />
	<!--<![endif]-->
		
<p><a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>

	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
</h4>
<p><a href="http://labs.byhook.com/meta/MetaballDemo.zip">Download the source for all of these demos here.</a></p>
<p>There are several parts to this demo, and I&#8217;m going to give credit where its due right now. The first part is the vector rendering of the metaballs; the real innovator here is <a href="http://www.niksula.hut.fi/~hkankaan/Homepages/index.html">Hannu Kankaanpää</a>, who has a <strong>great</strong> <a href="http://www.niksula.hut.fi/~hkankaan/Homepages/metaballs.html">write up</a> on a clever rendering algorthim, which I&#8217;ve adapted from Python to ActionScript. The second part is the eye-candy, the pixel shader. The folks over at <a href="http://omino.com/">omino</a> made <a href="http://omino.com/pixelblog/2010/04/21/ae-omino-glass-a-pixel-bender-filter/">this</a> spiffy distortion/chromatic aberration filter for AfterEffects, which I then adapted to run in Flash&#8217;s crippled PixelBender environment. I&#8217;m not totally satisfied with my conversion, but it does the job. I won&#8217;t be going over the details of the refraction, but the PixelBender source file is included.</p>
<p><em>Pro-tip: Right click on any of these demos for an option to turn on a profiler, so you can watch the performance.</em></p>
<p><strong>Fields of Metaballs</strong></p>
<p>So what is a metaball really? The mathematical terms for a metaball are either an <em>isoline</em> (two dimensional) or an <em>isosurface</em> (three dimensional). This demo only explores the two dimensional aspects. Isolines are analogous to a <em>contour map</em>; the center of each metaball is like the peak of a mountain, and the line formed by them is the contour of an elevation on that mountain. As those peaks get closer together, they begin to merge and a bridge emerges. If they sit on top of each other, they form one extra large mountain. In this demo, the graph on the top is like a side-view of the system; the metaballs on the bottom can be thought of as a cross-section of that system.</p>
<h4>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_MetaballGrapher_1669090357"
			class="flashmovie"
			width="900"
			height="320">
	<param name="movie" value="http://labs.byhook.com/meta/flash/MetaballGrapher.swf" />
	<param name="bgcolor" value="#ffffff" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://labs.byhook.com/meta/flash/MetaballGrapher.swf"
			name="fm_MetaballGrapher_1669090357"
			width="900"
			height="320">
		<param name="bgcolor" value="#ffffff" />
	<!--<![endif]-->
		
<p><a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>

	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
</h4>
<p>Mathematically, each metaball in the system has a position ( <img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_986.5_45ec3bb7ec6e7253069da2edb16a87d7.png" style="vertical-align:-13.5px; display: inline-block ;" alt="p_n" title="p_n"/> ) and a strength ( <img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_986.5_c47e1c97f9e43fd8e930781471d6a6c1.png" style="vertical-align:-13.5px; display: inline-block ;" alt="s_n" title="s_n"/> ), and the system as a whole has a &#8220;gooiness&#8221; constant ( <img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_994.5_5c385d6d334ea0a9301bd28ea067aba7.png" style="vertical-align:-5.5px; display: inline-block ;" alt="c" title="c"/> ). We can find the strength (or elevation, in our analogy) of a particular point ( <img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_994.5_d3d078bf2fc1425e6d4410ccb6ed6df9.png" style="vertical-align:-5.5px; display: inline-block ;" alt="p" title="p"/> ) by plugging everything in to a fall-off function for each metaball in the system, and summing the results. In our implementation, the fall-off function is</p>
<p style="text-align: center;"><img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_958_a3d0fd2de3194d1ebfac478415919ebf.png" style="vertical-align:-42px; display: inline-block ;" alt="{s_n}/{delim{vert}{~vec{p_n}~-~vec{p}~}{vert}}^{~c}" title="{s_n}/{delim{vert}{~vec{p_n}~-~vec{p}~}{vert}}^{~c}"/></p>
<p>This formula might look familiar; when <img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_994.5_9c259be4a53bcf3a521d16a64140bf29.png" style="vertical-align:-5.5px; display: inline-block ;" alt="c = 2" title="c = 2"/> it is an inverse square relationship, or basically <a href="http://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation">Newtonian attraction</a>. Really any fall-off function could be used, as long as it is smooth and has a domain of <img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_995.5_7aa9f1784354a4e48c29b050736904aa.png" style="vertical-align:-4.5px; display: inline-block ;" alt="~bbR" title="~bbR"/>, and there are some that are more efficient by leaving out the division. But, with some tricks in the code, this one does just fine.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Check the strength of this metaball on a point in space.
 * @param	v	The point to check against.
 * @param	c	The exponential constant of the field.
 * @return	The strength of this metaball's field at the point.
 */</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> strengthAt<span style="color: #66cc66;">&#40;</span>v:Vector2D, c:<span style="color: #0066CC;">Number</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> div:<span style="color: #0066CC;">Number</span> = <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">pow</span><span style="color: #66cc66;">&#40;</span> Vector2D.<span style="color: #006600;">subtract</span><span style="color: #66cc66;">&#40;</span>_position, v<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">lengthSq</span>, c <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">0.5</span> <span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">return</span> <span style="color: #66cc66;">&#40;</span>div <span style="color: #66cc66;">!</span>= <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> ? <span style="color: #66cc66;">&#40;</span>_strength <span style="color: #66cc66;">/</span> div<span style="color: #66cc66;">&#41;</span> : <span style="color: #cc66cc;">10000</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Rendering with Vectors</strong></p>
<p>A regular brute-force metaball renderer would operate by taking this formula and solving it for each pixel or voxel in the system. People have also cheated the effect in Flash using a variety of BitmapData tricks; generally something like drawing circles, applying a strong blur filter and then using <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html#threshold()">BitmapData.threshold()</a>. This can work really well; just look at <a href="http://www.patrickmatte.com/stuff/physicsLiquid/">this</a> awesome demo. Hannu&#8217;s approach is a little more complex, but very optimized for the CPU. It also has the unique benefit of having a <em>vector output</em>, which can come in handy given that most of Flash is vector based.</p>
<p>To explain how it works, lets return to our contour map analogy. Suppose you were in a mountain range and wanted to find the contour at around 500 feet elevation. One approach would involve standing on each square foot of dirt and measuring the elevation and then plotting those elevations on some kind of grid. This would be easy and fast if you had thousands of people with you to simultaneously measure each of those square foot plots. But if you&#8217;re all alone, like the CPU is, you need a more straightforward approach. Instead, you start at the top of one of the mountains, and descend in any direction until you reach 500 feet elevation. Then you start walking in either direction, never going up or down, only around. When you return to the spot you started at, you&#8217;ve successfully plotted the 500 foot elevation contour for that mountain (and any other mountain peaks you walked around). Instead of evaluating every square foot in the mountain range, you only make one evaluation per step you take.</p>
<p>This introduces some unique complexity issues; a GPU solution has a fixed complexity for a certain resolution and number of metaballs, whereas Hannu&#8217;s algorithm changes in complexity based on the position of the metaballs. There are also additional problems, such as how far each step should be, how many steps to take before you &#8220;give up,&#8221; and how to tell when you&#8217;re done. I&#8217;m not going to post the whole rendering algorithm here; it is messy, a bit long, and not particularly insightful. There are two loops; in the first loop, the algorithm locates a point on the edge of each metaball. The second loop traces the field normal (using second order Runge-Kutta) between the edge points found in the first loop, like a set of dominoes falling into each other. At every step, we write a coordinate to a graphics object, and end with a tidy, convenient <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/GraphicsPath.html">GraphicsPath</a> object. What&#8217;s the point? Well, that&#8217;s up to you, but here is something you could never do with a pixel-based renderer:</p>
<h4>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_MetaballRacetrack_179978299"
			class="flashmovie"
			width="900"
			height="400">
	<param name="movie" value="http://labs.byhook.com/meta/flash/MetaballRacetrack.swf" />
	<param name="bgcolor" value="#ffffff" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://labs.byhook.com/meta/flash/MetaballRacetrack.swf"
			name="fm_MetaballRacetrack_179978299"
			width="900"
			height="400">
		<param name="bgcolor" value="#ffffff" />
	<!--<![endif]-->
		
<p><a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>

	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
</h4>
<p><strong>There&#8217;s Always a Downside</strong></p>
<p>The biggest issue is the stability. Just like dominoes, sometimes things don&#8217;t line up quite right. Its a natural problem with a less rigorous approach, and there isn&#8217;t much to do about except adding additional error-checking and more generous tolerances. I developed the system for an application that would use four or five metaballs at most, and for that, the system is relatively stable. But&#8230;add enough metaballs to the stress test below, and things will start to go haywire; spiraling edges, inversions, the works. Another downside is recognized by Hannu; in certain configurations, a set of three or more metaballs can form a donut-like shape. A rigorous evaluation would show a hole in the middle, but this edge tracing technique may miss it some frames and pick it up in others. I think it could be addressed if it was a huge issue for a certain application, but in general it seems pretty unlikely.</p>
<p>The performance is decent on Flash Player 10, and I&#8217;m sure some keen eyes could find plenty of room for optimization. Turn on the profiler on the stress test below (its in the right click menu) and see how much you can break it!</p>
<h4>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_MetaballStresser_2026217404"
			class="flashmovie"
			width="900"
			height="500">
	<param name="movie" value="http://labs.byhook.com/meta/flash/MetaballStresser.swf" />
	<param name="bgcolor" value="#000000" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://labs.byhook.com/meta/flash/MetaballStresser.swf"
			name="fm_MetaballStresser_2026217404"
			width="900"
			height="500">
		<param name="bgcolor" value="#000000" />
	<!--<![endif]-->
		
<p><a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>

	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
</h4>
<p><a href="http://labs.byhook.com/meta/MetaballDemo.zip">Download the source for all of these demos here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/09/26/vector-metaballs/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Go Go Gadget Flow</title>
		<link>http://labs.byhook.com/2011/05/25/go-go-gadget-flow/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=go-go-gadget-flow</link>
		<comments>http://labs.byhook.com/2011/05/25/go-go-gadget-flow/#comments</comments>
		<pubDate>Wed, 25 May 2011 14:29:03 +0000</pubDate>
		<dc:creator>Parker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flow]]></category>
		<category><![CDATA[Menu]]></category>
		<category><![CDATA[Nav]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1602</guid>
		<description><![CDATA[A cover flow is a great way to display and browse through discrete content. It feels like flipping through a magazine: easy and fast, but informative. Its a natural addition to many user interfaces, but many existing implementations are like black boxes with strict display rules. You add in your elements, and you end up with iTunes 7. We needed something more generic and reusable; those were the priorities. We take a look at the built in <em>transform</em> property of a <em>DisplayObject</em>, and how that can be used to build an flexible flow]]></description>
			<content:encoded><![CDATA[<p>A cover flow is a great way to display and browse through discrete content. It feels like flipping through a magazine: easy and fast, but informative. Its a natural addition to many user interfaces, but many existing implementations are like black boxes with strict display rules. You add in your elements, and you end up with iTunes 7. We needed something more generic and reusable; those were the priorities. We take a look at the built in <em>transform</em> property of a <em>DisplayObject</em>, and how that can be used to build an flexible flow.<span id="more-1602"></span></p>
<h4 style="font-size: 1em">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_FlowDemo_2140236430"
			class="flashmovie"
			width="900"
			height="250">
	<param name="movie" value="/flow/FlowDemo.swf" />
	<param name="bgcolor" value="#FFFFFF" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="/flow/FlowDemo.swf"
			name="fm_FlowDemo_2140236430"
			width="900"
			height="250">
		<param name="bgcolor" value="#FFFFFF" />
	<!--<![endif]-->
		<a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial;" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><br />
</h4>
<p><a href="http://labs.byhook.com/flow/flowdemo.zip">Download the files here.</a></p>
<p><strong>Breaking It Down</strong></p>
<p>The flow can be broken into several pieces. The main class, called a <em>Flow</em>, handles things like user input, positioning of the elements, and z-sorting. Inside a <em>Flow</em> is an array of <em>FlowContainer</em>&#8216;s, which is really where the magic happens. The <em>FlowContainer</em> actually encapsulates various transformations, and applies a percentage of those transformations to itself based on the position of the mouse within the <em>Flow</em>. Both the <em>Flow</em> and <em>FlowContainer</em> extend <em>MovieClip</em>, and this means that any <em>DisplayObject</em> can be added as a child to the <em>FlowContainer</em> and it will inherit its various transformations.</p>
<p>Wow, that was abstract. What do I mean when I say <em>FlowContainer</em> encapsulates transformations? Every <em>DisplayObject</em> has a property <a title="flash.display.DisplayObject#transform" href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#transform"><em>transform</em> </a>which holds various information about the object&#8217;s position and color. I&#8217;ll make an example with a transformation matrix, which is a three by three matrix. The template of the matrix is:</p>
<p style="text-align: center;"><img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_956.5_7b8d6d0418fb24dddf3886c063870ef4.png" style="vertical-align:-43.5px; display: inline-block ;" alt="delim{[}{~matrix{3}{3}{a c t_x b d t_y u v w}~}{]}" title="delim{[}{~matrix{3}{3}{a c t_x b d t_y u v w}~}{]}"/></p>
<p>The elements <em>a, b, c, </em>and <em>d</em> control the scaling of the <em>DisplayObject</em>, while <em>tx</em> and <em>ty</em> control the translation of the <em>DisplayObject</em>. The <em>u, v,</em> and <em>w</em> usually provide additional information if its needed, but in a standard two dimensional transformation they are unnecessary. The most basic transfomation matrix is the identity matrix. The identity matrix, when applied to the object, does absolutely nothing.</p>
<p style="text-align: center;"><img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_971.5_d67fb2fcb18eebaebdc543e1ee203469.png" style="vertical-align:-28.5px; display: inline-block ;" alt="delim{[}{~matrix{3}{3}{1 0 0 0 1 0 0 0 1}~}{]}" title="delim{[}{~matrix{3}{3}{1 0 0 0 1 0 0 0 1}~}{]}"/></p>
<p>Now, lets say we want to translate, or move, the object 56 pixels to the right and 32 pixels down. The transformation matrix we would use is,</p>
<p style="text-align: center;"><img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_971.5_ea72d9f43c2b92f068e5c2f9c56afd1b.png" style="vertical-align:-28.5px; display: inline-block ;" alt="delim{[}{~matrix{3}{3}{1 0 56 0 1 32 0 0 1}~}{]}" title="delim{[}{~matrix{3}{3}{1 0 56 0 1 32 0 0 1}~}{]}"/>;</p>
<p>Easy. Scaling is similar, and uses <em>a</em> to scale horizontally and <em>d</em> to scale vertically. So to make our object 4.4 times wider and 2.6 times taller, we would use,</p>
<p style="text-align: center;"><img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_971.5_8a10f4f8869d67e043cc63acf06ac616.png" style="vertical-align:-28.5px; display: inline-block ;" alt="delim{[}{~matrix{3}{3}{4.4 0 56 0 2.6 32 0 0 1}~}{]}" title="delim{[}{~matrix{3}{3}{4.4 0 56 0 2.6 32 0 0 1}~}{]}"/>;</p>
<p>Note that the translation is still there, now its just scaling at the same time. Rotation is the strangest, because its actually a compound operation. Without getting too mathy, the elements <em>a</em> and <em>d</em> of the array control scale and the elements <em>c</em> and <em>b</em> control skew. If you do both operations at the same time, you can rotate the object. I&#8217;m going to remove the  scaling from the previous matrix for clarity. If we wanted to rotate the <em>DisplayObject</em> by 70 degrees (about 1.2 radians) we would use,</p>
<p style="text-align: center;"><img src="http://labs.byhook.com/wp-content/plugins/wpmathpub/phpmathpublisher/img/math_941.5_c239e721ed09299ed410bb6c3670e8c5.png" style="vertical-align:-58.5px; display: inline-block ;" alt="delim{[}{~matrix{3}{3}{{cos(1.2)} {-sin(1.2)} 56 {sin(1.2)} {cos(1.2)} 32 0 0 1}~}{]}" title="delim{[}{~matrix{3}{3}{{cos(1.2)} {-sin(1.2)} 56 {sin(1.2)} {cos(1.2)} 32 0 0 1}~}{]}"/>;</p>
<p>Let&#8217;s look at all this nonsense in action to drive the point home.</p>
<h4 style="font-size: 1em">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_InteractiveMatrix_932894598"
			class="flashmovie"
			width="900"
			height="210">
	<param name="movie" value="/flow/InteractiveMatrix.swf" />
	<param name="bgcolor" value="#FFFFFF" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="/flow/InteractiveMatrix.swf"
			name="fm_InteractiveMatrix_932894598"
			width="900"
			height="210">
		<param name="bgcolor" value="#FFFFFF" />
	<!--<![endif]-->
		<a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial;" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><br />
</h4>
<p>There, that&#8217;s a little more interesting. Try manipulating <em>a, b, c, </em>and <em>d</em> to make the box kind of rotate. Also, note that <em>a, b, c, </em>and <em>d</em> are all relative to the blue box&#8217;s registration point in the top left, while <em>tx</em> and <em>ty</em> are the translation from the <strong>parent&#8217;s</strong> registration point to the child&#8217;s registration point. Why does this happen? If <em>tx</em> is 56 and <em>ty</em> is 32, why isn&#8217;t the blue box at pixel (56, 32)? This is because the when the display object is rendering, it doesn&#8217;t stop at its own transformation matrix. It actually traverses up the display list and concatenates (multiplies) each and every transformation matrix above it to find an absolute transformation matrix relative to the stage. The inverse of this is that if we change the transformation matrix of a <em>DisplayObject</em>, all of the children of the object inherit that transformation.</p>
<p><strong>Go with the Flow</strong></p>
<p>Back to flows. How can we use all these transformations to make a cool effect like the cover flow? We can think of each <em>FlowContainer</em> in the <em>Flow</em> as having two appearances. One is when its out of focus, or off to the side. The other is when it is in focus, either in the center of the screen (like in the classic cover flow) or directly underneath the mouse (like in our flow example). If we define those two appearances as matrices, we can easily interpolate between the appearances based on whatever input we&#8217;re using (the mouse, a slider, arrow keys, etc.). For basic transformations, our <em>FlowContainer</em> class keeps track of four variables.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> lerp:<span style="color: #0066CC;">Number</span>; <span style="color: #808080; font-style: italic;">// the percentage of the effect currently being applied</span>
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> positioning:Matrix; <span style="color: #808080; font-style: italic;">// the original position of the object, letting our transformations be relative</span>
&nbsp;
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> transformNone:Matrix; <span style="color: #808080; font-style: italic;">// the relative transformation when lerp is 0</span>
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> transformFull:Matrix; <span style="color: #808080; font-style: italic;">// the relative transformation when lerp is 1</span></pre></div></div>

<p>To set the values of these, we use a single method with some constants for context.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Bind a transformation matrix to either the near or far appearence of the 
 * container. To specify whether the transformation happens near or away from 
 * the mouse, set the distance parameter to either Flow.NEAR_EFFECT or Flow.FAR_EFFECT.
 * @param	value		the transformation matrix to be bound
 * @param	distance	the distance constant at which the transformation is applied
 */</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> bindTransformEffect<span style="color: #66cc66;">&#40;</span>value:Matrix, distance:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>distance == Flow.<span style="color: #006600;">NEAR_EFFECT</span><span style="color: #66cc66;">&#41;</span>
		transformFull = value.<span style="color: #006600;">clone</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>distance == Flow.<span style="color: #006600;">FAR_EFFECT</span><span style="color: #66cc66;">&#41;</span>
		transformNone = value.<span style="color: #006600;">clone</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #b1b100;">else</span>
		<span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> TypeError<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;The distance must be either Flow.NEAR_EFFECT or Flow.FAR_EFFECT&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	synchronize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>After these are set, we use <em>synchronize()</em> to match the appearance of the container with whatever matrices were set.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> synchronize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> lerpedTransform:Matrix;
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>lerp <span style="color: #66cc66;">!</span>= <span style="color: #cc66cc;">0.0</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		lerpedTransform = Util.<span style="color: #006600;">lerpMatrix</span><span style="color: #66cc66;">&#40;</span>lerp, transformNone, transformFull<span style="color: #66cc66;">&#41;</span>;
		lerpedTransform.<span style="color: #0066CC;">concat</span><span style="color: #66cc66;">&#40;</span>positioning<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// make the transformation relative to the original position</span>
	<span style="color: #66cc66;">&#125;</span>
	<span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">// transformNone is cloned because otherwise the concat operation would compound</span>
		lerpedTransform = transformNone.<span style="color: #006600;">clone</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		lerpedTransform.<span style="color: #0066CC;">concat</span><span style="color: #66cc66;">&#40;</span>positioning<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	transform.<span style="color: #006600;">matrix</span> = lerpedTransform;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>There are two things to especially take note of in that code block. The first is at <em>Util.lerpMatrix()</em>, where we use linear interpolation between <em>transformNone</em> and <em>transformFull</em>. This is kind of bad, because linear interpolation doesn&#8217;t handle rotation correctly. But, it is a heck of a lot faster and easier than the alternatives: quaternions, slerping, or matrix decomposition/recomposition. If you&#8217;re like us and only need to use scaling and translation, here is the linear interpolation algorithm.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">function</span> lerpMatrix<span style="color: #66cc66;">&#40;</span>value:<span style="color: #0066CC;">Number</span>, low:Matrix, high:Matrix<span style="color: #66cc66;">&#41;</span>:Matrix
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>value <span style="color: #66cc66;">&lt;</span> <span style="color: #cc66cc;">0.0</span> <span style="color: #66cc66;">||</span> value <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">1.0</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> RangeError<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;The lerp value must be a percentage between 0.0 and 1.0.&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #000000; font-weight: bold;">var</span> result:Matrix = <span style="color: #000000; font-weight: bold;">new</span> Matrix<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	result.<span style="color: #006600;">a</span> = value <span style="color: #66cc66;">*</span> <span style="color: #66cc66;">&#40;</span>high.<span style="color: #006600;">a</span> - low.<span style="color: #006600;">a</span><span style="color: #66cc66;">&#41;</span> + low.<span style="color: #006600;">a</span>;
	result.<span style="color: #006600;">b</span> = value <span style="color: #66cc66;">*</span> <span style="color: #66cc66;">&#40;</span>high.<span style="color: #006600;">b</span> - low.<span style="color: #006600;">b</span><span style="color: #66cc66;">&#41;</span> + low.<span style="color: #006600;">b</span>;
	result.<span style="color: #006600;">c</span> = value <span style="color: #66cc66;">*</span> <span style="color: #66cc66;">&#40;</span>high.<span style="color: #006600;">c</span> - low.<span style="color: #006600;">c</span><span style="color: #66cc66;">&#41;</span> + low.<span style="color: #006600;">c</span>;
	result.<span style="color: #006600;">d</span> = value <span style="color: #66cc66;">*</span> <span style="color: #66cc66;">&#40;</span>high.<span style="color: #006600;">d</span> - low.<span style="color: #006600;">d</span><span style="color: #66cc66;">&#41;</span> + low.<span style="color: #006600;">d</span>;
	result.<span style="color: #006600;">tx</span> = value <span style="color: #66cc66;">*</span> <span style="color: #66cc66;">&#40;</span>high.<span style="color: #006600;">tx</span> - low.<span style="color: #006600;">tx</span><span style="color: #66cc66;">&#41;</span> + low.<span style="color: #006600;">tx</span>;
	result.<span style="color: #006600;">ty</span> = value <span style="color: #66cc66;">*</span> <span style="color: #66cc66;">&#40;</span>high.<span style="color: #006600;">ty</span> - low.<span style="color: #006600;">ty</span><span style="color: #66cc66;">&#41;</span> + low.<span style="color: #006600;">ty</span>;
&nbsp;
	<span style="color: #b1b100;">return</span> result;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>The second thing to take note of is the <em>concat()</em> function, where we concatenate (multiply) the <em>positioning</em> variable onto the transformation. This is because its way easier for whoever is interfacing with this code to define the translations relative to wherever they&#8217;ve placed the object. The tx and ty value can look like 50 and -25, instead of random nonsense like 480 and 312. But, the <em>transform</em> property of the <em>DisplayObject</em> stores transformations relative to its parent, not itself, so we have to take care of that step ourselves.</p>
<p>In addition to transformations, we also store <em><a title="flash.geom.ColorTransform" href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/geom/ColorTransform.html">ColorTransformation</a></em> objects and <em><a title="flash.filters.BlurFilter" href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/filters/BlurFilter.html">BlurFilter</a></em> objects to lerp between and synchronize in our <em>FlowContainer</em>. After seeing how the regular transformations work, hopefully these are pretty easy to understand. Using only the <em>FlowContainer</em> object, we can make something like this:</p>
<h4 style="font-size: 1em">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_FlowContainerDemo_1758260522"
			class="flashmovie"
			width="900"
			height="210">
	<param name="movie" value="/flow/FlowContainerDemo.swf" />
	<param name="bgcolor" value="#FFFFFF" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="/flow/FlowContainerDemo.swf"
			name="fm_FlowContainerDemo_1758260522"
			width="900"
			height="210">
		<param name="bgcolor" value="#FFFFFF" />
	<!--<![endif]-->
		<a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial;" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><br />
</h4>
<p><strong>A Little Organization</strong></p>
<p>The final step is organizing these little nuggets of transformation juju into a usable UI component. Its a lot simpler than you might think; the <em>Flow</em> object only has about three substantial functions. The first step though, is keeping track of the <em>FlowContainer</em>s so that we can iterate through them quickly. After that, adding <em>DisplayObjects</em> is easy.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Add a component to the flow. The component can be anything; if it is not already 
 * a flow container, it will be wrapped in one automatically.
 * @param	item	the component to be added to the flow
 */</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> addComponent<span style="color: #66cc66;">&#40;</span>item:DisplayObject<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> fc:FlowContainer
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">!</span><span style="color: #66cc66;">&#40;</span>item is FlowContainer<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		fc = <span style="color: #000000; font-weight: bold;">new</span> FlowContainer<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		fc.<span style="color: #006600;">addChild</span><span style="color: #66cc66;">&#40;</span>item<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
	<span style="color: #b1b100;">else</span>
		fc = FlowContainer<span style="color: #66cc66;">&#40;</span>item<span style="color: #66cc66;">&#41;</span>;
&nbsp;
	items.<span style="color: #0066CC;">push</span><span style="color: #66cc66;">&#40;</span>fc<span style="color: #66cc66;">&#41;</span>;
	addChild<span style="color: #66cc66;">&#40;</span>fc<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>After all the items are added, we need to put them in their place. We use the variable <em>track</em> here; its just a invisible movie clip that lets us separate the <em>Flow</em>&#8216;s area for interaction from its area for display. A simple spacing algorithm, followed by the z-sorting algorithm:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 * Organizes the flowable items into an even spread along the track.
 */</span>
<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> organize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> item:FlowContainer;
&nbsp;
	<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span> = <span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> items.<span style="color: #0066CC;">length</span>; ++i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		item = <span style="color: #66cc66;">&#40;</span>items<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span> as FlowContainer<span style="color: #66cc66;">&#41;</span>;
&nbsp;
		item.<span style="color: #006600;">x</span> = track.<span style="color: #006600;">x</span> + <span style="color: #66cc66;">&#40;</span> <span style="color: #0066CC;">Number</span><span style="color: #66cc66;">&#40;</span>i + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">/</span> <span style="color: #0066CC;">Number</span><span style="color: #66cc66;">&#40;</span>items.<span style="color: #0066CC;">length</span> + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> track.<span style="color: #0066CC;">width</span>;
		item.<span style="color: #006600;">x</span> -= item.<span style="color: #0066CC;">width</span> <span style="color: #66cc66;">/</span> <span style="color: #cc66cc;">2.0</span>; <span style="color: #808080; font-style: italic;">// center the component in its slot</span>
		item.<span style="color: #006600;">y</span> = track.<span style="color: #006600;">y</span>;
&nbsp;
		item.<span style="color: #006600;">freezePositioning</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// stores the flow containers current position as the start point for any relative transformations</span>
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/**
 * Sorts the z-index of the items based on their distance to the mouse.
 */</span>
<span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> zsort<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span> = <span style="color: #cc66cc;">0</span>;
	<span style="color: #000000; font-weight: bold;">var</span> j:<span style="color: #0066CC;">int</span> = numChildren - <span style="color: #cc66cc;">1</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">// make i the index of the component which should have the highest z-index</span>
	<span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>i <span style="color: #66cc66;">&lt;</span> <span style="color: #66cc66;">&#40;</span>items.<span style="color: #0066CC;">length</span> - <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&amp;&amp;</span> items<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">effectPercent</span> <span style="color: #66cc66;">&lt;</span>= items<span style="color: #66cc66;">&#91;</span>i + <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">effectPercent</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> 		++i; 	<span style="color: #66cc66;">&#125;</span> 	 	<span style="color: #808080; font-style: italic;">/* 	 Move this component to the top of the z-stack. Note that j will then 	 point to the next highest spot on the z-stack because of the post-decrement 	 operator. 	 */</span> 	swapChildren<span style="color: #66cc66;">&#40;</span>items<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>, getChildAt<span style="color: #66cc66;">&#40;</span>j--<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>; 	 	<span style="color: #808080; font-style: italic;">// sort the items left of the middle item 	for (var k_left = i - 1; k_left &gt;= 0; --k_left) {</span>
		swapChildren<span style="color: #66cc66;">&#40;</span>items<span style="color: #66cc66;">&#91;</span>k_left<span style="color: #66cc66;">&#93;</span>, getChildAt<span style="color: #66cc66;">&#40;</span>j--<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">// sort the items right of the middle item</span>
	<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> k_right = i + <span style="color: #cc66cc;">1</span>; k_right <span style="color: #66cc66;">&lt;</span> items.<span style="color: #0066CC;">length</span>; ++k_right<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		swapChildren<span style="color: #66cc66;">&#40;</span>items<span style="color: #66cc66;">&#91;</span>k_right<span style="color: #66cc66;">&#93;</span>, getChildAt<span style="color: #66cc66;">&#40;</span>j--<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Then, we just listen to the mouse and update the <em>FlowContainers</em>. The input could easily be replaced by a slider or arrow buttons for something more infinite.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> moveListener<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">e</span>:MouseEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #808080; font-style: italic;">// relative to the envelope of the flow</span>
	<span style="color: #000000; font-weight: bold;">var</span> mouseX:<span style="color: #0066CC;">Number</span> = <span style="color: #0066CC;">e</span>.<span style="color: #006600;">stageX</span> - <span style="color: #0066CC;">this</span>.<span style="color: #006600;">x</span>;
&nbsp;
	<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span> = <span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> items.<span style="color: #0066CC;">length</span>; ++i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">var</span> distance = <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">abs</span><span style="color: #66cc66;">&#40;</span>items<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">x</span> + items<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>.<span style="color: #0066CC;">width</span> <span style="color: #66cc66;">/</span> <span style="color: #cc66cc;">2.0</span> - mouseX<span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// here, effectNone and effectFull are numbers which indicate the distance from</span>
		<span style="color: #808080; font-style: italic;">// the mouse where there is no effect, and full effect. then it just maps the distance</span>
		<span style="color: #808080; font-style: italic;">// between those and winds up with a percentage.</span>
		<span style="color: #000000; font-weight: bold;">var</span> percent:<span style="color: #0066CC;">Number</span> = Util.<span style="color: #006600;">map</span><span style="color: #66cc66;">&#40;</span> distance, effectNone, effectFull, <span style="color: #cc66cc;">0.0</span>, <span style="color: #cc66cc;">1.0</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		items<span style="color: #66cc66;">&#91;</span>i<span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">effectPercent</span> = Util.<span style="color: #006600;">clamp</span><span style="color: #66cc66;">&#40;</span>percent, <span style="color: #cc66cc;">0.0</span>, <span style="color: #cc66cc;">1.0</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	zsort<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// if a new flow container is in focus, it needs to be on top!</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><strong>Custimization</strong></p>
<p>That&#8217;s the last of it really. Put all the pieces together, and you end up with something like this:</p>
<h4 style="font-size: 1em">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_FlowDemo_603035708"
			class="flashmovie"
			width="900"
			height="250">
	<param name="movie" value="/flow/FlowDemo.swf" />
	<param name="bgcolor" value="#FFFFFF" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="/flow/FlowDemo.swf"
			name="fm_FlowDemo_603035708"
			width="900"
			height="250">
		<param name="bgcolor" value="#FFFFFF" />
	<!--<![endif]-->
		<a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial;" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><br />
</h4>
<p>To drive home how simple this framework makes it, here is <strong>all</strong> of the code used to configure the above flow.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> flow:Flow;
&nbsp;
flow.<span style="color: #006600;">farEffectDistance</span>  = <span style="color: #cc66cc;">150.0</span>;
flow.<span style="color: #006600;">nearEffectDistance</span> = <span style="color: #cc66cc;">0.0</span>;
flow.<span style="color: #006600;">maintainEffect</span> = <span style="color: #000000; font-weight: bold;">false</span>;
&nbsp;
<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span> = <span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> <span style="color: #cc66cc;">12</span>; ++i<span style="color: #66cc66;">&#41;</span>
	flow.<span style="color: #006600;">addComponent</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SampleContainer<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
flow.<span style="color: #006600;">organize</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
flow.<span style="color: #006600;">transformEffect</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Matrix<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1.5</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1.5</span>, -<span style="color: #cc66cc;">30.0</span>, -<span style="color: #cc66cc;">40.0</span><span style="color: #66cc66;">&#41;</span>, Flow.<span style="color: #006600;">NEAR_EFFECT</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
flow.<span style="color: #006600;">blurEffect</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> BlurFilter<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>, Flow.<span style="color: #006600;">FAR_EFFECT</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>And to make it obvious how easy it is to customize it, here are some wacky settings that you might never want, but if you do, its possible. And that&#8217;s the important part.</p>
<h4 style="font-size: 1em">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_FlowDemo2_249797252"
			class="flashmovie"
			width="900"
			height="250">
	<param name="movie" value="/flow/FlowDemo2.swf" />
	<param name="bgcolor" value="#FFFFFF" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="/flow/FlowDemo2.swf"
			name="fm_FlowDemo2_249797252"
			width="900"
			height="250">
		<param name="bgcolor" value="#FFFFFF" />
	<!--<![endif]-->
		<a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial;" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><br />
</h4>
<p>&nbsp;</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">var</span> flow:Flow;
&nbsp;
flow.<span style="color: #006600;">farEffectDistance</span>  = <span style="color: #cc66cc;">150.0</span>;
flow.<span style="color: #006600;">nearEffectDistance</span> = <span style="color: #cc66cc;">0.0</span>;
flow.<span style="color: #006600;">maintainEffect</span> = <span style="color: #000000; font-weight: bold;">false</span>;
&nbsp;
<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">var</span> i:<span style="color: #0066CC;">int</span> = <span style="color: #cc66cc;">0</span>; i <span style="color: #66cc66;">&lt;</span> <span style="color: #cc66cc;">8</span>; ++i<span style="color: #66cc66;">&#41;</span>
	flow.<span style="color: #006600;">addComponent</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SampleContainer<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
flow.<span style="color: #006600;">organize</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
flow.<span style="color: #006600;">transformEffect</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Matrix<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0.2</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">0.2</span>, <span style="color: #cc66cc;">2.0</span>, -<span style="color: #cc66cc;">2.0</span><span style="color: #66cc66;">&#41;</span>, Flow.<span style="color: #006600;">FAR_EFFECT</span><span style="color: #66cc66;">&#41;</span>;
flow.<span style="color: #006600;">transformEffect</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Matrix<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1.0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1.0</span>, <span style="color: #cc66cc;">25.0</span>, -<span style="color: #cc66cc;">25.0</span><span style="color: #66cc66;">&#41;</span>, Flow.<span style="color: #006600;">NEAR_EFFECT</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
flow.<span style="color: #006600;">colorEffect</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ColorTransform<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>, Flow.<span style="color: #006600;">FAR_EFFECT</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>And guess what? Those buttons will always work.</p>
<p><a href="http://labs.byhook.com/flow/flowdemo.zip">Download the files here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/05/25/go-go-gadget-flow/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Alchemy Series Part 6: Ogg Vorbis Library Source Release</title>
		<link>http://labs.byhook.com/2011/05/03/alchemy-series-part-6-ogg-vorbis-library-source-release/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=alchemy-series-part-6-ogg-vorbis-library-source-release</link>
		<comments>http://labs.byhook.com/2011/05/03/alchemy-series-part-6-ogg-vorbis-library-source-release/#comments</comments>
		<pubDate>Tue, 03 May 2011 19:42:37 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[Alchemy]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[Ogg]]></category>
		<category><![CDATA[Vorbis]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1594</guid>
		<description><![CDATA[We have finally managed to get everything together so that we can release the Alchemy Source Code to our Ogg Vorbis Encoder/Decoder library for Flash!  Hit link from the post and start getting your hands dirty with the source!]]></description>
			<content:encoded><![CDATA[<p>And here we are with the final Ogg Vorbis/Alchemy post (at least for a while).  We finally got all of the licensing stuff in order (see the license.txt file, and the comments at the top of the source files) and are ready to release the C source, Yay!</p>
<p><a href="http://labs.byhook.com/oggvorbislib/HookOggVorbisLibFullSource.zip">Please Grab The Download Here.</a></p>
<p>The majority of the C code is from Xiph.org.  We basically took that, and hacked out the parts that wouldn’t compile through the alchemy/cygwin environment, such as the self tests and some of the macros.  We then also forced some of the ifdefs to the correct settings, and reorganized the file structure to make it a bit easier to compile under cygwin.  Once that was up and running, we spent the majority of our time building the wrapper C code (hookoggvorbislib.c) and the AS3 interface layer to access that C code.  You can check out our <a href="http://labs.byhook.com/2011/02/22/ogg-vorbis-encoder-decoder-for-flash">Decoder/Encoder post</a> to see how to use the library.</p>
<p>Once you download the source you can go into the alchemy/ogglib folder and check out all of the Alchemy source.<br />
For a quick Cygwin refresher you can check out our other Alchemy Series posts on getting set up:<br />
<a href="http://labs.byhook.com/2011/03/01/alchemy-series-part-2-environment-setup/">http://labs.byhook.com/2011/03/01/alchemy-series-part-2-environment-setup/</a><br />
<a href="http://labs.byhook.com/2011/03/09/alchemy-series-part-3-ubiquitous-hello-world/">http://labs.byhook.com/2011/03/09/alchemy-series-part-3-ubiquitous-hello-world/</a></p>
<p>To compile the library it takes a couple of steps:<br />
1) Open your Cygwin environment and turn on alc with “alc-on”<br />
2) Change the directory to the alchemy/ogglib/lib folder<br />
3) Delete the old object and archive files:./reset.sh<br />
4) Compile the Xiph lib: ./compileLib.sh<br />
5) Archive the lib: ./arcLib.sh<br />
6) Move back up a directory level, and link with the wrapper:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span> ..
.<span style="color: #000000; font-weight: bold;">/</span>linklib.sh</pre></div></div>

<p>That should create a brand new .swc for you called hookOggVorbisLib.swc</p>
<p>Most of the concepts used in the wrapper code have been covered through out our Alchemy series and its fairly well commented.  So feel free to poke around and see whats up.  There is one limitation thus far, seeking is not working properly for the decoding.  Of course if you decode the whole file into memory, then you can seek through the bytearray as you see fit.  But the seeking to parts of the ogg data, and decoding from there is not working.  If someone feels like tackling that let us know <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In any case, have fun and let us know if you manage to put any of this to good use, we would love to hear about it!</p>
<p>Also remember to like us on Facebook if you want to stay updated, or even just to show your support:<br />
<a href="https://www.facebook.com/pages/Hook/106749192712698"><img src="http://labs.byhook.com/alchemy3/hook.jpg" alt="" /></a><br />
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FHook%2F106749192712698&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe></p>
<p>And/Or you can follow me on Twitter:<br />
<a href="http://www.twitter.com/JakeCallery"><img src="http://twitter-badges.s3.amazonaws.com/follow_me-c.png" alt="Follow JakeCallery on Twitter"/></a></p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/05/03/alchemy-series-part-6-ogg-vorbis-library-source-release/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Alchemy Series Part 5: Revenge of the Thiz</title>
		<link>http://labs.byhook.com/2011/03/23/alchemy-series-part-5-revenge-of-the-thiz/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=alchemy-series-part-5-revenge-of-the-thiz</link>
		<comments>http://labs.byhook.com/2011/03/23/alchemy-series-part-5-revenge-of-the-thiz/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 17:29:50 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Actionscript 3]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[Alchemy]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1571</guid>
		<description><![CDATA[This episode is a bit of a catch all for some other random things that we wanted to cover in this series, like multiple file libraries, async functions, and Flash access from C.  The hope is, by the time you are done reading this post (along with the last 4) you will be able to start build swcs of other libraries, or even creating your own directly in C.  If this ends up being the case, please let us know, we would love to see what you guys make!  Anywho, on with the show...]]></description>
			<content:encoded><![CDATA[<p>This episode is a bit of a catch all for some other random things that we wanted to cover in this series.  The hope is, by the time you are done reading this post (along with the last 4) you will be able to start build swcs of other libraries, or even creating your own directly in C.  If this ends up being the case, please let us know, we would love to see what you guys make!  Anywho, on with the show&#8230;</p>
<p>For any of this to make sense, you will probably want to follow along with the code in the example which you can download here:<br />
<a href="http://labs.byhook.com/alchemy5/HookAlchemyPart5.zip">Example Source</a></p>
<p><strong>Multiple File Compilation and Linking</strong><br />
While doing my own research on Alchemy, I came across many a forum post asking about compiling and linking C libraries that were comprised of multiple files, as most are.  So this week’s example has been split up into multiple files to try and demonstrate the process.  In the alchemy folder bundled with the example code, this is a folder called “lib”.  In there is a couple of C files and a few Bash scripts.  For the purpose of this example, we are going to consider this our Library.  In order get our library compiled and ready to link with our Alchemy wrapper we have to complete a few intermediate steps.</p>
<p>The first step is to compile each of the .c files individually and create .o (object) files from them.  These object files are what is linked together in the end to create the swc.  Since most C libraries out there have lots of files, its probabaly most convenient to create a bash script to handle the compile.  In our case its the “compilelib.sh” file.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #007800;">optLevel</span>=<span style="color: #000000;">3</span>
&nbsp;
<span style="color: #c20cb9; font-weight: bold;">gcc</span> -I..<span style="color: #000000; font-weight: bold;">/</span>include -I.<span style="color: #000000; font-weight: bold;">/</span> <span style="color: #660033;">-Wall</span> -O<span style="color: #007800;">$optLevel</span> <span style="color: #660033;">-c</span> loopstart.c
<span style="color: #c20cb9; font-weight: bold;">gcc</span> -I..<span style="color: #000000; font-weight: bold;">/</span>include -I.<span style="color: #000000; font-weight: bold;">/</span> <span style="color: #660033;">-Wall</span> -O<span style="color: #007800;">$optLevel</span> <span style="color: #660033;">-c</span> cancelstate.c</pre></div></div>

<p>The first line should look familiar to you from previous <a href="http://labs.byhook.com/2011/03/09/alchemy-series-part-3-ubiquitous-hello-world/">posts</a>, but just in case you missed it, it simply tells cygwin to interpret this script with the “bash” shell located at “/bin/bash”.  Next we create a variable to make it easy to alter some compile settings without having to edit each line individually.  Then we have the now familiar “gcc” calls.  The “-I” switches tell gcc to add these folders to its search path when looking for files and definitions, such as (.h) header files.  In this case we are telling it to look in the “include” folder one level up, and to also look in its own folder.  The “include” folder has our “alcexample.h” file which contains the declarations for our library functions and data structures.  The -Wall tells gcc to report all types of warnings while compiling.  -O is the compiler optimization setting.  At one point I thought the optimization was messing with Alchemy, I was wrong.  But I figured it would be good to suggest leaving the variable in there as an example.  You could probably do the whole include bit with a var too.  Lastly “-c” tells gcc to not run the linker, and just save out the object file.  Once those files have been compiled into object files, we need to archive the library together into one file.  Thus the “arclib.sh” script:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #c20cb9; font-weight: bold;">ar</span> csr exampleLib.a loopstart.o cancelstate.o</pre></div></div>

<p>To build the archive we use the “ar” program.  The command line settings break down like this:<br />
c &#8211; create the archive<br />
s &#8211; this creates an object file index in the archive which  “allows routines in the library to call each other without regard to their placement in the archive” (from ranlib docs)<br />
r &#8211; inserts the object file into the archive and replaces duplicates instead of appending</p>
<p>Lastly we feed it the name we want the archive to be called and a list of object files we want included.</p>
<p>At this point we have the library built and archived ready for use in our Alchemy wrapper.  So if you pop up one folder level you will see our main Alchemy file, alcexample.c, as well as another Bash script that will finish our build called “compileandlink.sh”:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #c20cb9; font-weight: bold;">gcc</span> -I.<span style="color: #000000; font-weight: bold;">/</span>include -L.<span style="color: #000000; font-weight: bold;">/</span>lib <span style="color: #660033;">-lexampleLib</span> <span style="color: #660033;">-Wall</span> alcexample.c <span style="color: #660033;">-swc</span> <span style="color: #660033;">-O3</span> <span style="color: #660033;">-o</span> alcexample.swc</pre></div></div>

<p>This looks very similar to our “compilelib.sh” script, with a couple of notable exceptions.  This time we are using the “-L” switch to add a library path to the gcc search path.  We then follow that with a “-l” switch and the name of our library.  The “-c” has also been replaced by a “-o” and a “-swc”.  Which means that gcc will now link the project and create your brand new .swc file <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So, basically the moral of the story is to build a multi-file library, it takes three steps:<br />
1) Basic library compile to object files<br />
2) Archiving of the .o files to a single archive file (with indicies)<br />
3) Final compile and link</p>
<p>Great, now that we can compile the example, lets jump back into looking at code.</p>
<p><strong>Bound States</strong><br />
So a few posts ago, I had mentioned that the first parameter for the AS3_Function() call was usually NULL, and I at the time didn’t know why.  Well, its been figured out <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   You can replace this NULL with a pointer to some data of whatever kind you like.  This can be a handy shortcut so you don’t have to continuously pass in the pointer address from flash to your function calls when you want to access data within the C code.  If you take a look at the alcexample.c file and head down to main(), you will see it looks much like the rest of the examples.  However instead of passing NULL into our AS3_Functions we are now passing a pointer to a struct.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//LoopState</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> totalLoops<span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> isCancelled<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> LoopState<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Setup main state</span>
LoopState <span style="color: #339933;">*</span>mainState <span style="color: #339933;">=</span> initState<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
mainState<span style="color: #339933;">-&gt;</span>isCancelled <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
mainState<span style="color: #339933;">-&gt;</span>totalLoops <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Virtual Function (thunk) mappings</span>
AS3_Val setCancelStateMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>mainState<span style="color: #339933;">,</span> setCancelState<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val startStateLoopMethod <span style="color: #339933;">=</span> AS3_FunctionAsync<span style="color: #009900;">&#40;</span>mainState<span style="color: #339933;">,</span> startStateLoop<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val cleanUpMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>mainState<span style="color: #339933;">,</span> cleanUp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The struct itself is defined in the “alcexample.h” file, and simply included into the “alcexample.c” file.  Its a fairly basic structure that simply has two members, totalLoops, and isCancelled.  In main() we essentially “new up” an instance of that struct (really just allocate some memory for it)  by calling initState() which basically does this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">LoopState <span style="color: #339933;">*</span>state <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>LoopState<span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>LoopState<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span>state<span style="color: #339933;">;</span></pre></div></div>

<p>This is a bit of a spin on what we did in the last <a href="http://labs.byhook.com/2011/03/16/alchemy-series-part-4-d-is-for-data-manipulation/">post</a>.  Since we aren’t going to report this memory address back to Flash, we can return the pointer to the LoopState instance directly.  This way we won’t have to resolve the pointer from the memory address every time we want to use it, since its already a pointer.</p>
<p>After we malloc some space, and grab the pointer to it, we set up some default values in the struct.  We set isCancelled to 1 (which we will signify “true”) and set the totalLoops count to 0.  </p>
<p>With our state all set up, we can pass that pointer in to our thunks.  Which means that the C functions mapped in those thunks will be fed that pointer as its first argument.  So now we don’t need to pass the pointer to that data in every time.  It just gets bound to the thunk and we get access to it at all times in the functions.  This is great for convenience, but you do give up flexibility for it.  You won’t be able to change what pointer is bound to the thunk, so if you want to be able to access different data every time you call the function, you will need to pass in your own pointer, or a memory address that can be used to get the pointer, which is what we did for the imageData struct in the last post.</p>
<p>Lets take a look at the setCancelState() function in the cancelState.c file as an example of how to use this “state” data.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Get loop state from data passed in</span>
LoopState <span style="color: #339933;">*</span>state <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>LoopState<span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>data<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Vars to store passed in cancel state</span>
<span style="color: #993333;">int</span> cancelState<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Parse args for cancel state</span>
AS3_ArrayValue<span style="color: #009900;">&#40;</span>args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;IntType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>cancelState<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Set new cancel state</span>
state<span style="color: #339933;">-&gt;</span>isCancelled <span style="color: #339933;">=</span> cancelState<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Debug print</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Cancel State: %i&quot;</span><span style="color: #339933;">,</span> state<span style="color: #339933;">-&gt;</span>isCancelled<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">return</span> AS3_Null<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The first thing we do is cast and save the “data” argument into the “state” variable.  This is mainly for convenience.  Next we parse out the arguments passed in from flash, which in this case is either a 1 or a 0 and save that in “cancelState”.  Finally we set the “isCancelled” member of state to be whatever was passed in from flash.  Pretty straight forward.  All of the other functions work in the same fashion with regard to getting access to the LoopState structure.  When calling this function from Flash it looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Cancel Loop by setting the LoopState-&gt;isCancelled to 1 (true)</span>
_lib.setCancelState<span style="color: #000000;">&#40;</span><span style="color: #000000; font-weight:bold;">1</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p><strong>Async and the Thiz</strong><br />
The last major “feature”, if you will, in this example, is the use of the AS3_FunctionAsync().  This will allow you to set an ActionScript callback that will be called when the function finishes.  Back in main() you will see the thunk definition for this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">AS3_Val startStateLoopMethod <span style="color: #339933;">=</span> AS3_FunctionAsync<span style="color: #009900;">&#40;</span>mainState<span style="color: #339933;">,</span> startStateLoop<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>From ActionScript the call looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Call async function</span>
_lib.startStateLoop<span style="color: #000000;">&#40;</span>handleLoopComplete, <span style="color: #0033ff; font-weight: bold;">this</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>This means that when startStateLoop() completes, handleLoopComplete will be called in ActionScript.  Unfortunately, that is all this means.  I know what you’re thinking, “The function will run in its own thread!  Finally multi-threaded flash!”  Sadly, this is not the case.  Then you ask “So why even make a separate Function type if it simply plays out like every other function?”  The answer to that is in flyield().  This is a magical function in Alchemy that will “pause” alchemy and give up its timeslice back to Flash.  This means that every time you call  flyield(), flash gets to execute for another tick.  Then Alchemy will execute some more until flyield() is called again.  So even though its not really multi-threaded, you can let your C code churn on some data for a while without locking up your swf and its UI.  This is useful for instance if you are encoding sound data or some other cpu intesive task.  This way you can throw up a progress indicator of some kind and its visuals can be updated while the C code is doing its thing.  A quick thing to note, is that your UI will be locked up while the C code is doing something, it will only get updated when flyield() is called.  Which means that the longer you wait to call flyield() the longer the UI is unresponsive. If this is less than the time it takes to render a frame, then no one will notice.  This means that you will probably need to do some experimentation on your target hardware to determine how much processing you can do in C before giving it up to Flash.  The downside is that while Flash is doing stuff, your C code is not.  Which means that the more often you yield to flash, the slower your number crunching in C happens.</p>
<p>Now, I mentioned progress bars, and initially you probably just skimmed over that without any other thoughts, but there is an issue there.  If your C code is running in a timeslice, how exactly do you get the “progress” of the number crunching back to flash to display?  If you pop open loopstart.c we can take a look.</p>
<p>The first clue is in the argument parsing.  Besides the void *data argument, there is the other AS3_Val that gets passed in.  This gets stored in the AS3_Val clientObj variable.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//var to hold a reference to the Thiz</span>
AS3_Val clientObj<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Parse passed in arguments and get ref to Thiz</span>
AS3_ArrayValue<span style="color: #009900;">&#40;</span>args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;AS3ValType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>clientObj<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you’ll notice, from ActionScript we make this call</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Call async function</span>
_lib.startStateLoop<span style="color: #000000;">&#40;</span>handleLoopComplete, <span style="color: #0033ff; font-weight: bold;">this</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Notice the “this”?  That is an actionScript reference to an actionScript object.  When that is brought into C and converted to an Alchemy Data Type, its called a “Thiz”.  A thiz is essentially a virtual object much like a tunk is a virtual function, which is not to be confused with a C++ virtual function.  Now that we have this thiz we can do some cool things directly to our running Flash code.  In our case we are going to update the flash code with the current progress of our C code.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Build an array of parameters to pass to the ActionScript</span>
<span style="color: #666666; font-style: italic;">//Method call</span>
AS3_Val params <span style="color: #339933;">=</span> AS3_Array<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;IntType&quot;</span><span style="color: #339933;">,</span> state<span style="color: #339933;">-&gt;</span>totalLoops<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Call method on Thiz</span>
AS3_CallS<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;updateFromAlc&quot;</span><span style="color: #339933;">,</span> clientObj<span style="color: #339933;">,</span> params<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The AS3_CallS() takes three arguments, a const char* (C string) of the name of the method you want to call, the thiz you want to call the method on, and a list of params to pass to the method you are calling.  In our case, all we are passing is the totalLoop count from the LoopState.  In actionScript our updateFromAlc() method looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> updateFromAlc<span style="color: #000000;">&#40;</span>$totalLoops<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
<span style="color: #000000;">&#123;</span><span style="color: #009900;">//updateFromAlc</span>
	<span style="color: #009900;">//Update the UI (happens during a yield)</span>
	_textView.numLoopsText.<span style="color: #004993;">text</span> = $totalLoops.<span style="color: #004993;">toString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span><span style="color: #009900;">//updateFromAlc</span></pre></div></div>

<p>As you can see the method is expecting an integer to be passed to it, and it gets that from the state->totalLoops member from the C code.  So now we have full communication from the C code to Flash, and also from Flash to the C code.  Its worth mentioning that if you check out the <a href="http://labs.adobe.com/wiki/index.php/Alchemy:Documentation:Developing_with_Alchemy:C_API">Alchemy docs</a> you will see you can also get and set properties on ActionScript objects that are passed in to the C functions.</p>
<p><strong>Async Cancellation</strong><br />
There is one final interesting bit to this example.  If you check out the while loop in the startStateLoop() method, you will see this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>state<span style="color: #339933;">-&gt;</span>isCancelled <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>This essentially means that the loop is going to keep running until something changes in the LoopState data.  Specifically when isCancelled becomes non-zero.  If you think about it a bit, it at first seems impossible to change that state data while the loop is running.  However, as it turns out, during a flyield() you can actually call other functions on the C code while Flash has control!  Crazy right?  So in the Alchemy C code, the execution pointer is sitting at the flyield() call.  Flash gets its time slice, and then calls another function, in our case setCancelState(1), and changes the state data.  On the next tick, the Alchemy Code gets its next time slice and then continues on from original point of execution, one line after the flyield() call.  Now, the next time through the loop, state->isCancelled is now 1, and the loop exits.  Execution continues to the bottom of the function where the total number of loops is returned.  When this return is hit, guess what is called&#8230; our ActionScript method handleLoopComplete(), and to it is passed the total number of loops.  Yay!  This means we have full control of our C based async functions directly from Flash!  I mean what else can you ask for from a single threaded virtual machine? <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Fin</strong><br />
Welp, that about wraps it up.  There will probably be one more post in this series, but it won’t be so much of a tutorial as a information on our Ogg Vorbis library <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   So for those of you following along at home, thanks for reading about our Alchemy Adventures!  As always, if you get around to making something cool with any of this info, let us know, we would love to see it!</p>
<p>Also remember to like us on Facebook if you want to stay updated, or even just to show your support:<br />
<a href="https://www.facebook.com/pages/Hook/106749192712698"><img src="http://labs.byhook.com/alchemy3/hook.jpg" alt="" /></a><br />
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FHook%2F106749192712698&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe></p>
<p>And/Or you can follow me on Twitter:<br />
<a href="http://www.twitter.com/JakeCallery"><img src="http://twitter-badges.s3.amazonaws.com/follow_me-c.png" alt="Follow JakeCallery on Twitter"/></a></p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/03/23/alchemy-series-part-5-revenge-of-the-thiz/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Social Sentiment: Real Time artwork with Twitter</title>
		<link>http://labs.byhook.com/2011/03/21/social-sentiment-real-time-artwork-with-twitter/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=social-sentiment-real-time-artwork-with-twitter</link>
		<comments>http://labs.byhook.com/2011/03/21/social-sentiment-real-time-artwork-with-twitter/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 18:24:50 +0000</pubDate>
		<dc:creator>Derek</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[processing]]></category>
		<category><![CDATA[real-time]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1525</guid>
		<description><![CDATA[Real-time graphics have been an obsession of mine since the day my father came home with an Atari 800xl. I spent hours copying lines of BASIC code out of magazines to play games like “Space Junk” only for my mother to come in and turn the Atari off while I was at school and flushing my hard work.]]></description>
			<content:encoded><![CDATA[<p><strong>Real time awesomeness</strong><br />
Real-time graphics have been an obsession of mine since the day my father came home with an Atari 800xl. I spent hours copying lines of BASIC code out of magazines to play games like “Space Junk” only for my mother to come in and turn the Atari off while I was at school and flushing my hard work.</p>
<p>Thanks to the hard work of others and huge leaps in processing power, exploring the world of real-time graphics is much easier. I’d wanted to build something with Processing ( <a href="http://processing.org/">http://processing.org</a> ) for quite some time. It has a huge following, tons of libraries, and was born at MIT. Also, It’s much more difficult for my mother to unplug the internet and destroy my work.</p>
<p><strong>Twitter Data for real-time artwork</strong><br />
The twitter streaming server is referred to as ‘Firehose’ for good reason. It’s continuously spewing tweets and all of their accompanying meta-data. This provides a great look into real time data from around the world, and is a great source for generative graphics. I find this approach interesting as it really starts to show some patterns in the chaotic reality that is human social behavior. The stream is in JSON format and easily consumed using java or in this case the twitter4j lib. ( <a href="http://twitter4j.org/">http://twitter4j.org</a> ) I’m sure other social media platforms will or do have similar streams. I look forward to using them in future works for something even more visually abstract.</p>
<p><strong>Wrapping it all up</strong><br />
Based on the streaming data from twitters “firehose”, and the very cool opengl capabilities of processing I decided to map each tweet out to a 3D globe. Using natural language processing we color the tweets points, and text to a color representing the sentiment of the tweet. Pinkish is negative, Blue is Positive, and white is neutral. Now not all tweets from the stream are created equal. This is because not all users tweet from a geo enabled device. So, in the case that the tweet does not include geographical location data we simply do not plot it on the globe. But every tweet is analyzed by the NL engine and then used in the data set for the radial graph around the globe.</p>
<p>Using the great toxi libs I was able to track the tweets floating down the the surface as solids in a voxel grid. They are then converted to a triangular mesh and I draw them out to the screen in the render loop. If you watch them closely you will see the mesh uses the color of the tweet it represents, and mixes colors with nearby tweets creating a colorful mesh of voxely awesomeness. I realize this is nothing more than visual noise. But the intention here was to create something visually entertaining as well (semi-)informative.</p>
<p><strong>Making since of tweets</strong><br />
Have you seen the mindless jabber on twitter? It’s a bunch of “Got my #verizon #iphone #today! Can’t wait to download hipstermatic so I can be a photographer!”, “#Superbowl ads are the lolz!” or “#bacon for lunch again!” What’s the use in any of that? Well, using the very cool Lingpipe natural language engine we can make an attempt to extract the sentiment of tweets. While it’s not 100% accurate (the authors claim somewhere in the 80% range) it is very useful for driving visual cues in the visualization. It’s also great at identifying language or allowing us to filter stuff out such as people who are just tweeting links to porn sites or lolcats.</p>
<p>Computational linguistics is a science in itself. Let’s break down the basics used used here to classify the tweets.</p>
<p>In a new Processing sketch we include Lingpipe and connect to twitter to monitor the stream and build a Language Model (LM) that will later be loaded into the main visualization sketch to classify the tweets from the stream.</p>
<p>Pseudo code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">com.aliasi.util.*</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">com.aliasi.classify.*</span><span style="color: #339933;">;</span>
&nbsp;
mCategories <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span> “positive”, ”negative”,  “neutral”, “url” <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">int</span> nGram <span style="color: #339933;">=</span> <span style="color: #cc66cc;">8</span><span style="color: #339933;">;</span>
mClassifier
<span style="color: #339933;">=</span> DynamicLMClassifier
.<span style="color: #006633;">createNGramProcess</span><span style="color: #009900;">&#40;</span>mCategories,nGram<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>We initialize an instance of DynamicLMClassifier using a factory method and pass in an array of categories we will be using, and an n-gram size. In this case we used a 8-gram as suggested by the authors of Lingpipe. Later when we send in a sequence of characters (a tweet) the LMClassifier will break it down into n-grams. This allows Lingpipe to efficiently compare other sequences of characters later when we ask it to classify a tweet from the stream.</p>
<p>Now as tweets come in from the stream I can save them out to a text file categorized in folders to build the language model and save it out for later use. This is just a quick and dirty way to keep twitter data around after closing a processing sketch. After quite a few long hours of classifying each tweet ( and slowly loosing a little faith in humanity after reading that many random tweets ) I can generate a reusable data model to be used in the main sketch:</p>
<p>Pseudo code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> mCategories.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #003399;">String</span> category <span style="color: #339933;">=</span> mCategories<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
Classification classification <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Classification<span style="color: #009900;">&#40;</span>category<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">File</span> file <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">File</span><span style="color: #009900;">&#40;</span> polarityFolder, mCategories<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">File</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> trainFiles <span style="color: #339933;">=</span> file.<span style="color: #006633;">listFiles</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> trainFiles.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>j<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #003399;">File</span> trainFile <span style="color: #339933;">=</span> trainFiles<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>isTrainingFile<span style="color: #009900;">&#40;</span>trainFile<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #339933;">++</span>numTrainingCases<span style="color: #339933;">;</span>
<span style="color: #003399;">String</span> tweet <span style="color: #339933;">=</span> Files.<span style="color: #006633;">readFromFile</span><span style="color: #009900;">&#40;</span>trainFile,<span style="color: #0000ff;">&quot;ISO-8859-1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
numTrainingChars <span style="color: #339933;">+=</span> tweet.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Classified<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>CharSequence<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> classified
&nbsp;
&nbsp;
<span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Classified<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>CharSequence<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span><span style="color: #009900;">&#40;</span>tweet,classification<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
mClassifier.<span style="color: #006633;">handle</span><span style="color: #009900;">&#40;</span>classified<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Then simply save the instance of the classifier out and we have a model baked and ready to go.</p>
<p>Pseudo code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">FileOutputStream</span> fileOut <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">FileOutputStream</span><span style="color: #009900;">&#40;</span>dataPath<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\\</span>polarity.model&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">ObjectOutputStream</span> objOut <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ObjectOutputStream</span><span style="color: #009900;">&#40;</span>fileOut<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
mClassifier.<span style="color: #006633;">compileTo</span><span style="color: #009900;">&#40;</span>objOut<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
objOut.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>You can download this utility sketch here: <a title="LingPipePolarityGenerator.zip" href="http://labs.byhook.com/socialsentiment/LingPipePolarityGenerator.zip" target="_blank">LingPipePolarityGenerator.zip</a><br />
(Download the lingpipe.jar from <a href="http://alias-i.com/lingpipe/">http://alias-i.com/lingpipe/</a> and drop it into the code folder to run the sketch)</p>
<p>Back in the main sketch it’s trivial to load the model back in and ask it to classify the tweets as they come in from the stream.</p>
<p>Pseudo code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">InputStream</span> fileIn <span style="color: #339933;">=</span> createInput<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;polarity.model&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">ObjectInputStream</span> objIn <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ObjectInputStream</span><span style="color: #009900;">&#40;</span>fileIn<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
loadedModelClassifier <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>LMClassifier<span style="color: #009900;">&#41;</span>objIn.<span style="color: #006633;">readObject</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Streams.<span style="color: #006633;">closeInputStream</span><span style="color: #009900;">&#40;</span>objIn<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>We now have our model instance ( loadedModelClassifier ) ready to classify tweets like this:</p>
<p>Pseudo code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">Classification classification <span style="color: #339933;">=</span> loadedModelClassifier.<span style="color: #006633;">classify</span><span style="color: #009900;">&#40;</span> tweetFromStreamString <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">log</span><span style="color: #009900;">&#40;</span> classification.<span style="color: #006633;">bestCategory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The call to the bestCategory method will yield a string representation of the best match based on the sample data we supplied to the model in the utility sketch. Language detection is done in the same fashion, but it uses a model supplied with lingpipe and is reasonably accurate as well.</p>
<p>Lingpipe manages to encapsulate all of the complex methods of Computational Linguistics and yields some very useful results. Find more information on it here: <a href="http://alias-i.com/lingpipe/">http://alias-i.com/lingpipe/</a></p>
<p><strong>The Results</strong><br />
Once things started coming together I started to notice some patterns immediately. The most apparent pattern is the number percentage of positive, negative, and neutral tweets. And to my surprise they tend to stick to about 39%, 13%, 48% respectively. Looks like people on twitter aren’t nearly as negative as I had originally thought them to be!</p>
<p><strong>PROTIP: Global Illumination renders with Sunflow library</strong><br />
I’m no Java evangelist, but some of the open source libraries out there for the java platform are very cool. In this case Sunflow ( <a href="http://sunflow.sourceforge.net/">http://sunflow.sourceforge.net/</a> .) I rewrote all the geometry routines in the processing sketch to spit out data that sunflow could load in and render. The results are pretty fun, this was definitely a rewarding endeavor. Hey real-time is awesome, but so is global illumination and ambient occlusion shaders. Some day I’m sure the two will converge!</p>
<p><img src="http://labs.byhook.com/socialsentiment/render.jpg" width="910" height ="1138" border=0></p>
<p><strong>Have a go at it</strong><br />
<a title="Social Sentiment Web" href="http://labs.byhook.com/socialsentiment/web/" target="_blank">Click here</a> to run the sketch in your browser. It will not run in the browser on MacOS, so if that is your platform of choice give grab the standalone version linked below.</p>
<p><a href="http://labs.byhook.com/socialsentiment/socialSentiment.windows.zip" target="_blank">Standalone for Windows</a><br />
<a href="http://labs.byhook.com/socialsentiment/socialSentiment.mac.zip" target="_blank">Standalone for MacOS</a></p>
<p>You can download the processing sketch source here: <a title="social sentiment source" href="http://labs.byhook.com/socialsentiment/socialSentiment_src.zip" target="_blank">socialSentiment_src.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/03/21/social-sentiment-real-time-artwork-with-twitter/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Alchemy Series Part 4: D is for Data Manipulation</title>
		<link>http://labs.byhook.com/2011/03/16/alchemy-series-part-4-d-is-for-data-manipulation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=alchemy-series-part-4-d-is-for-data-manipulation</link>
		<comments>http://labs.byhook.com/2011/03/16/alchemy-series-part-4-d-is-for-data-manipulation/#comments</comments>
		<pubDate>Wed, 16 Mar 2011 15:11:45 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[Alchemy]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Pointers]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1528</guid>
		<description><![CDATA[This week, in Part 4 of our Alchemy Series we are exploring Data Management and Manipulation from Flash to C and back.  We cover keeping state inside of Alchemy code, as well as dealing with ByteArrays as File Streams and other basic data handling.]]></description>
			<content:encoded><![CDATA[<p>So far, we’ve gone though getting the <a href="http://labs.byhook.com/2011/03/01/alchemy-series-part-2-environment-setup/">environment </a>setup, basic <a href="http://labs.byhook.com/2011/03/09/alchemy-series-part-3-ubiquitous-hello-world/">compilation and implementation</a> of alchemy into a swf, and the standard <a href="http://labs.byhook.com/2011/03/09/alchemy-series-part-3-ubiquitous-hello-world/">Hello World</a> example.  So what next you ask?  Well I answer with “More Contrived Examples!”  Sadly its tough to make examples that don’t feel totally contrived, while also making those examples easy to understand while staying on point.  Kind of like the old racing adage, “Cheap, Fast, Reliable, pick any two”.  So I picked easy to understand and on point.  Which means we are still in the land of contrived examples, and for that I apologize.  Either way, on with the contrivedness! <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://labs.byhook.com/alchemy4/HookAlchemySeriesPart4.zip">The Example can be Downloaded Here.</a></p>
<p>This example is broken up into three different parts.  The first deals with basic object creation and return, the second, deals with ByteArrays as file streams in C (I promise that is super useful), and finally the third is keeping data stored in C as a way of keeping state internal to your library.</p>
<p>So if you run the supplied example inside of the Flash CS5 IDE or from FlashDevelop/Builder, or something that watches for traces, you will see this:</p>
<p>&#8211; Start Basic Data Example &#8211;<br />
(ALC) Text: Test Text<br />
(ALC) Int: 15<br />
(ALC) Number: 3.141592<br />
(ALC) AS3 Obj Text: Hawt String<br />
(ALC) AS3 Obj Int: 42<br />
Obj: Test Text<br />
Obj: 15<br />
Obj: 3.141592</p>
<p>&#8211; Start ByteArrays as Streams Example &#8211;<br />
In Bytes Length: 10000<br />
>Out Bytes Length Before: 0<br />
(ALC) Bytes Read 1024<br />
(ALC) Bytes Written 1024<br />
(ALC) Bytes Read 2048<br />
(ALC) Bytes Written 2048<br />
(ALC) Bytes Read 3072<br />
(ALC) Bytes Written 3072<br />
(ALC) Bytes Read 4096<br />
(ALC) Bytes Written 4096<br />
(ALC) Bytes Read 5120<br />
(ALC) Bytes Written 5120<br />
(ALC) Bytes Read 6144<br />
(ALC) Bytes Written 6144<br />
(ALC) Bytes Read 7168<br />
(ALC) Bytes Written 7168<br />
(ALC) Bytes Read 8192<br />
(ALC) Bytes Written 8192<br />
(ALC) Bytes Read 9216<br />
(ALC) Bytes Written 9216<br />
(ALC) Bytes Read 10000<br />
(ALC) Bytes Written 10000<br />
>Out Bytes Length After: 10000</p>
<p>&#8211; Start Image Data Example &#8211;<br />
Length: 40000<br />
Memory address for RED image: 1069136<br />
Length: 10000<br />
Memory address for GREEN image: 1069152</p>
<p>You will also see a Red square with a translucent and smaller Green square on top of it.  Epic exciting I know, but the behind the scenes bits are pretty awesome if you ask me <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   First up, basic data handling example.</p>
<p><strong>Data in, Data out</strong><br />
At this point, I’m assuming you have worked your way through the Part 3 post, and are fairly comfortable compiling things, and working with that compiled swc in flash.  But I do want to point out some changes in the main() function of this example.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Virtual Function (thunk) maps</span>
AS3_Val showArgsMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> showArgs<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val storeImageBytesMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> storeImageBytes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val adjustAlphaMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> adjustAlpha<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val getImageBytesMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> getImageBytes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val freeImageBytesMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> freeImageBytes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val copyBytesMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> copyBytes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The first bit is still the same.  We declare and define an AS3_Function thunk for each of the function we want to expose and map that to the actual internal C function.  So far so standard.</p>
<p>The next line you’ve seen before as well</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Bundle up the thunks into an AS3 Object.  This object is what flash sees</span>
<span style="color: #666666; font-style: italic;">//after you call init() on the loaded Alchemy loader.</span>
AS3_Val flashObj <span style="color: #339933;">=</span> AS3_Object<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;showArgs:AS3ValType, copyBytes:AS3ValType&quot;</span><span style="color: #339933;">,</span> showArgsMethod<span style="color: #339933;">,</span> copyBytesMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This, as before, creates an AS3 Object that will hold the mappings to our internal functions. This is how those functions are accessed from ActionScript.  You also pass in a Type Template pattern as a string, and then references to the thunks.  Still pretty normal.  However you will notice that we’ve defined six functions, but have only included two in our AS3 Object.  If we put all six in there, the line starts to get very unwieldy.  So we can use the AS3_SetS() function to attach more properties/functions to our AS3 Object.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">AS3_SetS<span style="color: #009900;">&#40;</span>flashObj<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;storeImageBytes&quot;</span><span style="color: #339933;">,</span> storeImageBytesMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_SetS<span style="color: #009900;">&#40;</span>flashObj<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;adjustAlpha&quot;</span><span style="color: #339933;">,</span> adjustAlphaMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_SetS<span style="color: #009900;">&#40;</span>flashObj<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;getImageBytes&quot;</span><span style="color: #339933;">,</span> getImageBytesMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_SetS<span style="color: #009900;">&#40;</span>flashObj<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;freeImageBytes&quot;</span><span style="color: #339933;">,</span> freeImageBytesMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>AS3_SetS() allows use to add properties by name and set their inial value.  The first parameter is the object we want to add our properties to.  The second is a (constant) char* list of characters that is the name of our property.  Lastly we pass in the initial value of that property.  In this case, we are passing in the thunks we made to expose out C functions with.  That is the first bit of data management in the first example.  Setting properties at runtime to AS3 Objects.  Remember this is a “real” AS3 Object, so it can be returned to Flash and used directly.</p>
<p>This concept is more obviously implemented in the showArgs() C function.  This function serves no purpose other than to demonstrate a few different ways of dealing with basic data.  From Flash we do this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">/////****** BASIC DATA EXAMPLE *****\\\\\</span>
<span style="color: #009900;">//Demonstrate Object Properties</span>
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;-- Start Basic Data Example --&quot;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> testObj<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = <span style="color: #000000;">&#123;</span> stringProp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #990000;">&quot;Hawt String&quot;</span>, answerProp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #000000; font-weight:bold;">42</span> <span style="color: #000000;">&#125;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> retObj<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span>; 
retObj = _lib.showArgs<span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Test Text&quot;</span>, <span style="color: #000000; font-weight:bold;">15</span>, <span style="color: #000000; font-weight:bold;">3.141592</span>, testObj<span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Obj: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> retObj.myText<span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Obj: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> retObj.myInt<span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Obj: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> retObj.myDbl<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>and we should get the following debug output:<br />
&#8211; Start Basic Data Example &#8211;<br />
(ALC) Text: Test Text<br />
(ALC) Int: 15<br />
(ALC) Number: 3.141592<br />
(ALC) AS3 Obj Text: Hawt String<br />
(ALC) AS3 Obj Int: 42<br />
Obj: Test Text<br />
Obj: 15<br />
Obj: 3.141592</p>
<p>Once the C library is instantiated, we can start to call functions on it. In this case we are creating a new object, “testObj” and defining a few dynamic properties on it by hand.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #6699cc; font-weight: bold;">var</span> testObj<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = <span style="color: #000000;">&#123;</span> stringProp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #990000;">&quot;Hawt String&quot;</span>, answerProp<span style="color: #000000; font-weight: bold;">:</span><span style="color: #000000; font-weight:bold;">42</span> <span style="color: #000000;">&#125;</span>;</pre></div></div>

<p>Then we make the call, passing in a few more parameters in addition to the testObj:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">retObj = _lib.showArgs<span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Test Text&quot;</span>, <span style="color: #000000; font-weight:bold;">15</span>, <span style="color: #000000; font-weight:bold;">3.141592</span>, testObj<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>This maps, not surprisingly, to the showArgs() function in our C file.  So lets dig into that a bit.<br />
The first bit is very similar to our echoMe() function from the previous post.  We declare some variables, and parse out the arguments using the AS3_ArrayValue() function.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Declare some variables to hold the passed in data</span>
<span style="color: #993333;">char</span><span style="color: #339933;">*</span> myText<span style="color: #339933;">;</span>	<span style="color: #666666; font-style: italic;">//AS3_String maps to char*</span>
<span style="color: #993333;">int</span> myInt<span style="color: #339933;">;</span>		<span style="color: #666666; font-style: italic;">//AS3_Int maps to int</span>
<span style="color: #993333;">double</span> myDbl<span style="color: #339933;">;</span>	<span style="color: #666666; font-style: italic;">//AS3_Number maps to double</span>
AS3_Val myObj<span style="color: #339933;">;</span>	<span style="color: #666666; font-style: italic;">//AS3_Object passed in.</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Declare some more vars to hold the values parsed out of myObj</span>
<span style="color: #993333;">char</span><span style="color: #339933;">*</span> testObjString<span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> testObjInt<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Delcare var for our return object</span>
AS3_Val returnObj<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Parse out arguments using AS3_ArrayValue</span>
<span style="color: #666666; font-style: italic;">//This takes the passed in args object, and creates new C values</span>
<span style="color: #666666; font-style: italic;">//from it based on the string of types given as a pattern</span>
AS3_ArrayValue<span style="color: #009900;">&#40;</span>args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;StrType, IntType, DoubleType, AS3ValType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>myText<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>myInt<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>myDbl<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>myObj<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>So this is expecting us to pass in a String, Int, Double, and a Generic AS3 Value.  Which we do with “Test Text”, 15, 3.141592, and testObj and store those in their respective C variables.  The first three are fairly standard, so we store them and then print them out with fprintf() which I touched on last time.  Basically fprintf takes a stream to write to and some things to write out in a specific format:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Print out the basic arguments</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;(ALC) Text: %s&quot;</span><span style="color: #339933;">,</span> myText<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;(ALC) Int: %i&quot;</span><span style="color: #339933;">,</span> myInt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;(ALC) Number: %f&quot;</span><span style="color: #339933;">,</span> myDbl<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In this case, our stream is stderr (declared in stdio.h).  The flash debugger will catch this and print it out much like a trace.  The second argument we have a char* (a string of characters) and a format identifier.  Lastly is a list of values that will populate those format identifiers.  A good reference for fprintf is here: <a href="http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/">http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/</a><br />
As you can probably tell, %s will display a char*, %i will display an integer, and %f will display a floating point value.  There are many things you can display in this manner, check out the reference page above for a complete list.</p>
<p>So that takes care of passing in basic atomic data.  What about objects and other forms of complex data?  For that we can use AS3_ObjectValue()</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Parse passed in AS3 Object into valid C types</span>
AS3_ObjectValue<span style="color: #009900;">&#40;</span>myObj<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;stringProp:StrType, answerProp:IntType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>testObjString<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>testObjInt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;(ALC) AS3 Obj Text: %s&quot;</span><span style="color: #339933;">,</span> testObjString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;(ALC) AS3 Obj Int: %i&quot;</span><span style="color: #339933;">,</span> testObjInt<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>AS3_ObjectValue() works in a similar fashion to AS3_ArrayValue().  You give it an AS3 object, a type template, and the destinations for the parsed values.  The AS3_ObjectValue() handles all of the details of the type conversion, which is nice.  Then we print out the respective values.  So far so good.  So what about returning an AS3 object?  We can do that too:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Build return object</span>
returnObj <span style="color: #339933;">=</span> AS3_Object<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;myText:StrType&quot;</span><span style="color: #339933;">,</span> myText<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_SetS<span style="color: #009900;">&#40;</span>returnObj<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;myInt&quot;</span><span style="color: #339933;">,</span> AS3_Int<span style="color: #009900;">&#40;</span>myInt<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_SetS<span style="color: #009900;">&#40;</span>returnObj<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;myDbl&quot;</span><span style="color: #339933;">,</span> AS3_Number<span style="color: #009900;">&#40;</span>myDbl<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This should look mighty familiar to you, as its nearly identical to what we did when putting our thunks together in main().  First we make an object with AS3_Object(), and feed it a property name:Type and then an initial value.  From there we can add more dynamic properties with AS3_SetS().  Its as simple as that.</p>
<p>So now we can send data into C functions, modify it, print it, and recombine it to be returned back to flash as a proper AS3 object.  As you will discover, once you get the hang of getting your values converted back and forth, working with Alchemy isn’t so hard at all <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   So lets look at something slightly (no much mind you) more practical.</p>
<p><strong>ByteArrays and File Streams</strong><br />
I’ve read quite a few <a href="http://unitzeroone.com/blog/2009/03/18/flash-10-massive-amounts-of-3d-particles-with-alchemy-source-included/">posts </a>and comments on the <a href="http://blog.joa-ebert.com/2009/04/03/massive-amounts-of-3d-particles-without-alchemy-and-pixelbender/">internet</a> debating whether or not Alchemy is faster than straight ActionScript, since it all runs within the flash virtual machine anyway.  The consensus seems to be a giant “it depends”.  For me however, its not so much about that.  Its more about being able to access the bagillion (careful, thats a technical term) lines of C/C++ code out there that has been written to do just about anything you want over the last 40ish years.  For us it was getting access to Xiph’s wonderful Ogg and Vorbis libraries for dealing with sound data.  Can you imagine flash with access to something like <a href="http://www.fmod.org/">FMOD</a>?  Or even <a href="http://www.sideroller.com/wck/">physics engines</a>? or C based path finding libraries?  Yeah epic&#8230; For me, this is the real power of Alchemy, though the faster memory access is also a nice bonus <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   My real point to all of that blathering is many of the libraries out there (especially libraries that convert stuff) use file data off of the command line, and write the modified data back out to a file stream.  So instead of trying to convert your data or make deep hacks at the C code, you can simply stream your ByteArray data as a standard file stream right to the library, as if it were coming right off of the command line.  The core concept for this was demonstrated here: <a href="http://segfaultlabs.com/devlogs/alchemy-asynchronous-jpeg-encoding">http://segfaultlabs.com/devlogs/alchemy-asynchronous-jpeg-encoding</a></p>
<p>The idea is that we can use funopen() to redefine how the file streams work in C.  Basically we replace the built in methods for accessing the data with our own.  For this we can use Alchemy’s ByteArray functions:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/******************************************
* bytearray manipulations for use as C streams
*******************************************/</span>
<span style="color: #993333;">static</span> <span style="color: #993333;">int</span> readba<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span>src<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>dst<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> length<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//readba</span>
	<span style="color: #b1b100;">return</span> AS3_ByteArray_readBytes<span style="color: #009900;">&#40;</span>dst<span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span>AS3_Val<span style="color: #009900;">&#41;</span>src<span style="color: #339933;">,</span> length<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//readba</span>
&nbsp;
<span style="color: #993333;">static</span> <span style="color: #993333;">int</span> writeba<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span>dst<span style="color: #339933;">,</span> <span style="color: #993333;">const</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>src<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> length<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//writeba</span>
	<span style="color: #b1b100;">return</span> AS3_ByteArray_writeBytes<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>AS3_Val<span style="color: #009900;">&#41;</span>dst<span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>src<span style="color: #339933;">,</span> length<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//writeba</span>
&nbsp;
<span style="color: #993333;">static</span> fpos_t seekba<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span>src<span style="color: #339933;">,</span> fpos_t offs<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> whence<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//seekba</span>
	<span style="color: #b1b100;">return</span> AS3_ByteArray_seek<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>AS3_Val<span style="color: #009900;">&#41;</span>src<span style="color: #339933;">,</span> offs<span style="color: #339933;">,</span> whence<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//seekba</span>
&nbsp;
<span style="color: #993333;">static</span> <span style="color: #993333;">int</span> closeba<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span>src<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//closeba</span>
	AS3_Val zero <span style="color: #339933;">=</span> AS3_Int<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	AS3_SetS<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>AS3_Val<span style="color: #009900;">&#41;</span>src<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;position&quot;</span><span style="color: #339933;">,</span> zero<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	AS3_Release<span style="color: #009900;">&#40;</span>zero<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//closeba</span></pre></div></div>

<p>To make use of these new functions we can reassign them like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Open bytearrays as stdio streams</span>
FILE <span style="color: #339933;">*</span>output <span style="color: #339933;">=</span> funopen<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>outBytes<span style="color: #339933;">,</span> readba<span style="color: #339933;">,</span> writeba<span style="color: #339933;">,</span> seekba<span style="color: #339933;">,</span> closeba<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>For this section of the post we will be using the copyBytes() function from the alcexample.c file.  The we call this from ActionScript in the “Byte Arrays as C Streams” section of Main.as</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">/////***** BYTE ARRAYS AS C STREAMS *****\\\\\</span>
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;<span style="">\n</span>-- Start ByteArrays as Streams Example --&quot;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> inBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">BitmapData</span><span style="color: #000000;">&#40;</span><span style="color: #000000; font-weight:bold;">50</span>, <span style="color: #000000; font-weight:bold;">50</span>, <span style="color: #0033ff; font-weight: bold;">true</span>, 0xFFFFFFFF<span style="color: #000000;">&#41;</span>.<span style="color: #004993;">getPixels</span><span style="color: #000000;">&#40;</span><span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Rectangle</span><span style="color: #000000;">&#40;</span><span style="color: #000000; font-weight:bold;">0</span>, <span style="color: #000000; font-weight:bold;">0</span>, <span style="color: #000000; font-weight:bold;">50</span>, <span style="color: #000000; font-weight:bold;">50</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> outBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">ByteArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
inBytes.<span style="color: #004993;">position</span> = <span style="color: #000000; font-weight:bold;">0</span>;
&nbsp;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;In Bytes Length: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> inBytes.<span style="color: #004993;">length</span><span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;&gt;Out Bytes Length Before: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> outBytes.<span style="color: #004993;">length</span><span style="color: #000000;">&#41;</span>
_lib.copyBytes<span style="color: #000000;">&#40;</span>inBytes, outBytes<span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;&gt;Out Bytes Length After: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> outBytes.<span style="color: #004993;">length</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>So what are we doing here?  To demonstrate how to use ByteArrays as C streams, we will simply be taking some byte data, iterating over it all, and pushing it into a new output stream.  Effectively making a copy of the byte data.  I know its not that exciting, but its what made our <a href="http://labs.byhook.com/2011/02/22/ogg-vorbis-encoder-decoder-for-flash/">OggVorbis encoder</a> possible.  So I think its a pretty awesome concept.</p>
<p>In the above ActionScript, we are simply generating some byte data to copy by making a white square as bitmap data, and using getPixels() to convert that to a ByteArray.  Then we create an empty ByteArray as a container for the copied byte data.  Finally we call copyBytes() on the C lib and pass in the input and output ByteArrays.</p>
<p>Meanwhile&#8230; In the C copyBytes() function we start off like we always do, declare some vars, and parse out the arguments.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Declare byte arrays</span>
AS3_Val inBytes<span style="color: #339933;">;</span>
AS3_Val outBytes<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Declare other needed vars</span>
<span style="color: #993333;">long</span> inLength<span style="color: #339933;">;</span>
<span style="color: #993333;">long</span> outLength<span style="color: #339933;">;</span>
<span style="color: #993333;">long</span> bytesRead <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #993333;">long</span> bytesWritten <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Parse args</span>
AS3_ArrayValue<span style="color: #009900;">&#40;</span>args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;AS3ValType, AS3ValType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>inBytes<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>outBytes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This parses our arguments and assigns our two ActionScript ByteArrays to inBytes and outBytes.  The goal here is to read through all of the inBytes bytes, and copy it to the outBytes ByteArray, all the while treating it like a file stream.</p>
<p>Next we set up the streams to make use of our ByteArray wrapper functions from before.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Open bytearrays as stdio streams</span>
FILE <span style="color: #339933;">*</span>output <span style="color: #339933;">=</span> funopen<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>outBytes<span style="color: #339933;">,</span> readba<span style="color: #339933;">,</span> writeba<span style="color: #339933;">,</span> seekba<span style="color: #339933;">,</span> closeba<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
FILE <span style="color: #339933;">*</span>input <span style="color: #339933;">=</span> funopen<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>inBytes<span style="color: #339933;">,</span> readba<span style="color: #339933;">,</span> writeba<span style="color: #339933;">,</span> seekba<span style="color: #339933;">,</span> closeba<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now being as though we are treating these guys as streams, we don’t know how many bytes there will be, so we are going to want to store off the length of the ByteArrays, using our old friend AS3_ObjectValue()</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//check length</span>
AS3_ObjectValue<span style="color: #009900;">&#40;</span>inBytes<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;length:IntType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>inLength<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_ObjectValue<span style="color: #009900;">&#40;</span>outBytes<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;length:IntType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>outLength<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p> Now that we are all set up, we can actually do something with the data.  To make an attempt to stay faithful to what generally happens, we are going to copy 1k chunks of the stream to a buffer, (where you would in theory modify the data) and then copy the contents of that buffer back to the output stream</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>bytesRead <span style="color: #339933;">&lt;</span> inLength<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//copy bytes</span>
	<span style="color: #666666; font-style: italic;">//Read 1k at a time</span>
	<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1024</span> <span style="color: #339933;">&amp;&amp;</span> bytesRead <span style="color: #339933;">&lt;</span> inLength<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//read to buffer</span>
	bytesRead <span style="color: #339933;">+=</span> fread<span style="color: #009900;">&#40;</span>readBuffer<span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>input<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//read to buffer</span>
&nbsp;
	fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;(ALC) Bytes Read %ld&quot;</span><span style="color: #339933;">,</span> bytesRead<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//write 1k out to stream</span>
	<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1024</span> <span style="color: #339933;">&amp;&amp;</span> bytesWritten <span style="color: #339933;">&lt;</span> inLength<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//write to output</span>
		bytesWritten <span style="color: #339933;">+=</span> fwrite<span style="color: #009900;">&#40;</span>readBuffer<span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span>output<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//write to output</span>
&nbsp;
	fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;(ALC) Bytes Written %ld&quot;</span><span style="color: #339933;">,</span> bytesWritten<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//copy bytes</span></pre></div></div>

<p>Now our ActionScript outBytes ByteArray will contain a copy of the contents of the inBytes ByteArray.</p>
<p>Finally when we are all done, we close up the streams, and release our AS3 objects:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Close up streams</span>
fclose<span style="color: #009900;">&#40;</span>output<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fclose<span style="color: #009900;">&#40;</span>input<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
AS3_Release<span style="color: #009900;">&#40;</span>inBytes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Release<span style="color: #009900;">&#40;</span>outBytes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><strong>Pointers and Data Structures</strong><br />
Ok, so far so good I hope.  All of this was in preparation for this last section.  In this part of the example, we will be demonstrating how to store data into malloc’d memory inside of the Alchemy code.  For this example we will be making use of the storeImageBytes(), freeImageBytes(),  adjustAlpha(), and getImageBytes() functions in the alcexample.c file.  If pointers or non-memory managed languages are new to you, you may want to grab a quick nap, or take a break and get something to eat. <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   Its not the simplest thing in the world on first viewing.</p>
<p>Deep Breath, here we go.</p>
<p>If you run the example swf, you will see a red box with a smaller translucent green box sitting inside of it.  What we are going to do, is store the bitmap data for both boxes inside of the Alchemy code (on the heap) and save off the memory address that starts the contents of that data.  Once its stored there, we can manipulate it within the C code, without having to push that data into Alchemy again and again.  We can just manipulate it right in memory, and when we are done, we can pull it back out.  This is an example of how to keep state inside of your C code.</p>
<p>First up, creating the ByteArrays that contain our bitmap data for the boxes:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">/////******* STATE MANAGEMENT ******\\\\\</span>
<span style="color: #009900;">//Build a red test image (red square)</span>
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;<span style="">\n</span>-- Start Image Data Example --&quot;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> redBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> redBD<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">BitmapData</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">BitmapData</span><span style="color: #000000;">&#40;</span><span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #000000; font-weight:bold;">100</span>, <span style="color: #0033ff; font-weight: bold;">true</span>, 0xFFFF0000<span style="color: #000000;">&#41;</span>;
redBytes = redBD.<span style="color: #004993;">getPixels</span><span style="color: #000000;">&#40;</span>redBD.<span style="color: #004993;">rect</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">//Build Green Test image (green square)</span>
<span style="color: #6699cc; font-weight: bold;">var</span> greenBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> greenBD<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">BitmapData</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">BitmapData</span><span style="color: #000000;">&#40;</span><span style="color: #000000; font-weight:bold;">50</span>, <span style="color: #000000; font-weight:bold;">50</span>, <span style="color: #0033ff; font-weight: bold;">true</span>, 0xFF00FF00<span style="color: #000000;">&#41;</span>;
greenBytes = greenBD.<span style="color: #004993;">getPixels</span><span style="color: #000000;">&#40;</span>greenBD.<span style="color: #004993;">rect</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Once we have that we store that data on heap:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Store bytes in alchemy memory</span>
redBytes.<span style="color: #004993;">position</span> = <span style="color: #000000; font-weight:bold;">0</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> redPtr<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Number</span> = _lib.storeImageBytes<span style="color: #000000;">&#40;</span>redBytes<span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Memory address for RED image: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> redPtr<span style="color: #000000;">&#41;</span>;
&nbsp;
greenBytes.<span style="color: #004993;">position</span> = <span style="color: #000000; font-weight:bold;">0</span>;
<span style="color: #6699cc; font-weight: bold;">var</span> greenPtr<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Number</span> = _lib.storeImageBytes<span style="color: #000000;">&#40;</span>greenBytes<span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Memory address for GREEN image: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> greenPtr<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>As you can see when we call _lib.storeBytes() we get a number back in return.  This number is the memory address that represents the start of our stored data.  Any time you want to access that data you will need to pass that back into the C code, which will then get a reference to the data from the memory address.  But before we get too far ahead or ourselves, lets check out what storeImageBytes() does.</p>
<p>The first part should at this point be very familiar to you.  Declare some vars, parse the arguments, and store the values from the arguments.  In this case we are also saving off the length of the passed in ByteArray.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Delcare incoming byte array</span>
AS3_Val bytes<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Var to hold the length value</span>
<span style="color: #993333;">int</span> length<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Pars args</span>
AS3_ArrayValue<span style="color: #009900;">&#40;</span>args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;AS3ValType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>bytes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Determine length</span>
AS3_ObjectValue<span style="color: #009900;">&#40;</span>bytes<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;length:IntType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>length<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This next bit, grabs some memory from the heap and stores a pointer to that memory</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Allocate memory for and save an instance of the imageData Struct</span>
imageData <span style="color: #339933;">*</span>image <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>imageData <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>imageData<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>I know, I know, there is that pesky “imageData” type that I haven’t mentioned yet.  So lets get to that real quick.  At the very top of the alcexample.c file, you will see the definition for that typedef struct.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//imageData</span>
        <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>data<span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> length<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> imageData<span style="color: #339933;">;</span></pre></div></div>

<p>Basically this is just an object that has two properties or members, “data”, and “length”.  Data is a pointer to some memory that holds a list of unsigned chars.  Why unsigned chars you ask?  Well, they have a valid range of 0 to +255.  Hmmm&#8230; what else goes from 0 to 255? Oh I know! A single channel of color data!  In flash if I say 0xFFFF0000 you probably immediately think Red at full Alpha, because Flash uses the ARGB color format (alpha, red, green, blue).  This is a hex number, when converted to Decimal, looks like 255 255 0 0 (argb).  So half alpha blue would look like 127 0 0 255 or 0x7F0000FF.  So what we are going to do is store the actual image byte data right there in the “data” member.  Then we are also going to store the length of our byte data in the “length” member.  However we want to make sure that our instance of the imageData struct doesn’t go out of scope when we leave the storeImageBytes() function, so we need to grab some memory off of the heap, instead of the stack.  Which is where the malloc line, once again, comes into play.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>imageData<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>With a pointer to our newly malloc’d imageData instance, we can access the “data” member of that instance and malloc some more memory to store our actual byte data in and also save off the length:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Allocate some heap memory</span>
image<span style="color: #339933;">-&gt;</span>data <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>malloc<span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>length<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Save length</span>
image<span style="color: #339933;">-&gt;</span>length <span style="color: #339933;">=</span> length<span style="color: #339933;">;</span></pre></div></div>

<p>Now with everything ready, we can read in our byte data from the passed in ByteArray and shove it into our struct.  We can use Alchemy’s built in ByteArray methods to get the data out.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Write bytes to buffer</span>
AS3_ByteArray_readBytes<span style="color: #009900;">&#40;</span>image<span style="color: #339933;">-&gt;</span>data<span style="color: #339933;">,</span> bytes<span style="color: #339933;">,</span> length<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>So now if we checked out the data that has been stored (assuming its from the red square bitmap data) when we execute this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;A: %i&quot;</span><span style="color: #339933;">,</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;R: %i&quot;</span><span style="color: #339933;">,</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;G: %i&quot;</span><span style="color: #339933;">,</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;B: %i&quot;</span><span style="color: #339933;">,</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>we would see:<br />
A: 255<br />
R: 255<br />
G: 0<br />
B: 0</p>
<p>That would be the ARGB colors of the first pixel in our red square.  Awesome right?</p>
<p>After we do some clean up we can then return the memory address of our struct instance:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">return</span> AS3_Number<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">long</span><span style="color: #009900;">&#41;</span>image<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>That number is the number we are going to store in our ActionScript code, to be used to reference the image data that we care about.</p>
<p>Great so now we have the data in there, what can we do.  Well staying consistent with the rest of the horribly forced examples, we are going to modify the Alpha Channel of that image data.  From ActionScript we are going to do this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Adjust the alpha of the image bytes</span>
_lib.adjustAlpha<span style="color: #000000;">&#40;</span>redPtr, <span style="color: #000000; font-weight:bold;">0.8</span><span style="color: #000000;">&#41;</span>;
_lib.adjustAlpha<span style="color: #000000;">&#40;</span>greenPtr, <span style="color: #000000; font-weight:bold;">0.3</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>The first argument is that memory address we received from when we stored the image data.  The second argument is a 0 &#8211; 1 value that we will multiply against our Alpha Channel bytes in our stored image data.</p>
<p>The adjustAlpha() function once again starts out like the rest.  Delcare some vars and parse the arguments</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Get access to image data from memory address</span>
imageData <span style="color: #339933;">*</span>image<span style="color: #339933;">;</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> imageAddress<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Storage for alpha multiplier</span>
<span style="color: #993333;">double</span> alphaMult<span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> count<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> alpha<span style="color: #339933;">;</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> red<span style="color: #339933;">;</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> green<span style="color: #339933;">;</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> blue<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Parse args</span>
AS3_ArrayValue<span style="color: #009900;">&#40;</span>args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;IntType, DoubleType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>imageAddress<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>alphaMult<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Next however, is the tricky bit.  We need to take that passed in memory address and create a pointer to the data at that address, which is of the imageData type defined by our struct</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Get pointer to image</span>
image <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>imageData <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>imageAddress<span style="color: #339933;">;</span></pre></div></div>

<p>So now, image is a pointer to the imageData instance we care about.  So lets do something with it.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Walk pixels</span>
count <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>count <span style="color: #339933;">&lt;</span> image<span style="color: #339933;">-&gt;</span>length<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//each pixel</span>
	alpha <span style="color: #339933;">=</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span>count<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	red <span style="color: #339933;">=</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span><span style="color: #339933;">++</span>count<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	green <span style="color: #339933;">=</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span><span style="color: #339933;">++</span>count<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	blue <span style="color: #339933;">=</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span><span style="color: #339933;">++</span>count<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//Modify channels</span>
	alpha <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>alpha<span style="color: #339933;">*</span>alphaMult<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
&nbsp;
	<span style="color: #666666; font-style: italic;">//Store back into data</span>
	image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span>count<span style="color: #339933;">-</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> alpha<span style="color: #339933;">;</span>
	image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span>count<span style="color: #339933;">-</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> red<span style="color: #339933;">;</span>
	image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span>count<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> green<span style="color: #339933;">;</span>
	image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#91;</span>count<span style="color: #339933;">-</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> blue<span style="color: #339933;">;</span>
&nbsp;
	count<span style="color: #339933;">++;</span>
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//each pixel</span></pre></div></div>

<p>Nothing earth shattering here, but if you come from a purely ActionScript background, some things may look a bit funky.  The most obvious item is the “->”.  Never fear, all this does is dereference the “image” pointer and grab the value at the memory address of the member data.  So for alpha= image->data[count]  we are simply getting the byte that is stored in that imageData instance at “count” index.  So if “count” is 0, and we are looking at the red square then the value would be 255 or 0xFF because that pixel has full Alpha (“A”rgb).  Then we simply walk down each byte and do whatever we want with it.  In this case, we are mutiplying the alpha value by the alpha multiplier that was passed into the function.  Then we write that back to the “data” member.  Simple enough.  The thing to remember is that we have modfied the data on the heap, so its permenantly set that way now, until of course we change it again.</p>
<p>So cool&#8230; We have managed to store some data, and modify it.  Now its time to get that modified data back into Flash.  I’ll bet you couldn’t have guessed we use the getImageBytes() function <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>From ActionScript we can do this to get our data back out</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Get altered image back from Alchemy</span>
<span style="color: #6699cc; font-weight: bold;">var</span> newRedBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span>; 
newRedBytes = _lib.getImageBytes<span style="color: #000000;">&#40;</span>redPtr<span style="color: #000000;">&#41;</span>;
newRedBytes.<span style="color: #004993;">position</span> = <span style="color: #000000; font-weight:bold;">0</span>;</pre></div></div>

<p>We call getImageBytes() on the C lib, and feed it the memory address to the data we care about, just as before.  From there we get a brand new ByteArray that is filled with our modified image data and returned back to Flash.  As with the rest of the of the functions, we again, set up some vars, and parse the args.  Then we generate a pointer to our data once again.  But then we get to do something new.  We create an actual ActionScript ByteArray in C.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Create a new byte array</span>
AS3_Val flash_utils_namespace <span style="color: #339933;">=</span> AS3_String<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;flash.utils&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val no_params <span style="color: #339933;">=</span> AS3_Array<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val ByteArray_class <span style="color: #339933;">=</span> AS3_NSGetS<span style="color: #009900;">&#40;</span>flash_utils_namespace<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;ByteArray&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val outBytes <span style="color: #339933;">=</span> AS3_New<span style="color: #009900;">&#40;</span>ByteArray_class<span style="color: #339933;">,</span> no_params<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The key function here is the AS3_NSGetS().  This gets a class definition that can then be newed up.  The first parameter is the package path (as an AS3_String) to the class definition you want.  In this case we are using “flash.utils”.  The second parameter is a constant char* (C string) of the name of the AS3 Class we want.  In this case its “ByteArray”. Then on the next line we new it up with AS3_New().  We pass to it the class definition and an array of parameters.  In this case we don’t need to send anything to the ByteArray constructor, so we just use an empty AS3_Array(&#8220;&#8221;).  At this point we have an honest to goodness AS3 ByteArray.  Which means we can fill it with bytes.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Write bytes to byte array</span>
AS3_ByteArray_writeBytes<span style="color: #009900;">&#40;</span>outBytes<span style="color: #339933;">,</span> image<span style="color: #339933;">-&gt;</span>data<span style="color: #339933;">,</span> image<span style="color: #339933;">-&gt;</span>length<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In our case we take the modified image data, and shove it into our newly created ByteArray.  Lastly we do a bit of clean up and return the new ByteArray back to flash.</p>
<p>From there, in ActionScript we take those bytes, and build a new BitmapData object from it, and display it on screen.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Set Bitmap data based on data returned from Alchemy</span>
<span style="color: #6699cc; font-weight: bold;">var</span> newRedBD<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">BitmapData</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">BitmapData</span><span style="color: #000000;">&#40;</span>redBD.<span style="color: #004993;">width</span>, redBD.<span style="color: #004993;">height</span>, <span style="color: #0033ff; font-weight: bold;">true</span>, 0x00000000<span style="color: #000000;">&#41;</span>;
newRedBD.<span style="color: #004993;">setPixels</span><span style="color: #000000;">&#40;</span>redBD.<span style="color: #004993;">rect</span>, newRedBytes<span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">//Put result image on stage</span>
<span style="color: #6699cc; font-weight: bold;">var</span> newRedImg<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Bitmap</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Bitmap</span><span style="color: #000000;">&#40;</span>newRedBD<span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">addChild</span><span style="color: #000000;">&#40;</span>newRedImg<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Now we have a semi transparent red block on screen <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   w00t!</p>
<p>The final bit is some manual memory management.  From Flash we can call</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">_lib.freeImageBytes<span style="color: #000000;">&#40;</span>redPtr<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Which results in</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Pointer to image data</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> imageAddress<span style="color: #339933;">;</span>
imageData <span style="color: #339933;">*</span>image<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Parse ags</span>
AS3_ArrayValue<span style="color: #009900;">&#40;</span>args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;IntType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>imageAddress<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Get access to our image data</span>
image <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>imageData <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>imageAddress<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Release memory used by our image data</span>
free<span style="color: #009900;">&#40;</span>image<span style="color: #339933;">-&gt;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
free<span style="color: #009900;">&#40;</span>image<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Lots more of the same, vars, args, pointers, blah, blah, blah.  But then there is the free() call.  Basically we are just giving that memory back, and Flash’s Garbage Collected can now reclaim it.</p>
<p><strong>Great Googly Moogly</strong><br />
So, if you have made it this far, congratulations, you have reached the light at the end of the tunnel, and the train is running late, so its actual sun light this time. <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>However, we still have two more Alchemy Posts in the series.  Part 5 covers some other random details, like mult-file compiling/linking, Asynchronous functions, and talking to ActionScript from the C code.  Should be a riot <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Remember to like us on Facebook if you want to stay updated, or even just to show your support:<br />
<a href="https://www.facebook.com/pages/Hook/106749192712698"><img src="http://labs.byhook.com/alchemy3/hook.jpg" alt="" /></a><br />
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FHook%2F106749192712698&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe></p>
<p>And/Or you can follow me on Twitter:<br />
<a href="http://www.twitter.com/JakeCallery"><img src="http://twitter-badges.s3.amazonaws.com/follow_me-c.png" alt="Follow JakeCallery on Twitter"/></a></p>
<p>Thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/03/16/alchemy-series-part-4-d-is-for-data-manipulation/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Alchemy Series Part 3: Ubiquitous Hello World</title>
		<link>http://labs.byhook.com/2011/03/09/alchemy-series-part-3-ubiquitous-hello-world/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=alchemy-series-part-3-ubiquitous-hello-world</link>
		<comments>http://labs.byhook.com/2011/03/09/alchemy-series-part-3-ubiquitous-hello-world/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 15:53:29 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[Alchemy]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[avm]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Cygwin]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[gcc]]></category>
		<category><![CDATA[llvm]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1515</guid>
		<description><![CDATA[In part 3 of our Adobe Alchemy series we finally dive into some C code, and get an example up and running from scratch.  You will be exposed to words like "thunk" and "bash" and not be referring to a bad cave man joke. Oh, and you will also make calls to C functions from Flash :)]]></description>
			<content:encoded><![CDATA[<p>Welcome to Part 3, where we finally get to write some C code! Yay!  This part is designed to get you comfortable with building up a C file from scratch for use within flash, and get used to the compiling and access process.  This example swc has two functions.  sayHi() and echoMe().  We are going to break these down into as much detail as we can, to get prepared for the next part in the series which talks about real data manipulation.  That post however is already getting pretty long, so we split out this section as a primer for Part 4.</p>
<p>Please download the source files for this <a href="http://labs.byhook.com/alchemy3/AlchemyHelloWorld.zip">example here</a>.</p>
<p>Also please make sure that you have the alchemy environment setup and running from <a href="http://labs.byhook.com/2011/03/01/alchemy-series-part-2-environment-setup/">Part 2</a>.</p>
<p>Now go ahead and launch Cygwin.bat and get your Cygwin shell up and running.</p>
<p><strong>Quick Cygwin Intro</strong><br />
First lets go over a few Cygwin Bash Shell commands:<br />
At any point you can open the manual (man pages) which has more info on each of these commands.  To access those simply type:</p>
<p><em>man command</em></p>
<p>and press enter.</p>
<p>Replace “command” with the command you are interested in.  An example of this would be:<br />
<em>man ls</em></p>
<p>That will give you something that looks like this:<br />
<img src="http://labs.byhook.com/alchemy3/manPages.png" alt="" /></p>
<p>Use the arrow keys to move up and down, and “q” to quit.</p>
<p><strong>Useful Cygwin Commands:</strong><br />
ls:<br />
This will list the files in the current directory.  Some useful options are -a -l -h.  A is for<br />
“All”, l is for “Long”, and h is for “Human Readable”.<br />
You can combine them like this:<br />
ls -alh</p>
<p>cd:<br />
Change directory.  There are no drive letters in Cygwin.  So “cd” gets you everywhere.<br />
cd /cygdrive/e/alchemyStuff<br />
That will put you in the “alchemyStuff” directory of the “c” drive.</p>
<p>pwd:<br />
Print Working Directory.  Just tells you what directory you are in.<br />
When you see a “~” that means your home directory.</p>
<p>rm:<br />
Remove &#8211; it deletes stuff, so rm dumbFile.c will delete dumbFile.c.</p>
<p>ln:<br />
Create a link.  Kind of a shortcut to a folder.  I generally use the “-s” option and make a<br />
symbolic link to my current project (saves a lot of cd’ing):<br />
ln -s /cygdrive/e/AlchemyHelloWorld<br />
This will put the link/shortcut into whatever directory you are currently in.<br />
So now from my home directory (cd ~) I can quickly get to my project:<br />
cd AlchemyHelloWorld</p>
<p>dos2unix:<br />
If you create a file in windows, it uses different line endings, newline + carriage return<br />
Cygwin just used new line.  So if you run:<br />
dos2unix myWindowsFile.sh<br />
It will convert the linendings and other little things to the proper format.</p>
<p>./:<br />
The dot+slash is super useful.  Your current working directory is probably not in the<br />
global path.  So in order to run anything you will need to put a ./ in front of it.  As you will<br />
see later in this post, to compile our stuff, we will use:<br />
 ./compileHello.sh<br />
That runs the bash script “compileHello.sh” from the current directory.</p>
<p>Now with that out of the way we can get to the good stuff.  Lets take a quick look at the files in the example:<br />
alchemy folder:<br />
- compileHello.sh<br />
this is a script that does our compiling.</p>
<p>- hello.c<br />
this is the C code for our hello world alchemy library</p>
<p>- hello.swc<br />
this is the compiled swc that we will access from flash.</p>
<p>bin folder:<br />
This is the standard FlashDevelop AS3 Project bin folder.  Just contains the index.html<br />
file and the swf of our example.  Nothing special here</p>
<p>src folder:<br />
- Main.as<br />
this is our document class that is the entry point for the example.</p>
<p>This example doesn’t have any on stage visual output so its not embedded in the page like the examples in the other posts.  Which means you will have to download the example and run it through FlashDevelop or some other IDE to catch the trace output.  Which brings us to&#8230;.</p>
<p><strong>Setting up the example</strong><br />
If you are using FlashDevelop, then all you have to do is double click on the project file.  Then navigate to the alchemy folder and right click on the “hello.swc” file, and select “Add To Library”.  Then press F5.  In the output pane you should see:</p>
<p><em>(fcsh)Build succeeded<br />
Done(0)<br />
[Starting debug session with FDB]<br />
Generating Hi Message in Alchemy<br />
Response From Alchemy: Hi From Alchemy!<br />
Echo: Echo This!</em></p>
<p>If you are using the Flash CS5 IDE, you will need to create a new .fla file in the “src” folder, and use “Main” as the document class.  Then go to File->Publish Settings->Flash->ActionScript3 Settings->Library Path and add “../alchemy” as a library path.<br />
Now do a “ctrl-enter” and you shoudl get the following output:</p>
<p><em>Generating Hi Message in Alchemy<br />
Response From Alchemy: Hi From Alchemy!<br />
Echo: Echo This!<br />
</em></p>
<p><strong>Compiling</strong><br />
Cool, so now that you know what the end result is, lets compile the hello.c file from scratch, shall we?</p>
<p>Pop into the Cygwin shell, and “cd” your way to where ever you have the source files extracted to.  </p>
<p>First we have to turn alchemy “on”, so type:<br />
alc-on</p>
<p>and press enter.  Now when you run gcc it will run through Alchemy.</p>
<p>To do that go into the /alchemy folder and type:<br />
./compileHello.sh</p>
<p>This is a bash script that I made so I don’t have to type so much.  The contents of the script look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
<span style="color: #c20cb9; font-weight: bold;">gcc</span> <span style="color: #660033;">-Wall</span> hello.c <span style="color: #660033;">-swc</span> <span style="color: #660033;">-O3</span> <span style="color: #660033;">-o</span> hello.swc</pre></div></div>

<p>The first line tells Cygwin that it should use “bash” to interpret the script.  The next line is the actual gcc command.  Now remember if you make a bash script in windows (like in notepad or whatever), and access it through Cygwin, you will need to run “dos2unix compileHello.c” to convert the end lines.</p>
<p>gcc obviously executes the gcc compiler and then we pass a few options to it.<br />
First -Wall, this says, turn all of the (W)arnings on.  Next is the .c file that we want to compile, and in this case its hello.c.  Next -swc says create a swc. -O3 sets the optimiztion to level 3 (compiler level optimizations will do things like inline your functions and various other compiler voodoo to make your stuff execute faster).  Lastly -o says output to hello.swc.</p>
<p>If all goes well you may get a warning about POSIX file paths, (which can be ignored, see previous <a href="http://labs.byhook.com/2011/03/01/alchemy-series-part-2-environment-setup/">post</a>) and a warning about ‘main’ arguments being dropped.  This can also safely be ignored.  You should then get a bunch of other stuff that prints out that looks like:<br />
<img src="http://labs.byhook.com/alchemy3/compile.png" alt="" /></p>
<p>So after all of that preliminary stuff, we can finally get on to the code.  Pop open the alchemy/hello.c file, and lets go through it.</p>
<p>Finally Some Code<br />
When starting a new C file that needs flash access you will need to include the “AS3.h” header file.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;AS3.h&quot;</span></pre></div></div>

<p>That will get you access to the various AS3 Value types, and the functions that allow you to convert data to and from ActionScript types.</p>
<p>Now jump down to the main() function at the very bottom.  This is where the initial setup happens that exposes your carefully crafted C functions to flash.  First up is the creation of a virtual function (basically an ActionScript function object that will reference a C function) or a “Thunk” as its technically called.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Create the thunk (a virtual function that can be exposed to flash)</span>
<span style="color: #666666; font-style: italic;">//this assigns a reference to a C function to an AS3 Function</span>
<span style="color: #666666; font-style: italic;">//definition that can be passed to AS3_Object()</span>
AS3_Val sayHiMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> sayHi<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Val echoMeMethod <span style="color: #339933;">=</span> AS3_Function<span style="color: #009900;">&#40;</span>NULL<span style="color: #339933;">,</span> echoMe<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The first thing beyond the comments is “AS3_Val”  this a data type that comes with “AS3.h”.  Basically its a place to store objects that are going to ActionScript or coming from ActionScript.  In this case, its going to put assigned to an object that is going to be visible to ActionScript.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Bundle up the thunks into an AS3 Object.  This object is what flash sees</span>
<span style="color: #666666; font-style: italic;">//after you call init() on the loaded Alchemy loader.</span>
AS3_Val flashObj <span style="color: #339933;">=</span> AS3_Object<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;alchemySayHi:AS3ValType, alchemyEchoMe:AS3ValType&quot;</span><span style="color: #339933;">,</span> sayHiMethod<span style="color: #339933;">,</span> echoMeMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is where we actually expose things to ActionScript.  The “flashObj” object will be available as a means of communication between our flash bits and our alchemy bits.  AS3_Object is a function that creates an as3 object with the properties passed in as its arguments.  The first argument is a comma separated list of propertyName:propertyType value pairs.  The second argument is the values of those properties.  In the next part of the series we will be taking a deeper look into AS3_Object as well as the other data management abilities of alchemy.  So for now, just know that this is where you give flash access to your C/Alchemy functions.  So in this case, the object will have a property on it called “alchemySayHi” and it will be of type AS3ValType.  This property will contain a reference to our thunk “sayHiMethod” from a few lines before.  That thunk references the C sayHi() function.  So from flash we can call lib.alchemySayHi() and it will execute the C sayHi() function.  Just to be a little clearer, “lib” in this case is the returned “flashObj” that we created.  The same goes for the “alchemyEchoMe” property, that will reference the “echoMeMethod”, which in turn executes the echoMe() C function.  Got all that? <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>As you are I’m sure well aware, Flash/ActionScript is a “Managed” system.  Meaning that the virtual machine manages all of the memory allocation and freeing.  This is good and bad, but in either case a discussion for another time.  C on the other hand is not a managed system.  Meaning that if we create stuff that takes up memory, we need to free that same stuff, so we don’t leave memory stranded out there that can no longer be accessed.  The rule of thumb is, if we create it, we release it.  There is one exception however.  If you are returning an object that you created it will be released automatically.  The last bit to keep in mind in terms of memory management is that when compiled down through Alchemy, the C code is now Adobe Virtual Machine byte code.  Which means it runs with in the VM.  Which ultimately means the memory is managed.  However, the Garbage Collector won’t know to free up the memory used in the C code if you don’t explicitly free it.  So for all intents and purposes, you can just pretend that the C code is still an unmanaged memory system.  Just know its  lie <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So all of that was to simply justify these lines:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//We created a new AS3_Val, so we have to release it now that we are done with it</span>
AS3_Release<span style="color: #009900;">&#40;</span>sayHiMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Release<span style="color: #009900;">&#40;</span>echoMeMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Lets take a quick break from C for the moment, and see how we can use the stuff in the main() function.  If you pop open Main.as in the /src folder, and meander down to the init() function you will see this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Setup the alchemy library</span>
_loader = <span style="color: #0033ff; font-weight: bold;">new</span> CLibInit<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
_lib = _loader.<span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>When you compile your C code through Alchemy, it builds you a swc with a package path that looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #0033ff; font-weight: bold;">import</span> cmodule.hello.CLibInit;</pre></div></div>

<p>Its cmodule.your_swc_name.  In there is the CLibInit class.  This is the Alchemy loader.  You new that up, and then call init() on the new CLibInit object.  This is what runs your main() function from the C code.  This retuns that “flashObj” object that we attached the two function references to.  That means we are free to do some crazy stuff like this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Now that we are all set up, we can call the exposed method</span>
<span style="color: #6699cc; font-weight: bold;">var</span> response<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">String</span>;
response = _lib.alchemySayHi<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Response From Alchemy: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> response<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Holy moly thats some ridiculous stuff right there.  Basically its doing what it says.  Its finding the “alchemySayHi” property from the Alchemy object, and executing that as a function, which it is, because we stored an AS3_Function(NULL, sayHi) in that property.</p>
<p>Ok, so we didn’t spend that long in ActionScript, but I figure you know how most of that works already <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   Back to C!</p>
<p>Lets take a look at the sayHi() function in hello.c</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">AS3_Val sayHi<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span>data<span style="color: #339933;">,</span> AS3_Val args<span style="color: #009900;">&#41;</span></pre></div></div>

<p>That is the start of the function definition for sayHi().  Now, I’m not going to lie, I don’t know how to use the first parameter, void *data.  The docs state this:<br />
“Create a synchronous function callback object, binding the function pointer with the data passed in.  data can be used to hold state for the function”<br />
So for now, I’m going to skip it until I understand it enough to properly inform you.  The second parameter however, I have a grasp on: AS3_Val args<br />
When you call a thunk from ActionScript it passes the parameters to this argument as an AS3 Array.  You can then pull apart that Array and use those passed in values within your function.  There is an example of that in the echoMe() function.  We will get to that in a bit.</p>
<p>Next up in the sayHi() function is:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">AS3_Val traceOut<span style="color: #339933;">;</span>
traceOut <span style="color: #339933;">=</span> AS3_String<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Generating Hi Message in Alchemy&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>First we make a variable of type AS3_val and call it “traceOut”.  This is going to be passed to an AS3_Trace() call.  If you check out the docs for AS3_Trace() you will see that it takes an AS3_Val val as its parameter.  So we need to make one of those, and in this case we called it “traceOut”.  Now that we have our AS3_Val we are going to want to store a string in it.  In C there is no real concept of strings.  They are essentially pointers to a list of chars.  We will go more into that in a bit.  For our current case however, we are going to make an AS3_String and store that into traceOut.  Which will then be traced out.  Super exciting.. I know&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">traceOut <span style="color: #339933;">=</span> AS3_String<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Generating Hi Message in Alchemy&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
AS3_Trace<span style="color: #009900;">&#40;</span>traceOut<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>It might be a good time to point out that AS3_String() is not a cast, it is a real C function defined in Alchemy.  This creates a new object that is of type AS3_String.  So just keep in mind that the only real ActionScript data type here is the AS3_Val type.  There is no AS3_String type, its a factory function.</p>
<p>But alas, I said the word create again.  Which can only mean one thing:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//We created it, we release it</span>
AS3_Release<span style="color: #009900;">&#40;</span>traceOut<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Finally for a little added pizazz (yes I said pizazz), we are going to return something back to ActionScript.  Part 5 of our series will talk at length about communicating between Flash and the Alchemy code, but I figured I could slip this in now <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Retun a string (an as3 string mind you) to flash</span>
<span style="color: #666666; font-style: italic;">//When something is returned, it is automatically &quot;released&quot;</span>
<span style="color: #b1b100;">return</span> AS3_String<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Hi From Alchemy!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>So in Main.as this is where “High From Alchemy!” is returned:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">response = _lib.alchemySayHi<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Response From Alchemy: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> response<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>This is what give us the output you see in your output window <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Lastly we are going to talk about the echoMe() function in hello.c.  I’m going to skim this one a bit, as it dips into the pool of the Part 4 post on data manipulation, but I figured I better give you something so you come back next time <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The function:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/*****************************************************************************
* echoMe:
*		This function will take a string from Flash, and trace it out.
* 
* arguments:
*		(AS3_String) a string of text to echo out.
*
* returns:
* 		(AS3_Val) NULL
******************************************************************************/</span>
AS3_Val echoMe<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span>data<span style="color: #339933;">,</span> AS3_Val args<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span><span style="color: #666666; font-style: italic;">//echoMe</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//Declare a variable to hold our input (which will be an as3 string)</span>
	<span style="color: #993333;">char</span><span style="color: #339933;">*</span> inputString<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//Parse &quot;args&quot; array from flash</span>
	AS3_ArrayValue<span style="color: #009900;">&#40;</span>args<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;StrType&quot;</span><span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>inputString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//Do the echo to stderr</span>
	fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Echo: %s&quot;</span><span style="color: #339933;">,</span> inputString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//We created it, we release it</span>
	free<span style="color: #009900;">&#40;</span>inputString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//Return nothing.</span>
	<span style="color: #666666; font-style: italic;">//Compiler is expecting an AS3_Val to be returned.</span>
	<span style="color: #666666; font-style: italic;">//We have to use AS3_Val so we can create the thunk in main()</span>
	<span style="color: #666666; font-style: italic;">//Therefore we have to return something, which in this case is nothing :)</span>
	<span style="color: #666666; font-style: italic;">//Ok, well its not nothing, its Null, and more than that its an AS3 null,</span>
	<span style="color: #666666; font-style: italic;">//not a C null.</span>
	<span style="color: #b1b100;">return</span> AS3_Null<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #666666; font-style: italic;">//echoMe</span></pre></div></div>

<p>So the function definition is exactly the same as the sayHi() function.  But then everything gets all different and stuff, and we sort of exit ActionScript land, and splash around a bit in puddles of C code.<br />
The first line declares a varible called inputString.  This is of type char* which is a C type.  Basically its a point to a memory address that will contain a list of characters.  Sounds familiar doesn’t it?<br />
Next we use the AS3_ArrayValue() function to pull apart the “args” parameter.  The first parameter in the AS3_ArrayValue() call is the source array from flash.  In this case its “args”. The next parameter is a string of comma separated Class/Type names.  This describes what the type of each element in the array is, so order is paramount.  The last parameter is where the value from the array will be stored.  In this case its going to be stored at the memory address specified by inputString.  (for more info, look up C pointers and dereferencing).  If you check out the docs for AS3_Array you will see a list of types and what they map to in C.  In this case “StrType” maps to char*.  Go figure <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Cool, so now, what do we do.  Well, list print out whatever was passed into the echoMe() call.  This time we are going to use a C function to do it, fprintf().  That is another one you are going to have to look up.  C programming is a bit beyond the scope of this post, but I will explain whats going on a bit here.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Echo: %s&quot;</span><span style="color: #339933;">,</span> inputString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Stderr stands for Standard Error.  We are telling fprintf to print our stuff out to the standard error pipe.  We do this so that FlashDevelop and the Flash IDE catch it and display it in the output window.  The next parameter is a string.  In this string is a %s which tells fprintf that you want to replace that %s with a char* value.  Hence the third parameter, intputString, which as you know is a char* value.  So when this is executed, it will display<br />
“Echo: Echo This!”<br />
or whatever you pass in to it.</p>
<p>Now, since we created a char*, we need to free it, which is what the free() call does.  Go figure.<br />
Lastly, since we promised the compiler that this function was going to return a AS3_Val, we need to do that.  However, since we don’t have anything useful to return we are just going to return an AS3_Null().  Now again, remember, AS3_Null() is a function that creates an object, which flash will read as Null, so again, its not a cast.</p>
<p>Whew, for so few lines of code, that took some serious explaining.  Hopefull this will help you understand how to get started with this stuff.  In the next part we are going to try to do something useful <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>As always, if you want updates for when new posts come out, Like us on facebook at the Hook page:<br />
<a href="https://www.facebook.com/pages/Hook/106749192712698"><img src="http://labs.byhook.com/alchemy3/hook.jpg" alt="" /></a><br />
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FHook%2F106749192712698&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe></p>
<p>And/Or follow me on Twitter:<br />
<a href="http://www.twitter.com/JakeCallery"><img src="http://twitter-badges.s3.amazonaws.com/follow_me-c.png" alt="Follow JakeCallery on Twitter"/></a></p>
<p>Tune in next time, on the same bat channel.  (I would have said same bat time too, but I can’t promise that <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/03/09/alchemy-series-part-3-ubiquitous-hello-world/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Alchemy Series Part 2: Environment Setup</title>
		<link>http://labs.byhook.com/2011/03/01/alchemy-series-part-2-environment-setup/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=alchemy-series-part-2-environment-setup</link>
		<comments>http://labs.byhook.com/2011/03/01/alchemy-series-part-2-environment-setup/#comments</comments>
		<pubDate>Tue, 01 Mar 2011 16:05:08 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[Alchemy]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[Cygwin]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1490</guid>
		<description><![CDATA[Part 2 of our Alchemy Series will get you all set up to start building and porting your own C libraries to Adobe Flash.  The initial setup seems to scare a lot of people off, so we tried to do a very easy to follow step by step guide to getting the Alchemy Development Environment up and running.  Check it out, and get started having fun with Alchemy!  You know you want to :)]]></description>
			<content:encoded><![CDATA[<p>To get started with Alchemy on a Windows box, you first need to get cygwin installed.  Cygwin is a pseudo linux environment that runs under Windows.  This gives us access the the LLVM and the gcc compilers.  This is how we are going to take C/C++ code and create a swc that we can access directly from flash.</p>
<p>To get started we are going to first need the Adobe Flex SDK, please download this and unzip it to c:\flexsdk<br />
<a href="http://opensource.adobe.com/wiki/display/flexsdk/Flex+SDK">http://opensource.adobe.com/wiki/display/flexsdk/Flex+SDK</a></p>
<p>Currently the latest release is Flex4.1 Update 4.1.0.16076.</p>
<p>Now we can grab Adobe Alchemy:<br />
<a href="http://labs.adobe.com/downloads/alchemy.html">http://labs.adobe.com/downloads/alchemy.html</a></p>
<p>Just check the box at the bottom and download the “Alchemy Toolkit for Cygwin on Windows”<br />
When that finishes downloading, unzip it into c:\alchemy (make sure that you don&#8217;t unzip it into folders within that, you want the folder structionto be c:\alchemy and then a bunch of folders such as c:\alchemy\achacks, c:\alchemy\bin, etc&#8230;</p>
<p>Next you will need to make sure you have Java installed.  If you do, please continue.  If you do not, please download and install it from here:<br />
<a href="http://www.java.com/en/download/index.jsp">http://www.java.com/en/download/index.jsp</a></p>
<p>Last up is Cygwin’s setup.exe file:<br />
<a href="http://www.cygwin.com/">http://www.cygwin.com/</a></p>
<p>Look for setup.exe about half way down the page, and download that to c:\cygwin (you can put this wherever you like, but I will be using c:\cygwin and c:\alchemy through out the post for simplicity)</p>
<p>This setup file is basically a client front end that allows you to download and install whatever linux packages you will need to get the job done.</p>
<p>Double click on the setup.exe to get things started.<br />
- Click next on the first screen.<br />
- On the second screen select “install from internet” and click next.<br />
- Set your root directory on the third screen to c:\cygwin and install for all users. Click Next<br />
- Set your local package directory to be c:\cygwin as well, click next.<br />
- Set up your proxy settings if you have any (if you are behind a corporate firewall or something) otherwise select “Direct Connection” and click next.<br />
- Select a mirror, I usually use http://mirrors.kernel.org click next.<br />
- You may get a Setup Alert warning you that this is your first install, so you should check out the docs.  This is normal, and fine, just click OK.<br />
-  This takes you to the package selection screen.  </p>
<p><img src="http://labs.byhook.com/images/alchemyimages/cygwin_package_selection_1.png" alt="" /></p>
<p>Yes I know, its scary, but you’ll be fine <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   There are a few packages that we need to install for the Alchemy setup, and a few that I install for convenience.  Here are the required packages (you can type the name in the search box to help narrow down the list) Once you find the package, click on the “Skip” button on the left, and that will change to a version number.  That means that package will download.  The next column over has 2 check boxes.  The first says Download Binaries, the second says Download Source.  For this we only need the binaries.<br />
	Required:<br />
	- All -> Devel -> gcc-g++: C++ compiler<br />
<img src="http://labs.byhook.com/images/alchemyimages/cygwin_package_selection_GCC.png" alt="" /></p>
<p>	- All -> Archive -> zip: Info-ZIP compression utility<br />
<img src="http://labs.byhook.com/images/alchemyimages/cygwin_package_selection_zip.png" alt="" /></p>
<p>	- All -> Perl -> perl: Larry Wall’s Practical Extracting and Report Language<br />
<img src="http://labs.byhook.com/images/alchemyimages/cygwin_package_selection_perl.png" alt="" /></p>
<p>	Optional:<br />
	-  All -> Shells -> rxvt: VT102 terminal emulator<br />
<img src="http://labs.byhook.com/images/alchemyimages/cygwin_package_selection_rxvt.png" alt="" /></p>
<p>	-  All -> Editors -> emacs: The extensible, customizable, real-time display editor<br />
<img src="http://labs.byhook.com/images/alchemyimages/cygwin_package_selection_emacs.png" alt="" /></p>
<p>Once all of the packages are selected, you can click Next</p>
<p>This will bring up a screen about Resolving Dependencies.  Make sure the check box is checked at the bottom of the window, and click Next.<br />
The great download starts.  Might be a good time to take a quick break as this will take a few minutes.<br />
When the download/install is complete, just click finish.</p>
<p>Finally with everything installed, we can configure it all <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Parts of the next section were learned from:<br />
<a href="http://www.developria.com/2009/04/setting-up-adobe-alchemy.html">http://www.developria.com/2009/04/setting-up-adobe-alchemy.html</a><br />
and<br />
<a href="http://labs.adobe.com/wiki/index.php/Alchemy:Documentation:Getting_Started">http://labs.adobe.com/wiki/index.php/Alchemy:Documentation:Getting_Started</a><br />
Both are excellent articles for getting the Alchemy Environment setup and running.</p>
<p>Now we have to add some things to cygwin’s path.  In the c:\cygwin\etc folder there will be a file called “profile”.  Please open that in Notepad++ or other proper text editor (in other words, not Microsoft WORD!).</p>
<p>The first line that isn’t a comment should be:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">PATH</span>=<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #007800;">$PATH</span></pre></div></div>

<p>We need to add alchemy and the flexsdk to that path:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">PATH</span>=<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>cygdrive<span style="color: #000000; font-weight: bold;">/</span>c<span style="color: #000000; font-weight: bold;">/</span>alchemy<span style="color: #000000; font-weight: bold;">/</span>achacks:<span style="color: #000000; font-weight: bold;">/</span>cygdrive<span style="color: #000000; font-weight: bold;">/</span>c<span style="color: #000000; font-weight: bold;">/</span>flexsdk<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #007800;">$PATH</span></pre></div></div>

<p>Please take note of the /cygdrive/c portions of the path.  This is how you access your drives from within cygwin.  If you want to access the “e” drive for instance it would be /cygdrive/e/ and not e: as it is within windows.</p>
<p>We also need to make sure all of the Alchemy setup scripts run when we start cygwin.  So right before the “PATH=” line that you just edited, we need to add the following:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">source</span> <span style="color: #000000; font-weight: bold;">/</span>cygdrive<span style="color: #000000; font-weight: bold;">/</span>c<span style="color: #000000; font-weight: bold;">/</span>alchemy<span style="color: #000000; font-weight: bold;">/</span>alchemy-setup</pre></div></div>

<p>You can now save and close the “profile” file.</p>
<p>If you installed the rxvt package (its a replacement terminal, because the default terminal for cygwin is terrible) then please open your c:\cygwin\cygwin.bat file and make it look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">@</span><span style="color: #7a0874; font-weight: bold;">echo</span> off
 C:
 chdir \cygwin\bin
 start rxvt <span style="color: #660033;">-sr</span> <span style="color: #660033;">-sl</span> <span style="color: #000000;">10000</span> <span style="color: #660033;">-fg</span> white <span style="color: #660033;">-bg</span> black <span style="color: #660033;">-fn</span> fixedsys <span style="color: #660033;">-fb</span> fixedsys <span style="color: #660033;">-tn</span> cygwin <span style="color: #660033;">-e</span> <span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">bash</span> <span style="color: #660033;">--login</span> <span style="color: #660033;">-i</span></pre></div></div>

<p>Now run the cygwin.bat file and it will drop you into a cygwin terminal.  We have to do one last bit of configuration and then we are done! Yay!</p>
<p>You will probably get a bit of messaging about Skeleton files being copied over.  This is good <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Here we have to setup alchemy.  So from the terminal type:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span> <span style="color: #000000; font-weight: bold;">/</span>cygdrive<span style="color: #000000; font-weight: bold;">/</span>c<span style="color: #000000; font-weight: bold;">/</span>alchemy</pre></div></div>

<p>This will put you in the Alchemy directory on your C: drive.<br />
From here type:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">.<span style="color: #000000; font-weight: bold;">/</span>config</pre></div></div>

<p>You should get a screen that looks like this:<br />
<img src="http://labs.byhook.com/images/alchemyimages/cygwin_alchemy_config.png" alt="" /></p>
<p>Now close the cygwin window, and in your text editor open the c:\alchemy\alchemy_setup file.<br />
Find the lines:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># Set this variable if you do not want to use the adl executable from your path</span>
<span style="color: #666666; font-style: italic;">#export ADL=/path/to/your/adl (or adl.exe)</span></pre></div></div>

<p>and replace the #export line with the following (be sure to remove the # at the beginning of the line)</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #007800;">ADL</span>=<span style="color: #000000; font-weight: bold;">/</span>cygdrive<span style="color: #000000; font-weight: bold;">/</span>c<span style="color: #000000; font-weight: bold;">/</span>flexsdk<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>adl.exe</pre></div></div>

<p>You will also need to locate this line:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #007800;">ASC</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span>cygpath <span style="color: #660033;">-m</span> <span style="color: #660033;">-s</span> <span style="color: #660033;">-p</span> <span style="color: #007800;">$ALCHEMY_HOME</span><span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>asc.jar<span style="color: #7a0874; font-weight: bold;">&#41;</span></pre></div></div>

<p>and change it to:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #007800;">ASC</span>=<span style="color: #007800;">$ALCHEMY_HOME</span><span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>asc.jar</pre></div></div>

<p>The POSIX to Windows path conversion doesn’t seem to work.  This change will throw a warning about POSIX file paths, but everything will work just fine.<br />
Save that, and restart cygwin (c:\cygwin\cygwin.bat)</p>
<p>That should do it!  You should have have function cygwin/alchemy environment.<br />
So lets compile something shall we?<br />
Type:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span> <span style="color: #000000; font-weight: bold;">/</span>cygdrive<span style="color: #000000; font-weight: bold;">/</span>c<span style="color: #000000; font-weight: bold;">/</span>alchemy<span style="color: #000000; font-weight: bold;">/</span>samples<span style="color: #000000; font-weight: bold;">/</span>stringecho</pre></div></div>

<p>Then type this to remove the old .swc:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">rm</span> stringecho.swc</pre></div></div>

<p>Now you can compile this sample provided by Adobe to make sure everything is cool.</p>
<p>First turn on the Alchemy gcc compiler, type:<br />
(you will only need to do this once per cygwin session)</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">alc-on</pre></div></div>

<p>Then run the actual link and compile, type:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">gcc</span> stringecho.c <span style="color: #660033;">-O3</span> <span style="color: #660033;">-Wall</span> <span style="color: #660033;">-o</span> stringecho.swc</pre></div></div>

<p>If you run into troubles with the swc being corrupt you may need to include the -swc switch as suggested by &#8220;coderyy&#8221; in the comments.  Thanks for the tip!</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">gcc</span> stringecho.c <span style="color: #660033;">-O3</span> <span style="color: #660033;">-Wall</span> <span style="color: #660033;">-swc</span> <span style="color: #660033;">-o</span> stringecho.swc</pre></div></div>

<p>With any luck you will get a screen that looks like this:<br />
<img src="http://labs.byhook.com/images/alchemyimages/cygwin_compile.png" alt="" /></p>
<p>(yes you can ignore the “Arguments Dropped” warning)</p>
<p>if you type ‘ls’ (short for list, same as ‘dir’ in dos) you will see your shiny new stringecho.swc <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In the next episode we will go over how to use that .swc and how to create your very own .c files that you can access from Flash!</p>
<p>As always if you want to get notified of new posts in this series, (or any of our labs posts) please &#8216;Like&#8217; us on Facebook:<br />
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FHook%2F106749192712698&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe></p>
<p>Or you can Follow me on Twitter:<br />
<a href="http://www.twitter.com/JakeCallery"><img src="http://twitter-badges.s3.amazonaws.com/follow_me-c.png" alt="Follow JakeCallery on Twitter"/></a></p>
<p>Thanks for reading and good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/03/01/alchemy-series-part-2-environment-setup/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Ogg Vorbis Encoder + Decoder for Flash</title>
		<link>http://labs.byhook.com/2011/02/22/ogg-vorbis-encoder-decoder-for-flash/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ogg-vorbis-encoder-decoder-for-flash</link>
		<comments>http://labs.byhook.com/2011/02/22/ogg-vorbis-encoder-decoder-for-flash/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 16:01:03 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[Alchemy]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[Audio]]></category>
		<category><![CDATA[Decoder]]></category>
		<category><![CDATA[Encoder]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Ogg]]></category>
		<category><![CDATA[Ogg Vorbis]]></category>
		<category><![CDATA[Sound]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1469</guid>
		<description><![CDATA[So we finally have both halves of the equation in one convenient library for all of your Ogg Vorbis needs!  Our new swc brings the ability to Encode and Decode Ogg Vorbis formatted audio files.  The Ogg Vorbis format is superior to MP3 in just about all categories.  High audio fidelity can be maintained at low bit rates, which makes for great sound quality at a very low file size.  Check out the post and give our examples a whirl!]]></description>
			<content:encoded><![CDATA[<p>Hook Ogg Vorbis Library: Encoding/Decoding</p>
<p>*** POST UPDATED: Crackling issue fixed with &#8220;on the fly&#8221; decoder, please see below ***</p>
<p>So we finally have both halves of the equation!  You can now, encode audio to the Ogg Vorbis format as well as decode it, all from the same library.  A significant portion of the Decoding code was brought over from the Ogg Vorbis decoder on the <a href="http://labs.adobe.com/wiki/index.php/Alchemy:Libraries">Adobe Libraries</a> page, written by Branden Hall of <a href="http://www.automatastudios.com/">Automatastudios.com</a>.  Thanks Branden!</p>
<p>So a fair bit of the library was rearranged (<a href="http://labs.byhook.com/2011/02/15/ogg-vorbis-encoder-for-flash-alchemy-series-part-1/">from our previous version</a>) to make it a touch easier to use.  First up, the main example.  This shows off most of the features in the library.  Keep scrolling for the second example which demonstrates &#8220;on the fly&#8221; decoding.</p>
<h4 style="font-size: 1em">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_OggVorbisLib_1914708510"
			class="flashmovie"
			width="550"
			height="430">
	<param name="movie" value="/oggvorbislib/swf/OggVorbisLib.swf" />
	<param name="bgcolor" value="#333333" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="/oggvorbislib/swf/OggVorbisLib.swf"
			name="fm_OggVorbisLib_1914708510"
			width="550"
			height="430">
		<param name="bgcolor" value="#333333" />
	<!--<![endif]-->
		<br />
<a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a><br />

	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><br />
</h4>
<p>Download The <a href="http://labs.byhook.com/oggvorbislib/HookOggVorbisLibExamples.zip">Library and Examples</a><br />
Download Just <a href="http://labs.byhook.com/oggvorbislib/HookOggVorbisLib.zip">The library</a></p>
<p>If you have read our last <a href="http://labs.byhook.com/2011/02/15/ogg-vorbis-encoder-for-flash-alchemy-series-part-1/">post</a>, you already know about some of the encoder features, but there have been a few changes, so we will go over each of them again.</p>
<p>The fist major change is there is now an OggManager class.  This class is a wrapper for all of the alchemy bits, and is the main point of control for encoding and decoding Ogg Vorbis data.  The quick answer is simply new up an instance of the OggManager, and then call .encode() or .decode().  From there you can listen for some events, and do what you need to do.  For the long answer, lets start with the encoder portion of the library.</p>
<p><strong>Encoder</strong><br />
The encoder works in 2 phases, first, the sound data is converted to a 44100, 16bit stereo pcm WAV format and is then encoded to Ogg Vorbis.  The encoding process can take some time depending on how much data you are encoding.  So this process is a fully asynchronous process.  You can keep track of the progress by listening for the following events:<br />
OggManagerEvent.ENCODE_BEGIN<br />
OggManagerEvent.ENCODE_COMPLETE<br />
OggManagerEvent.ENCODE_PROGRESS<br />
OggManagerEvent.ENCODE_CANCEL<br />
OggManagerEvent.WAV_ENCODE_BEGIN<br />
OggManagerEvent.WAV_ENCODE_COMPLETE<br />
OggManagerEvent.WAV_ENCODE_CANCEL<br />
OggManagerEvent.WAV_ENCODE_PROGRESS</p>
<p>The encoding process can be canceled at any time by calling .cancel() on the OggManager instance.  Please note that the process may not cancel right away, so please listen for the OggManagerEvent.ENCODE_CANCEL event to know when exactly the cancel has happened.</p>
<p>The method signature for the encode() method looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> encode<span style="color: #000000;">&#40;</span>$rawBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span>, $oggComments<span style="color: #000000; font-weight: bold;">:</span>OggComments=<span style="color: #0033ff; font-weight: bold;">null</span>, $oggQuality<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Number</span>=<span style="color: #000000; font-weight:bold;">0.5</span>, $wavLoopsPerYield=<span style="color: #000000; font-weight:bold;">10</span>, $vorbisLoopsPerYield<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>=<span style="color: #000000; font-weight:bold;">1</span>, $progressNotifications<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Boolean</span>=<span style="color: #0033ff; font-weight: bold;">true</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span></pre></div></div>

<p>$rawBytes is a byte array containg the raw flash sound data that is to be converted.  $oggComments is an OggComments object that contains the tags/comments for the Ogg Vorbis file.  These include things like Artist, Album, Title, etc&#8230;  Next is the $oggQuality setting.  This number ranges from -0.1 to 1 according to the xiph.org docs.  1 being the highest (largest file size, highest bitrate) and -0.1 being the lowest.  I’ve played with different settings (as can you in the example above), and found that it is really amazing how low of a bitrate and how small of a file size you can get without sacrificing too much audio fidelity. $wavLoopsPerYield and $vorbisLoopsPerYield are performance settings.  These basically decide how much time Alchemy gets to do the encode, before giving up its time slice to flash.  The higher the number, the quicker the encode, but the slower flash will be.  Lastly we have the $progressNotifications parameter.  If this is true, progress notification events will be dispatched.  Having this turned on, may slow the encode slightly, but without it, you won’t know how far along in the encode you are.  You will however get BEGIN, COMPLETE and CANCEL events in either case.  Currently the encoder still expects 44.1kHz, 16bit, Stereo data.  Possibly in the future support for more formats will be implemented.</p>
<p><strong>Decoder</strong><br />
The decoder can be used in two different ways.  The first is where you can give it ByteArray full of Ogg Vorbis encoded bytes and after a few moments, it will give you back raw flash sound data.  The other is to decode small chunks at a time, such as during the handling of a SAMPLE_DATA event when playing a sound.  The example at the top of the post, is an example of how to decode the entire file all at once.  The example below is how to decode the ogg file on the fly.</p>
<h4 style="font-size: 1em">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_DecodeOnTheFlyExample_1142396515"
			class="flashmovie"
			width="225"
			height="38">
	<param name="movie" value="/oggvorbislib/swf/DecodeOnTheFlyExample.swf" />
	<param name="bgcolor" value="#333333" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="/oggvorbislib/swf/DecodeOnTheFlyExample.swf"
			name="fm_DecodeOnTheFlyExample_1142396515"
			width="225"
			height="38">
		<param name="bgcolor" value="#333333" />
	<!--<![endif]-->
		<br />
<a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a><br />

	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><br />
</h4>
<p>Decoding the full file all at once is fairly trivial.  You can simply call .decode() on the OggManager instance:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #0033ff; font-weight: bold;">public</span> <span style="color: #339966; font-weight: bold;">function</span> <span style="color: #004993;">decode</span><span style="color: #000000;">&#40;</span>$oggBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span>, $samplesPerLoop<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>=<span style="color: #000000; font-weight:bold;">2048</span>, $delayPerLoopInMS<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>=<span style="color: #000000; font-weight:bold;">33</span>, $progressNotifications<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Boolean</span>=<span style="color: #0033ff; font-weight: bold;">true</span><span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span></pre></div></div>

<p>The method signature breaks down as follows:<br />
$oggBytes is the byteArray that contains your Ogg Vorbis encoded bytes from a file or wherever.  The second parameter is an integer that controls how many bytes are decoded per loop.  Just like the encoder, the decoding process is fully asynchronous.  More bytes per loop speeds up the decode, but slows down flash.  The third parameter controls how long to wait before kicking off another decode loop.  If your decode loops are taking a long time, you will want to increase this number so that it doesn’t start to stack up decoding loops.  Each chunk decode is handled by a timer, and the timer delay is set based on this parameter.  The last parameter tells the OggManager to dispatch progress events for the decoding process or not.  This is the same as with the encoder.  Decoding may be faster if you do not dispatch progress events.  BEGIN, COMPLETE and CANCEL events are always dispatched, regardless of this setting.</p>
<p>You can also keep track of the progress of the decode by listening for the following events:<br />
OggManagerEvent.DECODE_BEGIN<br />
OggManagerEvent.DECODE_COMPLETE<br />
OggManagerEvent.DECODE_PROGRESS<br />
OggManagerEvent.DECODE_CANCEL</p>
<p>The &#8220;On The Fly&#8221; decoding is very similar.  (please have a look ath the DecodeOnTheFlyExample.as and .fla files) The main difference is you have to initialize the decoder before you start decoding.  This is handled automatically if you are decoding the whole file at once but not if you are doing it on the fly.  </p>
<p>To do that you can simply:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">_oggManager.initDecoder<span style="color: #000000;">&#40;</span>_oggBytes<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>From there you can decode away, until you reach the end of the ogg bytes:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Make sound</span>
_sound = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">Sound</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
_sound.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span>SampleDataEvent.SAMPLE_DATA, handleSoundData, <span style="color: #0033ff; font-weight: bold;">false</span>, <span style="color: #000000; font-weight:bold;">0</span>, <span style="color: #0033ff; font-weight: bold;">true</span><span style="color: #000000;">&#41;</span>;
_soundChannel = _sound.<span style="color: #004993;">play</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> handleSoundData<span style="color: #000000;">&#40;</span>e<span style="color: #000000; font-weight: bold;">:</span>SampleDataEvent<span style="color: #000000;">&#41;</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
<span style="color: #000000;">&#123;</span><span style="color: #009900;">//handleSoundData</span>
	<span style="color: #6699cc; font-weight: bold;">var</span> result<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span>;
	<span style="color: #6699cc; font-weight: bold;">var</span> tmpBuffer<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span> = <span style="color: #0033ff; font-weight: bold;">new</span> <span style="color: #004993;">ByteArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
	result = _oggManager.getSampleData<span style="color: #000000;">&#40;</span>_oggManager.dataPtr, NUM_SAMPLES, _oggManager.audioInfo.blockAlign, _oggManager.audioInfo.sampleMultiplier, tmpBuffer<span style="color: #000000;">&#41;</span>;
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span>tmpBuffer.<span style="color: #004993;">length</span> <span style="color: #000000; font-weight: bold;">&lt;</span> NUM_SAMPLES <span style="color: #000000; font-weight: bold;">*</span> BYTES_PER_SAMPLE<span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span><span style="color: #009900;">//reset</span>
		<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Reset&quot;</span><span style="color: #000000;">&#41;</span>;
		<span style="color: #009900;">//Right now the only way to rewind is reseting the decoder</span>
		_oggManager.initDecoder<span style="color: #000000;">&#40;</span>_oggBytes<span style="color: #000000;">&#41;</span>;
		result = _oggManager.getSampleData<span style="color: #000000;">&#40;</span> NUM_SAMPLES, tmpBuffer<span style="color: #000000;">&#41;</span>;
	<span style="color: #000000;">&#125;</span><span style="color: #009900;">//reset</span>
&nbsp;
	tmpBuffer.<span style="color: #004993;">position</span> = <span style="color: #000000; font-weight:bold;">0</span>;	
	<span style="color: #0033ff; font-weight: bold;">while</span> <span style="color: #000000;">&#40;</span>tmpBuffer.<span style="color: #004993;">bytesAvailable</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span><span style="color: #009900;">//feed</span>
		<span style="color: #009900;">//feed data</span>
		e.<span style="color: #004993;">data</span>.<span style="color: #004993;">writeFloat</span><span style="color: #000000;">&#40;</span>tmpBuffer.<span style="color: #004993;">readFloat</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;		<span style="color: #009900;">//Left Channel</span>
		e.<span style="color: #004993;">data</span>.<span style="color: #004993;">writeFloat</span><span style="color: #000000;">&#40;</span>tmpBuffer.<span style="color: #004993;">readFloat</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;		<span style="color: #009900;">//Right Channel</span>
	<span style="color: #000000;">&#125;</span><span style="color: #009900;">//feed</span>
&nbsp;
<span style="color: #000000;">&#125;</span><span style="color: #009900;">//handleSoundData</span></pre></div></div>

<p>The important part is the getSampleData line:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">oggManager.getSampleData<span style="color: #000000;">&#40;</span>NUM_SAMPLES, tmpBuffer<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>The first parameter is how many flash sound samples you want back from the decoding.  The second parameter is where those decoded bytes are stored.  As you can see in the example code above  we simply store the decoded bytes into tmpBuffer and then write those bytes back to the SAMPLE_DATA event.  Its as simple as that.  The one thing to be aware of however, is that seeking is not currently supported.  So once you reach the end of the decode, you will need to initialize the decoder again to start back at the beginning of the ogg vorbis data.  So depending on your needs you may want to cache this data as its decoded in a byte array for later use.  But like I said, it kind of depends on what exactly you are doing with the data.</p>
<p>Please check out the <a href="http://labs.byhook.com/oggvorbislib/HookOggVorbisLibExamples.zip">Examples</a> and feel free to just download the <a href="http://labs.byhook.com/oggvorbislib/HookOggVorbisLib.zip">Wrapper and SWC</a>.</p>
<p>In the next Alchemy installment we will go over getting an Alchemy Environment setup for Windows, and go through recompiling the sources for the SWC.  From there we will talk about how to write your own Alchemy code, as well as other tips and tricks we have learned along the way.</p>
<p>Until next time you can get updates from our Facebook page:<br />
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FHook%2F106749192712698&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe></p>
<p>Or you can follow me on Twitter:<br />
<a href="http://www.twitter.com/JakeCallery"><img src="http://twitter-badges.s3.amazonaws.com/follow_me-c.png" alt="Follow JakeCallery on Twitter"/></a></p>
<p>Good luck, and please let us know if you use this in a cool project, we would love to see it!</p>
<p>********** UPDATE **********<br />
<img src="http://labs.byhook.com/oggvorbislib/images/farnesworth.png" alt="Good News Everyone" /><br />
Good news everyone!  I fixed the crackling issue with the &#8220;on the fly&#8221; realtime decoder.  It should now function properly with clean (not clipped) sound.  The issue turned out to be that we were dropping unused bytes.  So now all of the bytes are fed to the SAMPLE_DATA event, instead of just the requested number of samples.  The block alignment would sometimes force more bytes to be decoded than the exact number of requested samples.  The code and downloads have been updated, and the code in the post has also been updated.<br />
Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/02/22/ogg-vorbis-encoder-decoder-for-flash/feed/</wfw:commentRss>
		<slash:comments>70</slash:comments>
		</item>
		<item>
		<title>Ogg Vorbis Encoder for Flash: Alchemy Series Part 1</title>
		<link>http://labs.byhook.com/2011/02/15/ogg-vorbis-encoder-for-flash-alchemy-series-part-1/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ogg-vorbis-encoder-for-flash-alchemy-series-part-1</link>
		<comments>http://labs.byhook.com/2011/02/15/ogg-vorbis-encoder-for-flash-alchemy-series-part-1/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 16:08:51 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[Alchemy]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Encoder]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Ogg]]></category>
		<category><![CDATA[Vorbis]]></category>

		<guid isPermaLink="false">http://labs.byhook.com/?p=1425</guid>
		<description><![CDATA[An Ogg Vorbis encoder for flash is something we have wanted for quite a while, but there didn't seem to be any readily available.  After much searching, we decided it was time to make one.  So we downloaded Xiph.org's example code and had at it.  Feel free to download the example and give it a go!]]></description>
			<content:encoded><![CDATA[<p>Firstly, what you came here for:</p>
<p>Make sure you have a mic hooked up, and click record.  Once you have recorded some sound, click, stop.  At this point you can fill in some info for the file (these are used to set the metadata/comments/tags). Then click Encode to watch it encode the data.  Progress of the encode and the time it took to encode is listed at the right.  Finally you can click Save, and you can save your newly encoded .ogg file to your local machine.  Please note that the performance tuning in this example is set to keep flash as responsive as possible while the encoding is taking place.  This naturally slows the encoding performance.  Please see below to learn how to adjust the tuning to your needs.  Also, before we get started, I would like to mention, that we are planning on creating a series of posts about what we have learned working with <a href="http://labs.adobe.com/technologies/alchemy/">Adobe Alchemy</a> in the coming weeks.  Now, with that out of the way, on with the show!</p>
<h4 style="font-size: 1em">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_OggVorbisEncoderExample_1827077982"
			class="flashmovie"
			width="550"
			height="400">
	<param name="movie" value="/oggencoder/OggVorbisEncoderExample.swf" />
	<param name="bgcolor" value="#333333" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="/oggencoder/OggVorbisEncoderExample.swf"
			name="fm_OggVorbisEncoderExample_1827077982"
			width="550"
			height="400">
		<param name="bgcolor" value="#333333" />
	<!--<![endif]-->
		<br />
<a href="http://adobe.com/go/getflashplayer"><img style="border: 0px initial initial" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a><br />

	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><br />
</h4>
<p>You can download the source and encoder swc for this example <a href="http://labs.byhook.com/oggencoder/ovexample.zip">here</a>:<br />
<a href="http://labs.byhook.com/oggencoder/ovexample.zip">http://labs.byhook.com/oggencoder/ovexample.zip</a></p>
<p><strong>Quick props to all of the authors/sites that helped me get started with Alchemy:</strong><br />
- Forcing stdin/stdout to deal with ActionScript ByteArrays:<br />
<a href="http://segfaultlabs.com/devlogs/alchemy-asynchronous-jpeg-encoding">http://segfaultlabs.com/devlogs/alchemy-asynchronous-jpeg-encoding</a></p>
<p>- flyield() example:<br />
<a href="http://segfaultlabs.com/devlogs/alchemy-asynchronous-jpeg-encoding">http://segfaultlabs.com/devlogs/alchemy-asynchronous-jpeg-encoding</a></p>
<p>- Process for compiling multiple source files under gcc:<br />
<a href="http://ccgi.codegadget.plus.com/blog/2010/04/03/alchemy-c-library-1/">http://ccgi.codegadget.plus.com/blog/2010/04/03/alchemy-c-library-1/</a></p>
<p>-Alchemy Documentation<br />
<a href="http://labs.adobe.com/wiki/index.php/Alchemy:Documentation:Developing_with_Alchemy:C_API">http://labs.adobe.com/wiki/index.php/Alchemy:Documentation:Developing_with_Alchemy:C_API</a></p>
<p>More on all of those things coming in the next few posts!</p>
<p><strong>Encoder Usage</strong><br />
Currently this encoder takes 44.1kHz, 16bit, stereo wav formatted PCM data to do the encode (Adobe’s WAVWriter class is used to do the wav conversion in this example).  This version allows for different quality settings, async performance tuning, and the recommended Ogg Comment Tags. </p>
<p>I’m hoping the next release of our encoder will handle more types of input (different bitrates, mono support, etc..) as well as the ability to cancel the encode at any time.  I am also hoping to get a decoder working within this same package, for convenience.  For now, however I would suggest using the very well done <a href="http://labs.adobe.com/wiki/index.php/Alchemy:Libraries">Ogg Vorbis decoder</a> from Branden Hall at <a href="http://automatastudios.com/">automatastudios.com</a>.  If you check out the <a href="http://labs.byhook.com/2009/12/04/flash-10-audio-sequencer/">sources for our Sequencer</a>, you can see some examples of how to use the Decoder from Automata Studios.  </p>
<p>Additionally in the coming weeks we will be posting about making use of <a href="http://labs.adobe.com/technologies/alchemy/">Alchemy</a> in general.  From setup through all the steps we took creating this encoder.  We will also be posting code snippets for commonly needed alchemy abilities, such as reading and writing to and from ByteArrays, calling ActionScript methods from Alchemy, and a slew of other tid-bits that were hard to find online. </p>
<p>During those posts I will be releasing the source code to the encoder, but I have to read through all of the licenses for the different pieces of the Xiph example code to be sure that I’m not violating any of those by redistributing modified versions of Xiph.org’s sources.  Usually this just means that specific comments have to stay intact, and probably a readme file sent along with the sources.  But until then, I figured the .swc could be useful to people as is <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>For more immediate notifications of updates to the encoder you can:<br />
<a href="http://www.twitter.com/JakeCallery"><img src="http://twitter-badges.s3.amazonaws.com/follow_me-c.png" alt="Follow JakeCallery on Twitter"/></a></p>
<p>Or get updates from our Facebook page:<br />
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FHook%2F106749192712698&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe></p>
<p>Wow, it felt dirty saying that, but this is where we will be posting about updated versions of the encoder.</p>
<p>Much of the encoder code was taken from the example C code on the <a href="http://xiph.org/">Xiph.org</a> website.  It was then altered to expose parts to Flash as well as altered to allow for asynchronous operation.  The Vorbis and Ogg C libraries were modified for compilation through <a href="http://labs.adobe.com/technologies/alchemy/">Adobe Alchemy (FlaCC)</a>.  All of this was linked and archived to a .swc for use within flash.</p>
<p>Be sure to add the swc to the library in your IDE.  For Flash CS5, you will need to go to Publish Settings -> Flash Tab -> Script Settings -> Library Path Tab.  In there you can either add the path to the folder containing the swc, or you can add the swc itself. </p>
<p>As part of the example code there is an OggEncoder actionscript class.  This simplifies the use of the encoder swc.  </p>
<p>Use of the encoder is fairly simple.  First new up an instance of the OggEncoder, and listen for ENCODE_COMPLETE and ENCODE_PROGRESS events to keep track of the status.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Create a new instance of the encoder</span>
_oggEncoder = <span style="color: #0033ff; font-weight: bold;">new</span> OggEncoder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #009900;">//Listen for progress and complete events from the encoder (encode happens async)</span>
_oggEncoder.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span>OggEncoderEvent.ENCODE_COMPLETE, handleEncodeComplete, <span style="color: #0033ff; font-weight: bold;">false</span>, <span style="color: #000000; font-weight:bold;">0</span>, <span style="color: #0033ff; font-weight: bold;">true</span><span style="color: #000000;">&#41;</span>;
_oggEncoder.<span style="color: #004993;">addEventListener</span><span style="color: #000000;">&#40;</span>OggEncoderEvent.ENCODE_PROGRESS, handleEncodeProgress, <span style="color: #0033ff; font-weight: bold;">false</span>, <span style="color: #000000; font-weight:bold;">0</span>, <span style="color: #0033ff; font-weight: bold;">true</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>To start the encode progress, you will need to convert your sound data to a 44.1kHz, 16bit, 2Channel stereo wav file, with adobe’s WAVWriter Class.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Setup up wav writer for flash sound -&gt; wav conversion</span>
<span style="color: #6699cc; font-weight: bold;">var</span> wavWriter<span style="color: #000000; font-weight: bold;">:</span>WAVWriter = <span style="color: #0033ff; font-weight: bold;">new</span> WAVWriter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
wavWriter.numOfChannels = <span style="color: #000000; font-weight:bold;">2</span>;
wavWriter.sampleBitRate = <span style="color: #000000; font-weight:bold;">16</span>;
wavWriter.samplingRate = <span style="color: #000000; font-weight:bold;">44100</span>;
&nbsp;
<span style="color: #009900;">//Save converted data to _wavBytes (I would suggest modifying the</span>
<span style="color: #009900;">// processSamples method to work in small chunks that you call from</span>
<span style="color: #009900;">//a timer so you don't lock up the UI during the processing)</span>
_wavBytes.<span style="color: #004993;">position</span> = <span style="color: #000000; font-weight:bold;">0</span>;
_recData.<span style="color: #004993;">position</span> = <span style="color: #000000; font-weight:bold;">0</span>;
wavWriter.processSamples<span style="color: #000000;">&#40;</span>_wavBytes, _recData, <span style="color: #000000; font-weight:bold;">44100</span>, <span style="color: #000000; font-weight:bold;">2</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>From there you can simply call:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Start the encode</span>
_oggEncoder.encode<span style="color: #000000;">&#40;</span>_wavBytes, oggComments<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>While its encoding OggEncoderEvent.ENCODE_PROGRESS events are dispatched.  The &#8220;data&#8221; property on the event contains a number 0 &#8211; 1 which represents the percent complete.</p>
<p>Lastly an OggEncoderEvent.ENCODE_COMPLETE event will be dispatched when the encoding has finished.</p>
<p>If you don’t want to go through the OggEncoder class, you can directly access the exposed functions in the swc:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//do encoding</span>
startAsyncEncode<span style="color: #000000;">&#40;</span>onCompleteMethod<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Function</span>, clientObj<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Object</span>, wavBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span>, oggBytes<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">ByteArray</span>, <span style="color: #004993;">quality</span><span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">Number</span>, numLoopsPerYield<span style="color: #000000; font-weight: bold;">:</span><span style="color: #004993;">int</span>, commentObj<span style="color: #000000; font-weight: bold;">:</span>OggComments<span style="color: #000000;">&#41;</span>
&nbsp;
<span style="color: #009900;">//get version number as String: &quot;0.5&quot;</span>
getVersionNumber<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
&nbsp;
<span style="color: #009900;">//get version label as String: &quot;beta&quot; </span>
getVersionLabel<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p>First import the encoder classes</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #0033ff; font-weight: bold;">import</span> cmodule.oggvorbisencoder.CLibInit;</pre></div></div>

<p>Then create an instance of the Alchemy Lib:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Alchemy Loader object</span>
<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #6699cc; font-weight: bold;">var</span> _loader<span style="color: #000000; font-weight: bold;">:</span>CLibInit;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #009900;">//Setup the alchemy library</span>
_loader = <span style="color: #0033ff; font-weight: bold;">new</span> CLibInit;
_lib = _loader.<span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Lastly do some encoding:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;"><span style="color: #3f5fbf;">/***************
* This is the actual call the the Alchemy Ogg Encoder.
* Parameters:
* 
* encodeComplete: 
* method called when encoding is complete
* 
* this: 
* the object passed in here is required to have a method called handleProgress.
* when there is progress, the method is called with the number of bytes read from the wav 
* ByteArray, and the length of the wav ByteArray is passed to it.
* (see below for implementation)
* 
* _wavBytes: 
* the 44.1kHz, 16Bit, 2 Channel wav encoded bytes (ByteArray)
* 
* _encodedBytes: 
* a ByteArray to store the Ogg encoded bytes in.
* 
* 0.5: 
* quality setting for Ogg (valid range is 0.1 to 1)
* 
* 1: 
* number of ogg pages before yielding back to flash player 
* (low numbers - flash player stays faster, high numbers - encoding faster)  
* I would really just stick with 1 here
* 
* $oggComments: 
* this is the comment value object for filling in the comment tags for the Ogg file.
****************/</span>
&nbsp;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Wav Bytes: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> _wavBytes.<span style="color: #004993;">length</span> <span style="color: #000000; font-weight: bold;">+</span> <span style="color: #990000;">&quot; / &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> _wavBytes.<span style="color: #004993;">position</span><span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Enc Bytes: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> _encodedBytes.<span style="color: #004993;">length</span> <span style="color: #000000; font-weight: bold;">+</span> <span style="color: #990000;">&quot; / &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> _encodedBytes.<span style="color: #004993;">position</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Version Number: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> _lib.getVersionNumber<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Version Label: &quot;</span> <span style="color: #000000; font-weight: bold;">+</span> _lib.getVersionLabel<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
_lib.startAsyncEncode<span style="color: #000000;">&#40;</span>encodeComplete, <span style="color: #0033ff; font-weight: bold;">this</span>, _wavBytes, _encodedBytes, <span style="color: #000000; font-weight:bold;">0.5</span>, <span style="color: #000000; font-weight:bold;">1</span>, $oggComments<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>You can also call getVersionNumber() and getVersionLabel() on the library and it will return the current version info of the swc as an ActionScript String.</p>
<p>That about wraps up the technical portion.  If you are interested in the story behind the project keep reading <img src='http://labs.byhook.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>A quick history of the project</strong><br />
Off and on for the last few months I’ve been playing around with various parts of the audio world in Flash and Air.  Eventually each project hit the same roadblock, saving out the final audio performance.  Its fairly trivial to save out the raw byte data to a file and load that back in.  But of course the issue with that is the file size. As it is, well, gigantic.  At first I started looking around for MP3 encoders already built for flash.  I came across this <a href="http://code.google.com/p/flash-kikko/">port of the Shine mp3 encoder</a> as basically the only viable option.  While its pretty awesome in its own right, its still fairly limited in terms of sound quality, and the encoding process is rather slow.  There were a couple of other things that made mp3 less of an attractive option as well.  The first issue is the odd licensing scheme for the mp3 format.  Since I’m no lawyer, it was a bit scary trying to build an encoder from the published spec.  Lines like <a href="http://en.wikipedia.org/wiki/MP3#Going_public">this</a> &#8220;Implementers of the standard were supposed to devise their own algorithms suitable for removing parts of the information from the audio input.&#8221; made me nervous, probably without warrant.  However, there was another reason that mp3 wasn’t a good fit for the projects, frame padding.  As discovered while we were building our <a href="http://labs.byhook.com/2009/12/04/flash-10-audio-sequencer/">Sequencer</a> mp3’s won’t loop smoothly.  It seems that if a frame of the mp3 is not full, it gets padded.  This padding causes a very noticeble gap in playback.  Therefore smooth looping without some sort of gapless playback support from the <a href="http://www.rockbox.org/tracker/11891">encoder and decoder is impossible</a>.  Thus it was time to look for another format. Ogg Vorbis be thy name.  </p>
<p>Ogg Vorbis is completely open, and is of very high quality.  From the <a href="http://xiph.org/vorbis/">Xiph.org</a> page:<br />
&#8220;Ogg Vorbis is a fully open, non-proprietary, patent-and-royalty-free, general-purpose compressed audio format for mid to high quality (8kHz-48.0kHz, 16+ bit, polyphonic) audio and music at fixed and variable bitrates from 16 to 128 kbps/channel. This places Vorbis in the same competitive class as audio representations such as MPEG-4 (AAC), and similar to, but higher performance than MPEG-1/2 audio layer 3, MPEG-4 audio (TwinVQ), WMA and PAC.&#8221;</p>
<p>Yay!</p>
<p>An Ogg Vorbis file doesn’t have the same issues with gapless playback as mp3, and seems to make smaller files, at least from my initial testing, which isn’t super extensive.  Additionally encoding performance is pretty good.</p>
<p>The problem was, I could only find an <a href="http://labs.adobe.com/wiki/index.php/Alchemy:Libraries">Ogg Vorbis Decoder</a> for flash.  Mind you its an excellent decoder written by Branden Hall at <a href="http://automatastudios.com">automatastudios.com</a>, but that only gets us half way.  Some further looking around revealed that <a href="http://blog.andre-michelle.com/2008/first-audiotool-live-recorded-vorbis-encoded-session/">Andre Michelle</a> and <a href="http://http://blog.joa-ebert.com/2008/07/24/as3-vorbis-encoder/">Joa Ebert</a> had ported a java version of the encoder to AS3.  So I started trying to do that, but stopped almost immediately when I came across the use of 64bit ints in the Java code.  Flash’s ints are only 32bits wide, and since the codebase was so big, I didn’t want to try and merry two 32bit ints together everywhere a 64bit integer was needed.  So began the trip down Alchemy Lane.  We will be doing a series of posts about Alchemy in the coming weeks, so stay tuned! </p>
]]></content:encoded>
			<wfw:commentRss>http://labs.byhook.com/2011/02/15/ogg-vorbis-encoder-for-flash-alchemy-series-part-1/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

