<?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>toxiclibs &#187; Usage</title>
	<atom:link href="http://toxiclibs.org/category/usage/feed/" rel="self" type="application/rss+xml" />
	<link>http://toxiclibs.org</link>
	<description>Building blocks for computational design</description>
	<lastBuildDate>Tue, 20 Dec 2011 17:03:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Tutorials galore</title>
		<link>http://toxiclibs.org/2011/05/tutorials-galore/</link>
		<comments>http://toxiclibs.org/2011/05/tutorials-galore/#comments</comments>
		<pubDate>Tue, 10 May 2011 22:08:28 +0000</pubDate>
		<dc:creator>toxi</dc:creator>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Usage]]></category>

		<guid isPermaLink="false">http://toxiclibs.org/?p=476</guid>
		<description><![CDATA[The ongoing lack of tutorials is still one of the most pressing issues to resolve for me &#038; everyone else using (or trying to use) these libraries. Add to this the recent lack of updates to this blog, it all might give the illusion the project itself is stagnating. This couldn&#8217;t be further from the [...]]]></description>
			<content:encoded><![CDATA[<p>The ongoing lack of tutorials is still one of the most pressing issues to resolve for me &#038; everyone else using (or trying to use) these libraries. Add to this the recent lack of updates to this blog, it all might give the illusion the project itself is stagnating. This couldn&#8217;t be further from the truth. In fact, the past few months have seen an incredible uptake of interest as well as development effort (93 revisions since beginning of the year), but I&#8217;m also close to reaching the point where I&#8217;ll impose a temporary new feature freeze as soon as version 0021 has been released within the next 6 weeks. 0022 will most likely be far more focused on a new, much improved system for documentation and a new website&#8230;</p>
<p>In the meanwhile, I&#8217;ve been doing my best to respond to concrete issues &#038; tasks people were trying solve on the Processing forums as well as the issue tracker. The <a href="http://openprocessing.org/portal/?userID=4530" onclick="pageTracker._trackPageview('/outgoing/openprocessing.org/portal/?userID=4530&amp;referer=');">list of demos on OpenProcessing</a> has grown too. And thanks to personal heroes of mine, like <a href="http://www.flong.com/" onclick="pageTracker._trackPageview('/outgoing/www.flong.com/?referer=');">Golan Levin</a>, <a href="http://shiffman.net" onclick="pageTracker._trackPageview('/outgoing/shiffman.net?referer=');">Daniel Shiffman</a> and their students, there&#8217;re also a number of very interesting student projects this year, which are utilising the libraries and (in some cases) have their code explorations shared (like good citizens tend to do :). A round-up post of these will follow shortly.</p>
<p>Speaking of missing examples and small projects, teaching workshops has been another well under-documented effort of mine. For most of them, I&#8217;ve created a Mercurial repository on <a href="http://learn.postspectacular.com/hg/" onclick="pageTracker._trackPageview('/outgoing/learn.postspectacular.com/hg/?referer=');">this website</a> and I&#8217;d encourage you to download and play with these examples as well. A lot of them are more advanced than the examples bundled with each release, some utilize 3rd party libraries and all are generally full of comments, not just about library specific topics. Please also send your virtual thanks to all the unis &#038; institutions allowing this material to be shared!</p>
<p>Workshop repositories: <a href="http://learn.postspectacular.com/hg/" onclick="pageTracker._trackPageview('/outgoing/learn.postspectacular.com/hg/?referer=');">http://learn.postspectacular.com/hg/</a> &#8211; <strong>All source code is LGPL licensed unless stated otherwise.</strong></p>
<p>Before I get to the compiled list of mini-tutorials and discussions from the Processing forum, Amnon Owed has recently produced two excellent tutorials for this project and I sincerely hope his efforts will inspire other users to follow suit:</p>
<p><a href="http://amnonp5.wordpress.com/2011/04/23/working-with-toxiclibs/" onclick="pageTracker._trackPageview('/outgoing/amnonp5.wordpress.com/2011/04/23/working-with-toxiclibs/?referer=');">Working with toxiclibs, part #1</a> (polygons, voronoi explosions)<br />
<a href="http://www.creativeapplications.net/processing/working-with-toxiclibs-processing-tutorial/" onclick="pageTracker._trackPageview('/outgoing/www.creativeapplications.net/processing/working-with-toxiclibs-processing-tutorial/?referer=');">Working with toxiclibs &#038; Processing, part #2</a> (physics, colors, zoomlens)</p>
<p><iframe src="http://player.vimeo.com/video/22772055" width="680" height="382" frameborder="0"></iframe></p>
<p>List of recent forum threads (including lots of source code), sorted by subject:</p>
<h2>Interaction, events, multi-threading</h2>
<p><a href="http://forum.processing.org/topic/ipad-tuio-toxi-physics2d-concurrentmodificationexception#25080000000852035" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/ipad-tuio-toxi-physics2d-concurrentmodificationexception_25080000000852035?referer=');">iPad, TUIO &amp; particles with dynamic attraction behaviors</a><br />
<a href="http://forum.processing.org/topic/custom-events-event-listener#25080000000727107" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/custom-events-event-listener_25080000000727107?referer=');">Custom Events + Event listener?</a></p>
<p><img src="http://toxiclibs.org/wp-content/uploads/2011/05/voronoi.png" alt="" title="voronoi" width="600" height="600" class="aligncenter size-full wp-image-486" /></p>
<h2>Geometry</h2>
<p><a href="http://forum.processing.org/topic/toxiclib-voronoi-example-sketch" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/toxiclib-voronoi-example-sketch?referer=');">How to use the Toxiclibs Voronoi class?</a><br />
<a href="http://forum.processing.org/topic/2d-collision-detection-irregular-shapes-computer-vision-blobs" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/2d-collision-detection-irregular-shapes-computer-vision-blobs?referer=');">2D Collision detection &#8211; irregular shapes (computer vision blobs)</a><br />
<a href="http://forum.processing.org/topic/octree-visualization-toxiclibs#25080000000842257" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/octree-visualization-toxiclibs_25080000000842257?referer=');">Octree Visualization</a><br />
<a href="http://forum.processing.org/topic/toxiclibs-perlinnoise-to-specified-target-destination#25080000000764005" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/toxiclibs-perlinnoise-to-specified-target-destination_25080000000764005?referer=');">PerlinNoise to specified target destination</a><br />
<a href="http://forum.processing.org/topic/what-does-vec2d-heading-in-toxiclibs-do-exactly" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/what-does-vec2d-heading-in-toxiclibs-do-exactly?referer=');">What does Vec2D.heading() in Toxiclibs do exactly?</a><br />
<a href="http://forum.processing.org/topic/how-to-calculate-the-tangent-line-of-a-circle" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/how-to-calculate-the-tangent-line-of-a-circle?referer=');">How to calculate the tangent line of a circle?</a><br />
<a href="http://forum.processing.org/topic/mouse-within-a-certain-area#25080000000731001" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/mouse-within-a-certain-area_25080000000731001?referer=');">Mouse within a certain area</a><br />
<a href="http://forum.processing.org/topic/using-toxiclibs-geomutils-to-solve-the-pulley-problem#25080000000727111" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/using-toxiclibs-geomutils-to-solve-the-pulley-problem_25080000000727111?referer=');">using toxiclibs geomutils to solve the &#8220;pulley problem&#8221;</a></p>
<p><img src="http://toxiclibs.org/wp-content/uploads/2011/05/gpsflickr-680x510.jpg" alt="" title="gpsflickr" width="680" height="510" class="alignnone size-large wp-image-488" /></p>
<h2>Geo location (Twitter &amp; Flickr)</h2>
<p><a href="http://forum.processing.org/topic/gps-to-spherical-coordinates-with-vec3d-toxilibs#25080000000756005" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/gps-to-spherical-coordinates-with-vec3d-toxilibs_25080000000756005?referer=');">GPS to spherical coordinates with Vec3D &#038; toxilibs</a><br />
<a href="http://forum.processing.org/topic/geolocation-twitter-search-twitter4j#25080000000834814" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/geolocation-twitter-search-twitter4j_25080000000834814?referer=');">GeoLocation Twitter Search: Twitter4j</a><br />
<a href="http://forum.processing.org/topic/geolocation#25080000000772027" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/geolocation_25080000000772027?referer=');">Simple mapping of geolocated tweets</a></p>
<p><iframe src="http://player.vimeo.com/video/23319820" width="680" height="382" frameborder="0"></iframe></p>
<h2>Color</h2>
<p><a href="http://www.creativeapplications.net/processing/working-with-toxiclibs-processing-tutorial/" onclick="pageTracker._trackPageview('/outgoing/www.creativeapplications.net/processing/working-with-toxiclibs-processing-tutorial/?referer=');">Working with toxiclibs &#038; Processing, part #2</a><br />
<a href="http://forum.processing.org/topic/question-on-toxiclibs-colorutils-histogram#25080000000721113" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/question-on-toxiclibs-colorutils-histogram_25080000000721113?referer=');">Question on toxiclibs colorutils Histogram</a></p>
<p><img src="http://toxiclibs.org/wp-content/uploads/2011/05/andres-680x372.jpg" alt="" title="volumetric glgraphics" width="680" height="372" class="alignnone size-large wp-image-491" /></p>
<h2>Rendering</h2>
<p><a href="http://forum.processing.org/topic/glgraphics-toxiclibs-volumeutils" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/glgraphics-toxiclibs-volumeutils?referer=');">GLGraphics + Toxiclibs Volumeutils</a> (also see post on <a href="http://codeanticode.wordpress.com/2011/03/28/integrating-toxilibs-and-glgraphics/" onclick="pageTracker._trackPageview('/outgoing/codeanticode.wordpress.com/2011/03/28/integrating-toxilibs-and-glgraphics/?referer=');">codeanticode</a>)<br />
<a href="http://forum.processing.org/topic/drawing-a-dotted-dashed-arc#25080000000715416" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/drawing-a-dotted-dashed-arc_25080000000715416?referer=');">Drawing a dotted/dashed arc</a><br />
<a href="http://forum.processing.org/topic/library-with-box-x-y-z-function#25080000000717206" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/library-with-box-x-y-z-function_25080000000717206?referer=');">Library with box(x,y,z) function?</a></p>
<h2>Math</h2>
<p><a href="http://forum.processing.org/topic/can-toxi-spline2d-be-use-for-more-than-vector-positions#25080000000749048" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/can-toxi-spline2d-be-use-for-more-than-vector-positions_25080000000749048?referer=');">Can toxi Spline2D be use for more than Vector positions?</a><br />
<a href="http://forum.processing.org/topic/convert-0-54321-to-0-54-and-convert-2-to-100#25080000000749044" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/convert-0-54321-to-0-54-and-convert-2-to-100_25080000000749044?referer=');">convert 0.54321 to 0.54 and convert 2 to 100</a></p>
<h2>XML (JAXB)</h2>
<p>These two threads are about JAXB, which is indirectly referenced by various toxiclibs geometry types in order to store them as XML. In anyway, many users are interested in data visualization and JAXB is lightyears ahead of the default XML library bundled with Processing&#8230;</p>
<p><a href="http://forum.processing.org/topic/jaxb-tutorial-xml-parsing-with-style" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/jaxb-tutorial-xml-parsing-with-style?referer=');">JAXB tutorial: XML parsing with style</a><br />
<a href="http://forum.processing.org/topic/jaxb-tutorial-question" onclick="pageTracker._trackPageview('/outgoing/forum.processing.org/topic/jaxb-tutorial-question?referer=');">JAXB tutorial question</a></p>
<p>Last, but not least: If you have any similar questions, interest in running workshops at your university/company or any small tutorials to share, please do get in touch! ¡Muchas gracias!</p>
]]></content:encoded>
			<wfw:commentRss>http://toxiclibs.org/2011/05/tutorials-galore/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>simutils-0001: Gray-Scott reaction diffusion</title>
		<link>http://toxiclibs.org/2010/02/simutils-grayscott/</link>
		<comments>http://toxiclibs.org/2010/02/simutils-grayscott/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 08:05:39 +0000</pubDate>
		<dc:creator>toxi</dc:creator>
				<category><![CDATA[colorutils]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[simutils]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Usage]]></category>
		<category><![CDATA[volumeutils]]></category>

		<guid isPermaLink="false">http://toxiclibs.org/?p=217</guid>
		<description><![CDATA[This is part 2 of the discussion of the classes &#38; processes provided by the recently released simutils package. The first part of this series dealt with Diffusion-limited Aggregation (DLA) and this next process too is related to the simulated diffusion of particles. However, whereas the DLA process dealt with individual particles, this next one [...]]]></description>
			<content:encoded><![CDATA[<p>This is part 2 of the discussion of the classes &amp; processes provided by the recently released <a href="http://toxiclibs.org/category/simutils/">simutils</a> package. <a href="http://toxiclibs.org/2010/02/new-package-simutils/">The first part of this series dealt with Diffusion-limited Aggregation</a> (DLA) and this next process too is related to the simulated diffusion of particles. However, whereas the DLA process dealt with individual particles, this next one is only looking at the concentrations of particles of different &#8220;substances&#8221; in a two-dimensional simulation space.</p>
<p>The Gray-Scott reaction diffusion model is a member of a whole variety of <a href="http://en.wikipedia.org/wiki/Reaction-diffusion_system" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Reaction-diffusion_system?referer=');">RD systems</a>, popular largely due to its ability to produce a very varied number of biological looking (and behaving) patterns, both static and constantly changing. Some patterns are reminiscent of cell devision, gastrulation or the formation of spots &amp; stripes on furry animals. As with all RD models, these patterns are the result of an iterative process evaluating each cell of the simulation space based on the concentrations of the two main parameters (for Gray-Scott usually named <strong>f</strong> and <strong>K</strong>) of the reaction equation as well as taking into account the concentrations of these 2 substances in neighboring cells. So conceptually the reaction diffusion system lies somewhere between the isolated DLA process working with individual particles and the entirely rulebased evaluation of a cell&#8217;s neighborhood in traditional cellular automatas, which we will deal with in the next post.</p>
<p>The image below, by <a href="http://mrob.com/pub/comp/xmorphia/" onclick="pageTracker._trackPageview('/outgoing/mrob.com/pub/comp/xmorphia/?referer=');">Robert Munafo</a>, is a fantastically helpful map of possible patterns resulting from various combinations of the <strong>f</strong> and <strong>K</strong> coefficients. Click the image to go to his website and explore the parameters in more detail (there&#8217;re close-ups and videos of all interesting combinations).</p>
<p><a href="http://mrob.com/pub/comp/xmorphia/" onclick="pageTracker._trackPageview('/outgoing/mrob.com/pub/comp/xmorphia/?referer=');"><img class="alignnone size-large wp-image-245" title="gs-parameter-map" src="http://toxiclibs.org/wp-content/uploads/2010/02/gs-parameter-map-680x680.jpg" alt="GS parameter map" width="680" height="680" /></a></p>
<p>As with the other classes of the <a href="http://toxiclibs.org/category/simutils/">simutils</a> package, the GrayScott implementation comes with several small demos to help you get started. The most basic use case (<a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/HelloGrayScott/HelloGrayScott.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/HelloGrayScott/HelloGrayScott.pde?referer=');">HelloGrayScott</a>) is just setting up a simulation with default parameters and then allows you to draw in the simulation space with the mouse. Each frame, the reaction is updated, its new state translated into grayscale pixels and then rendered to the screen. The important thing to know here is that there&#8217;re 2 separate results states available, normally called the <strong>u</strong> and <strong>v</strong> buffers.</p>
<pre class="brush:java">
GrayScott gs;

// create a new simulation instance
// the "false" refers to a non-tiled space with walls
// set to true to create tiling patterns
gs=new GrayScott(width,height,false);

// configure the simulation params to:
// f=0.023, K=0.074
// diffusion speed for u buffer = 0.095
// diffusion speed for u buffer = 0.03
gs.setCoefficients(0.023,0.074,0.095,0.03);
</pre>
<p>The main <code>draw()</code> loop then just does this:</p>
<pre class="brush:java">
void draw() {
  if (mousePressed) {
    // set cells around mouse pos to max saturation
    gs.setRect(mouseX, mouseY,20,20);
  }
  loadPixels();
  // update simulation by 10 time steps per frame
  for(int i=0; i&lt;10; i++) gs.update(1);
  // read out the v buffer and translate into grayscale colors
  for(int i=0; i&lt;gs.v.length; i++) {
    float cellValue=gs.v[i];
    // the cell values in v are usually in the range 0.0 .. 0.33
    int col=255-(int)(min(255,cellValue*768));
    // use the col value for red, green and blue and set alpha to full opacity
    pixels[i]=col&lt;&lt;16|col&lt;&lt;8|col|0xff000000;
  }
  updatePixels();
}
</pre>
<p>To avoid this manual pixel pushing and enable us to make some of the subtle changes of densities more obvious, we can also use the handy (and also new) <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.color/toxi/color/ToneMap.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.color/toxi/color/ToneMap.java?referer=');"><code>ToneMap</code></a> class of the <a href="http://toxiclibs.org/category/colorutils/">colorutils</a> package. This allows us to map a number range to different positions (colors) on a multi-color gradient and so potentially better visualize the different densities. The basic usage of this class is shown below:</p>
<pre class="brush:java">
import toxi.color.*;

ToneMap toneMap;

// define a color gradient by adding colors at certain key points
// a gradient is like a 1D array with target colors at certain points
// all inbetween values are automatically interpolated (customizable too)
// this gradient here will contain 256 values
ColorGradient gradient=new ColorGradient();
gradient.addColorAt(0, NamedColor.BLACK);
gradient.addColorAt(128, NamedColor.RED);
gradient.addColorAt(192, NamedColor.YELLOW);
gradient.addColorAt(255, NamedColor.WHITE);

// now create a ToneMap instance using this gradient
// this maps the value range 0.0 .. 0.33 across the entire gradient width
// a 0.0 input value will be black, 0.33 white
toneMap=new ToneMap(0, 0.33, gradient);
</pre>
<p>Now we can refactor our Gray-Scott rendering code into something even simpler:</p>
<pre class="brush:java">
for(int i=0; i&lt;gs.v.length; i++) {
    // take a GS v value and turn it into a packed integer ARGB color value
    pixels[i]=toneMap.getARGBToneFor(gs.v[i]);
}
</pre>
<p>Btw. The <code>ToneMap</code> class is a nice example of the whole reusable &#8220;building block philosophy&#8221; of toxiclibs (and the object oriented approach in general). The class is simply a <a href="http://en.wikipedia.org/wiki/Object_composition" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Object_composition?referer=');">composition</a> of other library classes and under the hood delegates everything to these elements:</p>
<p><img src="http://toxiclibs.org/wp-content/uploads/2010/02/tonemap.png" alt="ToneMap composition" title="ToneMap composition" width="379" height="266" class="aligncenter size-full wp-image-275" /></p>
<p>All other GrayScott demos, as well as all Cellular Automata examples, make use of this ToneMap class, so do have a look at those for more reference&#8230; </p>
<p>Since a homogeneous configuration of the entire sim grid will always just provide one particular character/patterning, the <code>GrayScott</code> class has been designed with extension in mind. The <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/CustomGrayScott/CustomGrayScott.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/CustomGrayScott/CustomGrayScott.pde?referer=');">CustomGrayScott</a> demo shows how to impose a pattern on the actual simulation parameters themselves, so that cells at different positions are evaluated using different parameters:</p>
<pre class="brush:java">
class PatternedGrayScott extends GrayScott {

  // our constructor just passes things on to the parent class
  PatternedGrayScott(int w, int h, boolean tiling) {
    super(w,h,tiling);
  }

  // this function is called for each cell
  // to retrieve its f coefficient
  public float getFCoeffAt(int x, int y) {
    // here we only take the x coordinate
    // and choose one of 2 options (even &#038; odd)
    x/=32;
    return 0==x%2 ? f : f-0.005;
  }

  // this function is called for each cell
  // to retrieve its K coefficient
  public float getKCoeffAt(int x, int y) {
    // here we only use the y coordinate
    // and create a gradient falloff for this param
    return k-y*0.00004;
  }
}
</pre>
<p>Instead of using the default GrayScott class, we only need to change one line in the setup() method to use our extended version instead:</p>
<pre class="brush:java">
GrayScott gs;

void setup() {
	size(200,200);
	gs=new PatternedGrayScott(width,height,false);
	...
}
</pre>
<p>The result of this is shown below&#8230; Easy, huh? :)</p>
<p><img class="alignnone size-full wp-image-193" title="CustomGrayScott001" src="http://toxiclibs.org/wp-content/uploads/2010/02/CustomGrayScott001.png" alt="" width="680" height="362" /></p>
<p>Having this mechanism in place, it can be also used to create more interesting types of masking. For a commission to produce a <a href="http://postspectacular.com/work/printmag/" onclick="pageTracker._trackPageview('/outgoing/postspectacular.com/work/printmag/?referer=');">cover design for Print Magazine</a> in 2008, I generated a type face from simple line &#038; arc segments and used it as mask to manipulate the concentrations of the f &#038; K parameters to achieve two different types of patterning: one for the inside of the letter shapes, the other for the outside&#8230;</p>
<p><iframe src="http://player.vimeo.com/video/1272071" width="680" height="383" frameborder="0"></iframe></p>
<p>The frames of that animation were then stacked up along the Z axis in 3D space and with the help of the <a href="http://toxiclibs.org/category/volumeutils/">volumeutils</a> classes turned into 3D mesh, <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.core/toxi/geom/util/STLWriter.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.core/toxi/geom/util/STLWriter.java?referer=');">exported as STL format</a> (also see <a href="http://toxiclibs.org/docs/core/toxi/geom/util/TriangleMesh.html#saveAsSTL%28java.lang.String%29">TriangleMesh.saveAsSTL()</a>) and finally fabricated into the physical, 3D printed sculpture shown below. In a way, the sculpture can be seen as a map of its entire creation process&#8230;</p>
<p><img class="size-full wp-image-237" title="typeform_square_680" src="http://toxiclibs.org/wp-content/uploads/2010/02/typeform_square_680.jpg" alt="Type &amp; Form sculpture" width="680" height="680" /></p>
<p>Here&#8217;re some more rendered detail shots of the sculpture. <a href="http://postspectacular.com/work/printmag/" onclick="pageTracker._trackPageview('/outgoing/postspectacular.com/work/printmag/?referer=');">More information about this project is here</a> and the <a href="http://www.flickr.com/photos/toxi/sets/72157604724789091/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/sets/72157604724789091/?referer=');">related flickr set</a>.</p>
<p><img class="aligncenter size-full wp-image-265" title="typeform_detail1" src="http://toxiclibs.org/wp-content/uploads/2010/02/typeform_detail1.jpg" alt="" width="680" height="382" /></p>
<p><img src="http://toxiclibs.org/wp-content/uploads/2010/02/typeform_detail2.jpg" alt="" title="typeform_detail2" width="680" height="382" class="aligncenter size-full wp-image-266" /></p>
<p>Finally, the <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/GrayScottImage/GrayScottImage.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/GrayScottImage/GrayScottImage.pde?referer=');"><code>GrayScottImage</code></a> demo shows another supported technique of using the library: the seeding of the simulation using a bitmap image.</p>
<p><img class="alignnone size-full wp-image-194" title="GrayScottImage002" src="http://toxiclibs.org/wp-content/uploads/2010/02/GrayScottImage002.png" alt="" width="680" height="362" /></p>
]]></content:encoded>
			<wfw:commentRss>http://toxiclibs.org/2010/02/simutils-grayscott/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Re-inventing the wheel</title>
		<link>http://toxiclibs.org/2010/01/re-inventing-the-wheel/</link>
		<comments>http://toxiclibs.org/2010/01/re-inventing-the-wheel/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 02:44:50 +0000</pubDate>
		<dc:creator>toxi</dc:creator>
				<category><![CDATA[core]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Usage]]></category>
		<category><![CDATA[generative]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[searchspace]]></category>
		<category><![CDATA[spline]]></category>
		<category><![CDATA[symmetry]]></category>
		<category><![CDATA[variation]]></category>

		<guid isPermaLink="false">http://toxiclibs.org/?p=141</guid>
		<description><![CDATA[Firstly, massive thanks are in order for such a storming positive reception of this new site &#8211; I really hope this will become a good resource for everyone interested in the fields these libs are addressing and I will try to update everyone (and everything) as often as I can. In the near future that [...]]]></description>
			<content:encoded><![CDATA[<p>Firstly, massive thanks are in order for such a storming positive reception of this new site &#8211; I really hope this will become a good resource for everyone interested in the fields these libs are addressing and I will try to update everyone (and everything) as often as I can. In the near future that will include a bit of future gazing, but today I&#8217;ve been re-inventing the wheel, literally&#8230;</p>
<p><a href="http://www.flickr.com/photos/toxi/4280317234/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4280317234/?referer=');"><img class="alignnone size-full wp-image-147" title="wheel12" src="http://toxiclibs.org/wp-content/uploads/2010/01/wheel12.jpg" alt="wheel 12 spokes" width="680" height="525" /></a></p>
<p>I&#8217;ve been working on some designs for custom made wheels for a potential installation project. The aim is to lasercut some light-weight &amp; good looking acrylic wheels and so I&#8217;ve been literally searching for a few candidate solutions, which allow me to cut out large pieces of material from inside the wheel to keep the weight down whilst still being sturdy enough (thankfully the load on them will be minimal so I can skip the structural analysis).</p>
<p>Not wanting to do this exploration/hike manually, I opted for the Processing PDF output route and have written this little tool below to show me my options (at least some of them) and also tweak them easily.</p>
<p>Apart from Processing, the tool also makes use of these 3 classes from the <a href="http://toxiclibs.org/docs/core/">toxiclibscore</a> package:</p>
<h2>Vec2D</h2>
<p>This class, alongside its sibling Vec3D, is likely one of the most used classes of the entire library. Since 1.0 Processing has its own vector class too now, but Vec2D/3D are far more feature complete, implement a <a href="http://en.wikipedia.org/wiki/Fluent_interface" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Fluent_interface?referer=');">fluent interface</a> for more legible code when dealing with complex vector maths and <em>can</em> be faster too (especially for 2D, but also by helping you to avoid temporary object creation). Furthermore Vec2D also has support for polar coordinates (Vec3D has spherical as equivalent) which was very helpful for building the tool below:</p>
<p>Normally, you&#8217;d specify a Cartesian point with:</p>
<pre class="brush:java">Vec2D v = new Vec2D(x, y);</pre>
<p>However, if we want to interpret our vector as polar coordinates, we&#8217;re using the x component to specify the radius and the y component as rotation angle. To convert the vector back into Cartesian space (e.g. our screen) we can use the <code>.toCartesian()</code> method&#8230;</p>
<pre class="brush:java">Vec2D v = new Vec2D(radius, theta).toCartesian();</pre>
<p>In a similar manner, you can also transform a Cartesian point into polar coordinates:</p>
<pre class="brush:java">// here we 1st create a copy of v and then convert that one
Vec2D p = v.copy().toPolar();</pre>
<p>To see this basic usage pattern in more context, take a closer look at the <code>drawHoles(</code>) method below (lines 114-134) or check out the <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/core/PolarUnravel/PolarUnravel.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/core/PolarUnravel/PolarUnravel.pde?referer=');">PolarUnravel demo</a> bundled with the core lib.</p>
<h2>Spline2D</h2>
<p>Each cut-out shape in the wheel is created from a simple spline shape, specified using only 4 points. As mentioned above, these anchor points are specified using (initially) polar coordinates and the Spline2D class is then computing control points (handles) for each of these given points automatically. As user you can also specify tightness &amp; subdivisions for the computed curve vertices in between. While the lack of direct manual control over the spline handles might be a shortcoming in some situations, I generally found it easier to work with this automated version, especially when working with long curves and not only single bezier segments.</p>
<p>The next release of the library will also add a decimator method to this class which will enable the sampling of the curve at a uniform interval (i.e. all successive points of the returned list have the same distance (within a tolerance), regardless of curvature). This feature comes from the <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.physics/toxi/physics/ParticlePath.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.physics/toxi/physics/ParticlePath.java?referer=');">ParticlePath</a> class briefly described in the <a href="http://toxiclibs.org/2010/01/happy-2010/">Happy 2010 post</a>.</p>
<p>Computing symmetrical handles for the curve endpoints is another still outstanding feature, but currently low priority (unless someone has got a patch ready for that ;)</p>
<p>The next image shows the 4 anchor points of each spline shape in green and all other computed vertices in pink.</p>
<p><a href="http://www.flickr.com/photos/toxi/4280635396/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4280635396/?referer=');"><img src="http://toxiclibs.org/wp-content/uploads/2010/01/wheelspline-e1263695654792.png" alt="wheel with highlighted spline vertices" title="wheelspline" width="680" height="680" class="alignnone size-full wp-image-180" /></a></p>
<h2>UnitTranslator</h2>
<p>This class is the sole, lonely member of the <code>toxi.math.conversion</code> package, but is especially useful for those of you using Processing for digital fabrication or creating printed outputs. It provides the following conversion methods, making it trivial to e.g produce PDF outputs at the right physical dimensions (without trial &amp; error):</p>
<ul>
<li><code>millisToPixels(double mm, int dpi)</code> &#8211; Converts millimeters into pixels.</li>
<li><code>millisToPoints(double mm)</code> &#8211; Converts millimeters into PostScript points.</li>
<li><code>pixelsToInch(int pix, int dpi)</code> &#8211; Converts pixels into inches.</li>
<li><code>pixelsToMillis(int pix, int dpi)</code> &#8211; Converts pixels into millimeters.</li>
<li><code>pixelsToPoints(int pix, int dpi)</code> &#8211; Converts pixels into points.</li>
<li><code>pointsToMillis(double pt)</code> &#8211; Converts points into millimeters.</li>
<li><code>pointsToPixels(double pt, int dpi)</code> &#8211; Converts points into pixels.</li>
</ul>
<p>In the demo below, we&#8217;re using it to specifiy the wheel radius and drill holes in mm and then automatically calculate the required window size in pixels. In that case we&#8217;re however not using <code>millisToPixels()</code>, but <code>millisToPoints()</code> because PDF units are in points which are interpreted as 1 pixel (at 72 dpi)&#8230;</p>
<h2>The Wheel tool</h2>
<p>Just copy &#038; paste the code below into Processing and hit <em>Run</em> to fill up your hard disk (kidding, by default it only generates 120 different small PDF files/variations). The variations are created by iterating over all permutations of 4 parameters: number of symmetry steps, inset radius, core radius, alternate core radius.</p>
<pre class="brush:java">/**
 * Generative wheel designs utilizing Vec2D polar coordinates,
 * splines and unit conversion. By default each design is exported as
 * PDF &#038; PNG file, but can be turned off by setting the doExport flag to false.
 *
 * Usage: if export is enabled simply run &#038; wait until all permutations
 * have been generated. Else press 'x' to activate next permutation or
 * use - / = to adjust the ARC_WIDTH parameter which defines the
 * size of the cutouts.
 *
 * (c) 2010 Karsten Schmidt, PostSpectacular Ltd.
 *
 * More info: http://toxiclibs.org/2010/01/re-inventing-the-wheel/
 * Source code licensed under GPL v3.0. See http://www.gnu.org/licenses/gpl.html
 */

import processing.pdf.*;

import toxi.geom.*;
import toxi.math.conversion.*;

// bleed in mm
int BLEED = 6;

// wheel radii &#038; document size
float R = (float)UnitTranslator.millisToPoints(370 / 2);
float W = 2 * R + 2 * (float)UnitTranslator.millisToPoints(BLEED);
float EMPTY_CORE_SIZE = (float)UnitTranslator.millisToPoints(5);

// start number of main segments
int NUM_SEGMENTS = 3;

// normalized parameters
float INSET_RADIUS = 0.8f;
float OFFSET = 0.1f;
float CORE_RADIUS = 0.15f;
float ALTCORE_RADIUS = 0.3f;
float ARC_WIDTH = 0.4f;

// optional mounting holes
int NUM_DOTS = 18;
float DOT_RADIUS = 0.97f;
float DOTSIZE = (float)UnitTranslator.millisToPoints(2);

// number of subdivisions for spline vertex computation
int SPLINE_SUBDIV = 20;

// flag for PDF &#038; PNG export of all permutations
boolean doExport = true;

public void setup() {
  size((int) W, (int) W);
  // turn off automatic redraws when not exporting
  if (!doExport) {
    noLoop();
  }
}

public void draw() {
  String frameID =
    "wheel-" + NUM_SEGMENTS + "-" + nf(INSET_RADIUS, 1, 2) + "-"
    + nf(ALTCORE_RADIUS, 1, 2) + "-"
    + nf(CORE_RADIUS, 1, 2) + "-" + nf(ARC_WIDTH, 1, 2);
  println(frameID);
  if (doExport) {
    beginRecord(PDF, "out/" + frameID + ".pdf");
  }
  background(255);
  noStroke();
  fill(0);
  translate(width / 2, height / 2);
  ellipseMode(RADIUS);
  ellipse(0, 0, R, R);
  fill(255);
  ellipse(0, 0, EMPTY_CORE_SIZE, EMPTY_CORE_SIZE);
  // main holes
  drawHoles((INSET_RADIUS + OFFSET) * R, CORE_RADIUS * R, (INSET_RADIUS
    + OFFSET + CORE_RADIUS)
    / 2 * R, ARC_WIDTH, 0, NUM_SEGMENTS);
  if (CORE_RADIUS &gt;= 0.5) {
    drawHoles(CORE_RADIUS * 0.85f * R, 0.2f * R,
    (CORE_RADIUS * 0.85f + 0.2f) / 2 * R, ARC_WIDTH, 0,
    NUM_SEGMENTS);
  }
  // small cutouts
  drawHoles(INSET_RADIUS * R, ALTCORE_RADIUS * R,
  (INSET_RADIUS + ALTCORE_RADIUS) / 2 * R, ARC_WIDTH / 2, PI
    / NUM_SEGMENTS, NUM_SEGMENTS);
  if (ALTCORE_RADIUS &gt;= 0.5) {
    drawHoles(ALTCORE_RADIUS * 0.85f * R, 0.3f * R,
    (ALTCORE_RADIUS * 0.85f + 0.3f) / 2 * R, ARC_WIDTH / 2, PI
      / NUM_SEGMENTS, NUM_SEGMENTS);
  }
  // drill holes
  drawDots(NUM_DOTS, DOT_RADIUS * R, DOTSIZE);
  if (doExport) {
    endRecord();
    saveFrame("png/" + frameID + ".png");
    nextPermutation();
  }
}

void drawDots(int num, float radius, float s) {
  float delta = TWO_PI / num;
  for (int i = 0; i &lt; num; i++) {
    Vec2D p = new Vec2D(radius, i * delta).toCartesian();
    ellipse(p.x, p.y, s, s);
  }
}

void drawHoles(float outerR, float innerR, float centerR, float radiusWidth, float thetaOffset, int num) {
  radiusWidth *= PI / num;
  Spline2D s = new Spline2D();
  // define point in polar coordinates, then convert them
  Vec2D p = new Vec2D(outerR, 0).toCartesian();
  Vec2D a = new Vec2D(outerR, radiusWidth).toCartesian();
  Vec2D b = new Vec2D(centerR, radiusWidth).toCartesian();
  Vec2D c = new Vec2D(innerR, 0).toCartesian();
  Vec2D d = new Vec2D(centerR, -radiusWidth).toCartesian();
  Vec2D e = new Vec2D(outerR, -radiusWidth).toCartesian();
  // add points to spline &#038; compute
  s.add(p).add(a).add(b).add(c).add(d).add(e).add(p);
  java.util.List verts = s.computeVertices(SPLINE_SUBDIV);
  float delta = TWO_PI / num;
  for (int i = 0; i &lt; num; i++) {
    pushMatrix();
    rotate(i * delta + thetaOffset);
    drawPath(verts);
    popMatrix();
  }
}

void drawPath(java.util.List verts) {
  beginShape();
  for (Iterator i = verts.iterator(); i.hasNext();) {
    Vec2D v = (Vec2D) i.next();
    vertex(v.x, v.y);
  }
  endShape();
}

public void keyPressed() {
  if (key == 'x') {
    nextPermutation();
  } else if (key == '-') {
    ARC_WIDTH -= 0.02;
  } else if (key == '=') {
    ARC_WIDTH += 0.02;
  }
  redraw();
}

void nextPermutation() {
  CORE_RADIUS += 0.2;
  if (CORE_RADIUS &gt;= INSET_RADIUS) {
    CORE_RADIUS = 0.15f;
    ALTCORE_RADIUS += 0.2f;
    if (ALTCORE_RADIUS &gt;= INSET_RADIUS) {
      ALTCORE_RADIUS = 0.3f;
      INSET_RADIUS += 0.1f;
      if (INSET_RADIUS &gt; 0.8) {
        NUM_SEGMENTS++;
        INSET_RADIUS = 0.8f;
        if (NUM_SEGMENTS &gt; 12) {
          exit();
        }
      }
    }
  }
}
</pre>
<p>Finally, below are some more images of variations created with this tool (<a href="http://www.flickr.com/photos/toxi/sets/72157623224570676/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/sets/72157623224570676/?referer=');">see the full size &#038; set on flickr</a>):</p>
<p><a href="http://www.flickr.com/photos/toxi/4280053262/" title="wheel3_all by toxi, on Flickr" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4280053262/?referer=');"><img src="http://farm3.static.flickr.com/2680/4280053262_5e0676cd13.jpg" width="350" height="500" alt="wheel3_all" /></a></p>
<p><a href="http://www.flickr.com/photos/toxi/4279310563/" title="wheel5_all by toxi, on Flickr" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4279310563/?referer=');"><img src="http://farm5.static.flickr.com/4021/4279310563_ca5ed79d6c.jpg" width="350" height="500" alt="wheel5_all" /></a></p>
<p><a href="http://www.flickr.com/photos/toxi/4280055796/" title="wheel8_all by toxi, on Flickr" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4280055796/?referer=');"><img src="http://farm3.static.flickr.com/2758/4280055796_f43663fc20.jpg" width="350" height="500" alt="wheel8_all" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://toxiclibs.org/2010/01/re-inventing-the-wheel/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Additive waves</title>
		<link>http://toxiclibs.org/2009/12/additive-waves/</link>
		<comments>http://toxiclibs.org/2009/12/additive-waves/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 22:28:34 +0000</pubDate>
		<dc:creator>toxi</dc:creator>
				<category><![CDATA[Showcase]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Usage]]></category>
		<category><![CDATA[3d]]></category>
		<category><![CDATA[core]]></category>
		<category><![CDATA[terrain]]></category>
		<category><![CDATA[waves]]></category>

		<guid isPermaLink="false">http://toxiclibs.postspectacular.com/?p=50</guid>
		<description><![CDATA[The December release cycle has seen a number of new demos, including this one below using the built-in wave generators to create a dynamic 3D terrain. These generators are actually some of the oldest &#38; most re-usable components of the core library, but they never got much attention on the demo front. This is of [...]]]></description>
			<content:encoded><![CDATA[<p>The December release cycle has seen a number of new demos, including this one below using the built-in wave generators to create a dynamic 3D terrain. These generators are actually some of the oldest &amp; most re-usable components of the core library, but they never got much attention on the demo front. This is of course not right, especially since they also nicely demonstrate the object oriented &#8220;building block&#8221; approach also underlying most of the other available classes.</p>
<p><a title="new toxiclibs demo: AdditiveWaves017 by toxi, on Flickr" href="http://www.flickr.com/photos/toxi/4124850086/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4124850086/?referer=');"><img src="http://farm3.static.flickr.com/2689/4124850086_407814a592_m.jpg" alt="new toxiclibs demo: AdditiveWaves017" width="240" height="140" /></a> <a title="new toxiclibs demo: AdditiveWaves011 by toxi, on Flickr" href="http://www.flickr.com/photos/toxi/4124848628/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4124848628/?referer=');"><img src="http://farm3.static.flickr.com/2709/4124848628_96243ea1e9_m.jpg" alt="new toxiclibs demo: AdditiveWaves011" width="240" height="140" /></a></p>
<p><a title="new toxiclibs demo: AdditiveWaves003 by toxi, on Flickr" href="http://www.flickr.com/photos/toxi/4124075907/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4124075907/?referer=');"><img src="http://farm3.static.flickr.com/2709/4124075907_1de68ca9da_m.jpg" alt="new toxiclibs demo: AdditiveWaves003" width="240" height="140" /></a> <a title="new toxiclibs demo: AdditiveWaves005 by toxi, on Flickr" href="http://www.flickr.com/photos/toxi/4124847486/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/4124847486/?referer=');"><img src="http://farm3.static.flickr.com/2804/4124847486_7cf1c98746_m.jpg" alt="new toxiclibs demo: AdditiveWaves005" width="240" height="140" /></a></p>
<p>The Processing source code for generating these meshes is available with the library download, with an excerpt shown also below. But first, here&#8217;s a brief overview of how to use these classes:</p>
<p>Waves &amp; oscillation in general are very flexible &amp; powerful tools for many different design tasks and shouldn&#8217;t always be thought of in an audio context. For example, a square wave can be used to flick between 2 values at a given frequency, without the need for any <code>if()</code> statements. I also often use sine waves to create cyclical, soft, harmonious value changes, be it for interface design, movement, animation or even the time based modulation of behavioural parameters of agents. The core library comes with the following pre-defined wave types:</p>
<ul>
<li>Sine (pure, frequency modulated (FM), amplitude &amp; frequency modulated (AMFM))</li>
<li>Sawtooth (FM)</li>
<li>Square (FM and FM with harmonics)</li>
<li>Triangle (FM)</li>
<li>Constant (only provides a static value, e.g. useful as static source for input as FM)</li>
</ul>
<p>All of these types are expressed as implementations of the <code>AbstractWave</code> class in the <a href="http://toxiclibs.postspectacular.com/docs/core/toxi/math/waves/package-summary.html" onclick="pageTracker._trackPageview('/outgoing/toxiclibs.postspectacular.com/docs/core/toxi/math/waves/package-summary.html?referer=');">toxi.math.waves</a> package. This abstract class defines all commonalities of what constitutes a wave: a phase, a frequency, an amplitude, a centre offset and a bunch of accessors and converters. The actual wave function then needs to be implemented by a concrete sub-class. Using <a href="http://en.wikipedia.org/wiki/Type_polymorphism" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Type_polymorphism?referer=');">poly-morphism</a> and having an <a href="http://en.wikipedia.org/wiki/Abstract_class" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Abstract_class?referer=');">abstract super class</a> makes a lot of sense in this case, since it allows for all this:</p>
<ol>
<li>It frees our main application from having to know which exact wave type we&#8217;re going to use and so allows for easier/faster experimentation and generally more flexibility.</li>
<li>It enables us to plug-in any of the available wave types as input for frequency or amplitude modulation and so create highly (theoretically infinitely) complex waveforms.</li>
<li>It provides the basics of an extensible framework for creating new wave types.</li>
</ol>
<p>These points are hopefully confirmed by you when looking at this method below (taken from the <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/core/AdditiveWaves/AdditiveWaves.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/core/AdditiveWaves/AdditiveWaves.pde?referer=');">AdditveWaves</a> demo, bundled since toxiclibscore-0015):</p>
<pre class="brush:java">AbstractWave createRandomWave() {

  AbstractWave result=null;

  // create a randomized sine wave to be used as
  // FM input for the main wave chosen below
  // the order of parameters is:
  // start phase, frequency (in radians), amplitude, offset value
  AbstractWave fmod=new SineWave(0, random(0.005, 0.02), random(0.1, 0.5), 0);

  // pick a random frequency
  float freq=random(0.005, 0.05);

  // choose a wave type
  switch((int)random(7)) {
  case 0:
    result = new FMTriangleWave(0, freq, 1, 0, fmod);
    break;
  case 1:
    result = new FMSawtoothWave(0, freq, 1, 0, fmod);
    break;
  case 2:
    result = new FMSquareWave(0, freq, 1, 0, fmod);
    break;
  case 3:
    // harmonic square waves are created by
    // adding sine waves upto a number of octaves
    // above the base frequency
    result = new FMHarmonicSquareWave(0, freq, 1, 0, fmod);
    ((FMHarmonicSquareWave)result).maxHarmonics=(int)random(3,30);
    break;
  case 4:
    result = new FMSineWave(0, freq, 1, 0, fmod);
    break;
  case 5:
    AbstractWave amod=new SineWave(0, random(0.01,0.2), random(2, 3), 0);
    result = new AMFMSineWave(0, freq, 0, fmod, amod);
    break;
  case 6:
    result = new ConstantWave(random(-1,1));
    break;
  }
  return result;
}</pre>
<p>The next snippet then quickly shows how this method would be used:</p>
<pre class="brush:java">import toxi.math.waves.*;

AbstractWave wave=createRandomWave();

// updates the wave phase and computes the new function value
// this code doesn't care which wave type we're dealing with
float currValue=wave.update();
</pre>
<p>The generators have another useful feature, though: A state stack. If you&#8217;ve used Processing or OpenGL before, you have likely  come across the concept in the form of <code>pushMatrix()</code>/<code>popMatrix()</code> calls to save and restore the state of the graphical transformation matrix. The wave generators implement the same idea and so can be easily used to create the 3D meshes above.</p>
<pre class="brush:java">// save current wave state
wave.push();

for(int i=0; i<10; i++) {
  float lookahead=wave.update();
  // do something clever
}

// restore wave to previous state
wave.pop();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://toxiclibs.org/2009/12/additive-waves/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

