
<?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>daniel shiffman &#187; processing.org</title>
	<atom:link href="http://www.shiffman.net/category/processingorg/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.shiffman.net</link>
	<description></description>
	<lastBuildDate>Tue, 24 Jan 2012 03:41:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Night #8: Rendering an image sequence</title>
		<link>http://www.shiffman.net/2011/12/28/night-8-rendering-out-as-image-sequence/</link>
		<comments>http://www.shiffman.net/2011/12/28/night-8-rendering-out-as-image-sequence/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 16:13:43 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[image sequence]]></category>
		<category><![CDATA[png]]></category>
		<category><![CDATA[render]]></category>
		<category><![CDATA[saveFrame]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1073</guid>
		<description><![CDATA[How can one render a movie from a Processing sketch? In Processing 1.5.1, there is a class called MovieMaker which generates a Quicktime file directly. However, this class uses ye old Quicktime for Java and will be removed from Processing &#8230; <a href="http://www.shiffman.net/2011/12/28/night-8-rendering-out-as-image-sequence/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>How can one render a movie from a Processing sketch?  In Processing 1.5.1, there is a class called MovieMaker which generates a Quicktime file directly.  However, this class uses ye old Quicktime for Java and will be removed from Processing 2.0.  Instead, 2.0 is going to introduce a MovieMaker &#8220;tool&#8221; which will generate a movie file from a directory containing an image sequence.  So how do you get this image sequence?  Easy:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  saveFrame<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;output/frames####.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This will create a folder called &#8220;output&#8221; in your sketch folder and for each frame of draw(), it will write a file &#8212; frames0001.png, frames0002.png, etc.  The &#8216;#&#8217; sign tells processing to auto-number the images.</p>
<p>There are a couple additional tricks included in this new example.  First, it uses a boolean variable to turn rendering on and off and cycles the boolean in keyPressed() allowing recording to be stopped and started by pressing &#8216;r&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// If we are recording call saveFrame!</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>recording<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    saveFrame<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;output/frames####.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> keyPressed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>  
  <span style="color: #666666; font-style: italic;">// If we press r, start or stop recording!</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>key <span style="color: #339933;">==</span> <span style="color: #0000ff;">'r'</span> <span style="color: #339933;">||</span> key <span style="color: #339933;">==</span> <span style="color: #0000ff;">'R'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    recording <span style="color: #339933;">=</span> <span style="color: #339933;">!</span>recording<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In addition, if you draw anything after saveFrame() it won&#8217;t actually appear in the output, but will be seen on screen.  This is useful for debugging information that you don&#8217;t want included in the render.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Draw lots of stuff to be recorded!</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>recording<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    saveFrame<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;output/frames####.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Draw our debugging stuff that won't be recorded!</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Until 2.0 is released, I recommend you use 3rd party software to take the image sequence and turn it into a movie.  The old Quicktime 7 will do the trick, as well as any number of video production applications like final cut, after effects, iMovie, etc.  The nice thing about using a PNG sequence is that the images are uncompressed, but aren&#8217;t as large as say TIFFs.  I don&#8217;t recommend saving JPGs because then you will likely be compressing twice (once when saving the image, once when exporting the movie file).</p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/SavingFrames.zip'><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/frames.png" alt="" title="frames" width="590" height="352" class="alignnone size-full wp-image-1075" /></a></p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/SavingFrames.zip'>SavingFrames.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/28/night-8-rendering-out-as-image-sequence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Night #7: Nature of Code excerpts</title>
		<link>http://www.shiffman.net/2011/12/27/night-7-nature-of-code-excerpts/</link>
		<comments>http://www.shiffman.net/2011/12/27/night-7-nature-of-code-excerpts/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 20:48:41 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[fractal]]></category>
		<category><![CDATA[genetic algorithm]]></category>
		<category><![CDATA[nature of code]]></category>
		<category><![CDATA[neural network]]></category>
		<category><![CDATA[tree]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1052</guid>
		<description><![CDATA[For tonight&#8217;s post, I&#8217;m going to include three new examples from my upcoming Nature of Code book. I&#8217;ll also excerpt some of the text with these examples below. This first example expands on the existing Recursive Tree example that comes &#8230; <a href="http://www.shiffman.net/2011/12/27/night-7-nature-of-code-excerpts/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>For tonight&#8217;s post, I&#8217;m going to include three new examples from my upcoming Nature of Code book.  I&#8217;ll also excerpt some of the text with these examples below.</p>
<p>This first example expands on the existing <a href="http://processing.org/learning/topics/tree.html">Recursive Tree</a> example that comes with Processing.</p>
<p><strong>Chapter 8: Recursion and Fractals</strong></p>
<p>The recursive tree fractal is a nice example of a scenario in which adding a little bit of randomness can make the tree look more natural.  Take a look outside and you’ll notice that branch lengths and angles vary from branch to branch, not to mention the fact that branches don’t all have exactly the same number of smaller branches.   First, let’s see what happens when we simply vary the angle and length.  This is a pretty easy one, given that we can just ask Processing for a random number each time we draw the tree.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> branch<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> len<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>	
  <span style="color: #666666; font-style: italic;">// Start by picking a random angle for each branch</span>
  <span style="color: #000066; font-weight: bold;">float</span> theta <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>,PI<span style="color: #339933;">/</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
&nbsp;
  line<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  translate<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  len <span style="color: #339933;">*=</span> <span style="color: #cc66cc;">0.66</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>len <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    pushMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>    
    rotate<span style="color: #009900;">&#40;</span>theta<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>   
    branch<span style="color: #009900;">&#40;</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    popMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>     
    pushMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    rotate<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span>theta<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    branch<span style="color: #009900;">&#40;</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    popMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In the above function, we always call branch() twice.  But why not pick a random number of branches and call branch() that number of times?</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> branch<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> len<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>	
&nbsp;
  line<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  translate<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>len <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Call branch() a random number of times</span>
    <span style="color: #000066; font-weight: bold;">int</span> n <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#40;</span>random<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">4</span><span style="color: #009900;">&#41;</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> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> n<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>	
&nbsp;
      <span style="color: #666666; font-style: italic;">// Each branch gets its own random angle</span>
      <span style="color: #000066; font-weight: bold;">float</span> theta <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span>PI<span style="color: #339933;">/</span><span style="color: #cc66cc;">2</span>, PI<span style="color: #339933;">/</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
      pushMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>     
      rotate<span style="color: #009900;">&#40;</span>theta<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      branch<span style="color: #009900;">&#40;</span>h<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      popMatrix<span style="color: #009900;">&#40;</span><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></div></div>

<p>The example below takes the above a few steps further.  It uses Perlin noise to generate the angles, as well as animate them.  In addition, it draws each branch with a thickness according to its level and sometimes shrinks a branch by a factor of two to vary where the levels begin.</p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/TreeStochasticNoise.zip'><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/tree1.png" alt="" title="tree" width="580" height="347" class="alignnone size-full wp-image-1058" /></a></p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/TreeStochasticNoise.zip'>TreeStochasticNoise.zip</a></p>
<p>Next up an excerpt from the Genetic Algorithm chapter.</p>
<p><strong>Chapter 9: Evolution and Code</strong></p>
<p>In 2009, <a href="http://blog.blprnt.com">Jer Thorp</a>  released a great genetic algorithms example on his blog entitled “<a href="http://blog.blprnt.com/blog/blprnt/project-smart-rockets">Smart Rockets</a>.”   Jer points out that NASA uses evolutionary computing techniques to solve all sorts of problems, from satellite antenna design to rocket firing patterns. This inspired him to create a Flash demonstration of evolving rockets.  Here is a description of the scenario:</p>
<p>A population of rockets launches from the bottom of the screen with the goal of hitting a target at the top of the screen (with obstacles blocking a straight line path).   </p>
<p><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/rockets.png" alt="" title="rockets" width="300" height="187" class="alignnone size-full wp-image-1061" /></p>
<p>Each rocket is equipped with five thrusters of variable strength and direction.    The thrusters don’t fire all at once and continuously; rather, they fire one at a time in a custom sequence.  In this example, we’re going to evolve our own simplified Smart Rockets, inspired by Jer Thorp’s.   You can leave implementing some of Jer’s additional advanced features as an exercise.  </p>
<p>Our rockets will have only one thruster, and this thruster will be able to fire in any direction with any strength in every single frame of animation.  This isn&#8217;t particularly realistic, but it will make building out the framework a little easier. (We can always make the rocket and its thrusters more advanced and realistic later.)   </p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/SmartRockets.zip'><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/rockets2.png" alt="" title="rockets2" width="590" height="352" class="alignnone size-full wp-image-1063" /></a></p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/SmartRockets.zip'>SmartRockets.zip</a></p>
<p>And here&#8217;s a short excerpt from the beginning of the chapter on neural networks, as well as the example that closes out the chapter demonstrating how to visualize the flow of information through a network.</p>
<p><strong>Chapter 10: The Brain</strong></p>
<p>Computer scientists have long been inspired by the human brain.   In 1943, Warren S. McCulloch, a neuroscientist, and Walter Pitts, a logician, developed the first conceptual model of an artificial neural network.  In their paper, &#8220;A logical calculus of the ideas imminent in nervous activity,” they describe the concept of a neuron, a single cell living in a network of cells that receives inputs, processes those inputs, and generates an output.</p>
<p>Their work, and the work of many scientists and researchers that followed, was not meant to accurately describe how the biological brain works.  Rather, an artificial neural network (which we will now simply refer to as a “neural network”) was designed as a computational model based on the brain that can solve certain kinds of problems.</p>
<p>It’s probably pretty obvious to you that there are certain problems that are incredibly simple for a computer to solve, but difficult for you.  Take the square root of 964,324, for example.  A quick line of code produces the value 982, a number Processing computed in less than a millisecond.   There are, on the other hand, problems that are incredibly simple for you or me to solve, but not so easy for a computer.   Show any toddler a picture of a kitten or puppy and they’ll be able to tell you very quickly which one is which.   Say hello and shake my hand one morning and you should be able to pick me out of a crowd of people the next day.  But need a machine to perform one of these tasks?  People have already spent careers researching and implementing complex solutions.</p>
<p>The most common application of neural networks in computing today is to perform one of these easy-for-a-human, difficult-for-a-machine” tasks, often referred to as pattern classification.   Applications range from optical character recognition (turning printed or handwritten scans into digital text) to facial recognition.  We don’t have the time or need to use some of these more elaborate artificial intelligence algorithms here, but if you are interested in researching neural networks, I’d recommend the books Artificial Intelligence: A Modern Approach by Stuart J. Russell and Peter Norvig and AI for Game Developers by David M. Bourg and Glenn Seemann.</p>
<p>In this chapter, we’ll instead begin with a conceptual overview of the properties and features of neural networks and build the simplest example possible of one (a network that consists of a singular neuron).  Afterwards, we’ll examine strategies for building a “Brain” object that can be inserted into our Vehicle class and used to determine steering.   Finally, we’ll also look at techniques for visualizing and animating a network of neurons.</p>
<p><script type="application/processing">

Network network;

void setup() {
  size(590, 360); 
  smooth();
  
  // Create the Network object
  network = new Network(width/2, height/2);

  // Create a bunch of Neurons
  Neuron a = new Neuron(-300, 0);
  Neuron b = new Neuron(-200, 0);
  Neuron c = new Neuron(0, 100);
  Neuron d = new Neuron(0, -100);
  Neuron e = new Neuron(200, 0);
  Neuron f = new Neuron(300, 0);

  // Connect them
  network.connect(a, b,1);
  network.connect(b, c,random(1));
  network.connect(b, d,random(1));
  network.connect(c, e,random(1));
  network.connect(d, e,random(1));
  network.connect(e, f,1);

  // Add them to the Network
  network.addNeuron(a);
  network.addNeuron(b);
  network.addNeuron(c);
  network.addNeuron(d);
  network.addNeuron(e);
  network.addNeuron(f);
}

void draw() {
  background(255);
  // Update and display the Network
  network.update();
  network.display();
  
  // Every 30 frames feed in an input
  if (frameCount % 30 == 0) {
    network.feedforward(random(1));
  }
}

class Connection {
  // Connection is from Neuron A to B
  Neuron a;
  Neuron b;
  
  // Connection has a weight
  float weight;

  // Variables to track the animation
  boolean sending = false;
  PVector sender;
  
  // Need to store the output for when its time to pass along
  float output = 0;

  Connection(Neuron from, Neuron to, float w) {
    weight = w;
    a = from;
    b = to;
  }
  
  
  // The Connection is active
  void feedforward(float val) {
    output = val*weight;        // Compute output
    sender = a.location.get();  // Start animation at Neuron A
    sending = true;             // Turn on sending
  }
  
  // Update traveling sender
  void update() {
    if (sending) {
      // Use a simple interpolation
      sender.x = lerp(sender.x, b.location.x, 0.1);
      sender.y = lerp(sender.y, b.location.y, 0.1);
      float d = PVector.dist(sender, b.location);
      // If we've reached the end
      if (d < 1) {
        // Pass along the output!
        b.feedforward(output);
        sending = false;
      }
    }
  }
  
  // Draw line and traveling circle
  void display() {
    stroke(0);
    strokeWeight(1+weight*4);
    line(a.location.x, a.location.y, b.location.x, b.location.y);

    if (sending) {
      fill(0);
      strokeWeight(1);
      ellipse(sender.x, sender.y, 16, 16);
    }
  }
}

class Network {

  // The Network has a list of neurons
  ArrayList neurons;

  // The Network now keeps a duplicate list of all Connection objects.
  // This makes it easier to draw everything in this class
  ArrayList connections;
  PVector location;

  Network(float x, float y) {
    location = new PVector(x, y);
    neurons = new ArrayList();
    connections = new ArrayList();
  }

  // We can add a Neuron
  void addNeuron(Neuron n) {
    neurons.add(n);
  }

  // We can connection two Neurons
  void connect(Neuron a, Neuron b, float weight) {
    Connection c = new Connection(a, b, weight);
    a.addConnection(c);
    // Also add the Connection here
    connections.add(c);
  } 

  // Sending an input to the first Neuron
  // We should do something better to track multiple inputs
  void feedforward(float input) {
    Neuron start = (Neuron) neurons.get(0);
    start.feedforward(input);
  }

  // Update the animation
  void update() {
    for (int i = 0; i < connections.size(); i++) {
      Connection c = (Connection) connections.get(i);
      c.update();
    }
  }

  // Draw everything
  void display() {
    pushMatrix();
    translate(location.x, location.y);
    for (int i = 0; i < neurons.size(); i++) {
      Neuron n = (Neuron) neurons.get(i);
      n.display();
    }

    for (int i = 0; i < connections.size(); i++) {
      Connection c = (Connection) connections.get(i);
      c.display();
    }
    popMatrix();
  }
}

// An animated drawing of a Neural Network
// Daniel Shiffman <http://www.shiffman.net>
// Nature of Code

class Neuron {
  // Neuron has a location
  PVector location;

  // Neuron has a list of connections
  ArrayList connections;

  // We now track the inputs and sum them
  float sum = 0;

  // The Neuron's size can be animated
  float r = 32;

  Neuron(float x, float y) {
    location = new PVector(x, y);
    connections = new ArrayList();
  }

  // Add a Connection
  void addConnection(Connection c) {
    connections.add(c);
  } 

  // Receive an input
  void feedforward(float input) {
    // Accumulate it
    sum += input;
    // Activate it?
    if (sum > 1) {
      fire();
      sum = 0;  // Reset the sum to 0 if it fires
    }
  }

  // The Neuron fires
  void fire() {
    r = 64;   // It suddenly is bigger

    // We send the output through all connections
    for (int i = 0; i < connections.size(); i++) {
      Connection c = (Connection) connections.get(i);

      c.feedforward(sum);
    }
  }

  // Draw it as a circle
  void display() {
    stroke(0);
    strokeWeight(1);
    // Brightness is mapped to sum
    float b = map(sum, 0, 1, 255, 0);
    fill(b);
    ellipse(location.x, location.y, r, r);

    // Size shrinks down back to original dimensions
    r = lerp(r, 32, 0.1);
  }
}

</script></p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/NetworkAnimation.zip'>NetworkAnimation.zip</a></script></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/27/night-7-nature-of-code-excerpts/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Night #6: Image Sequence Object (with variable speed)</title>
		<link>http://www.shiffman.net/2011/12/26/night-6-image-sequence-object-with-variable-speed/</link>
		<comments>http://www.shiffman.net/2011/12/26/night-6-image-sequence-object-with-variable-speed/#comments</comments>
		<pubDate>Mon, 26 Dec 2011 16:00:19 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[image sequence]]></category>
		<category><![CDATA[PImage]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1036</guid>
		<description><![CDATA[I have an example from Learning Processing which demonstrates how to package a &#8220;pre-made&#8221; animation (i.e. sequence of images) into an object in Processing so that it can be duplicated many times on screen. For tonight&#8217;s example, I&#8217;m going to &#8230; <a href="http://www.shiffman.net/2011/12/26/night-6-image-sequence-object-with-variable-speed/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have <a href="http://www.learningprocessing.com/exercises/chapter-15/exercise-15-5/">an example from Learning Processing</a> which demonstrates how to package a &#8220;pre-made&#8221; animation (i.e. sequence of images) into an object in Processing so that it can be duplicated many times on screen.   For tonight&#8217;s example, I&#8217;m going to make a new version that improves a few key points.</p>
<p>First, in the original example the the image files are loaded in the class itself.  This is problematic.  Sure, if you make one object then you are loading files from the hard drive once.  However, if you make many objects, then you are loading the same images over and over again which is totally unnecessary (and can cause problems like using too much memory, stuttering if objects are made during draw(), taking too long to start up, etc.).</p>
<p>We can fix this by loading an array of images in setup() and passing it to the object.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Animation a<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// Load the image sequence first!</span>
  PImage<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> seq <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> PImage<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">40</span><span style="color: #009900;">&#93;</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> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> seq.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    seq<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> loadImage<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;stick/stick&quot;</span><span style="color: #339933;">+</span>nf<span style="color: #009900;">&#40;</span>i<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Now when you make the animation object, you pass it the image array!</span>
  a <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Animation<span style="color: #009900;">&#40;</span>seq<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The class then receives the array in the constructor and passes it to its own array.</p>
</pre>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Animation <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// The array of images</span>
  PImage<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> images<span style="color: #339933;">;</span>
&nbsp;
  Animation<span style="color: #009900;">&#40;</span>PImage<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> images_<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    images <span style="color: #339933;">=</span> images_<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></div></div>

<p>This way (as you'll see in the example) if we make an array of objects, each one uses the same array of images (which we loaded only once). Another feature of this improvement is that the Animation object is more generic, and can be created with any arbitrary array of images.</p>
<p>The original example demonstrated how to have the sequences start at different images so that they didn't all appear to be perfectly in sync.  However, the question I usually get is instead: "How can the sequences play back at variable speeds?"   </p>
<p>The original example used an integer to keep track of the current "frame" of the animation.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">int</span> index <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  index <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>index <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> images.<span style="color: #006633;">length</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here, you see that we move one spot in the array each frame, and the animation is then shown at the frame rate of our sketch.  So in theory, you could change the above to "index = index + 2" to, say, double the speed.   A more flexible way to vary the rate of the animation, however, is to use a float for the index in the array, i.e.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">float</span> index <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">float</span> speed <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// Move the index forward in the animation sequence</span>
  index <span style="color: #339933;">+=</span> speed<span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">// If we are at the end, go back to the beginning</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>index <span style="color: #339933;">&gt;=</span> images.<span style="color: #006633;">length</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// We could just say index = 0</span>
    <span style="color: #666666; font-style: italic;">// but this is slightly more accurate</span>
    index <span style="color: #339933;">-=</span> images.<span style="color: #006633;">length</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> 
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Of course, you can't actually use this float when you go to look up an image in the array -- indices must be integers!  So we simply convert it to an int when the time comes to draw the image.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> display<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">int</span> imageIndex <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#40;</span>index<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  image<span style="color: #009900;">&#40;</span>images<span style="color: #009900;">&#91;</span>imageIndex<span style="color: #009900;">&#93;</span>, x, y<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here is the example.</p>
<p><script type="application/processing">
// An array of "Animation" objects
Animation[] animations = new Animation[6];

// The image sequence will be loaded outside of the object
// We don't want multiple instances of an object
// to load images again and again, just to point to an array
// of pre-loaded images

void setup() {
  size(640,360);
  
  // Load the image sequence
  PImage[] seq = new PImage[40];
  for (int i = 0; i < seq.length; i++) {
    seq[i] = loadImage("http://www.shiffman.net/p5/stick/stick"+nf(i+1,2)+".png"); 
  }
  
  // Make all the objects
  float y = 0;
  for (int i = 0; i < animations.length; i ++ ) {
    // Each object gets an image array and an x,y location
    animations[i] = new Animation(seq,0,y);
    y += 58;
  }
}

void draw() {

  background(255);
  
  // Display, cycle, and move all the animation objects
  for (int i = 0; i < animations.length; i ++ ) {
    animations[i].display();
    animations[i].next();
    animations[i].move();
  }
}


// Daniel Shiffman
// Hanukkah 2011
// 8 nights of Processing examples
// http://www.shiffman.net

// The animation object

class Animation {
  float x;  // location for Animation
  float y;  // location for Animation

  // The index into the array is a float!
  // This allows us to vary the speed of the animation
  // It will have to be converted to an int before the actual image is displayed
  float index = 0; 
  
  // Speed, this will control both the animations movement
  // as well as how fast it cycles through the images
  float speed;

  // The array of images
  PImage[] images;
  
  Animation(PImage[] images_, float x_, float y_) {
    images = images_;
    x = x_;
    y = y_;
    
    // A random speed
    speed = random(1,5);
    // Starting at the beginning
    index = 0;

  }

  void display() {
    // We must convert the float index to an int first!
    int imageIndex = int(index);
    image(images[imageIndex], x, y);
  }

  void move() {
    // Object only moves horizontally
    x += speed;
    if (x > width) {
      x = -images[0].width;
    }
  }

  void next() {
    // Move the index forward in the animation sequence
    index += speed;
    // If we are at the end, go back to the beginning
    if (index >= images.length) {
      // We could just say index = 0
      // but this is slightly more accurate
      index -= images.length;
    } 
  }
}
</script></p>
<p>Download source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/AnimationExample.zip'>AnimationExample.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/26/night-6-image-sequence-object-with-variable-speed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Revisiting Flight404 Particles</title>
		<link>http://www.shiffman.net/2011/02/28/revisiting-flight404-particles/</link>
		<comments>http://www.shiffman.net/2011/02/28/revisiting-flight404-particles/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 17:40:27 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[flight404]]></category>
		<category><![CDATA[nature of code]]></category>
		<category><![CDATA[particles]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=792</guid>
		<description><![CDATA[In February 2008, Robert Hodgin published a series of Particle System examples that demonstrated many of the techniques behind his amazing work (i.e.: Magnetosphere). The examples, however, use some advanced GL calls (accessing JOGL directly) and no longer work in &#8230; <a href="http://www.shiffman.net/2011/02/28/revisiting-flight404-particles/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/02/flight404_particles.jpg" alt="" title="flight404_particles" width="400" height="411" class="alignnone size-full wp-image-793" /></p>
<p>In February 2008, Robert Hodgin <a href="http://www.flight404.com/blog/?m=200802">published a series of Particle System examples</a> that demonstrated many of the techniques behind his amazing work (i.e.: <a href="http://roberthodgin.com/magnetosphere-itunes-visualizer/">Magnetosphere</a>).   The examples, however, use some advanced GL calls (accessing JOGL directly) and no longer work in Processing 1.0.   I would say a student comes to ask me about updating these examples several times a semester and I usually respond by pretending I know what I&#8217;m talking about and pointing the student some vague openGL direction.   It&#8217;s time for me to bit the bullet and figure this out myself.  </p>
<p>Step 1 is simply to recreate the examples using Processing&#8217;s core drawing functions sans fancy GL.   Now, they run a great deal slower than Robert&#8217;s original examples because they are no longer using display lists.</p>
<p>Check out the <a href="https://github.com/shiffman/The-Nature-of-Code/tree/master/chp4_systems/flight404">source</a> or download <a href="https://github.com/shiffman/The-Nature-of-Code/blob/master/chp4_systems/flight404.zip?raw=true">flight404.zip</a>.</p>
<p>Step 2 is to use the wonderful <a href="http://codeanticode.wordpress.com/">Andrés Colubri</a>&#8216;s <a href="http://glgraphics.sourceforge.net/">GLGraphics</a> library to optimize for performance.   Stay tuned.</p>
<p>UPDATE: Step 1a is to create OPENGL textures directly like so:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">particleTex <span style="color: #339933;">=</span> TextureIO.<span style="color: #006633;">newTexture</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">File</span><span style="color: #009900;">&#40;</span>dataPath<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;particle.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>, <span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>(Thanks to Jeff Gentes and Ben Hosken for chiming in)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/02/28/revisiting-flight404-particles/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Asteroids Spaceship</title>
		<link>http://www.shiffman.net/2011/02/13/asteroids-spaceship/</link>
		<comments>http://www.shiffman.net/2011/02/13/asteroids-spaceship/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 20:23:05 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[asteroids]]></category>
		<category><![CDATA[book]]></category>
		<category><![CDATA[nature of code]]></category>
		<category><![CDATA[PVector]]></category>
		<category><![CDATA[trigonometry]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=767</guid>
		<description><![CDATA[One of the &#8220;trignometry + forces&#8221; exercises from my upcoming Nature of Code book is to implement in Processing the spaceship from asteroids. Here&#8217;s a solution! Source: _03_asteroids.zip]]></description>
			<content:encoded><![CDATA[<p>One of the &#8220;trignometry + forces&#8221; exercises from my <a href="">upcoming Nature of Code book</a> is to implement in Processing the spaceship from asteroids.   Here&#8217;s a solution!</p>
<p><script type="application/processing">

// Nature of Code 2011
// Daniel Shiffman
// Chapter 3: Asteroids exercise
// http://www.shiffman.net

// Mover object
Spaceship ship;

void setup() {
  size(435, 200);
  frameRate(60);
  smooth();
  ship = new Spaceship();
}

void draw() {
  background(50); 
  
  // Update location
  ship.update();
  // Wrape edges
  ship.wrapEdges();
  // Draw ship
  ship.display();
   

  fill(255);
  textSize(14);
  text("arrow keys turn ship, press 'z' to thrust",10,height-5);

  // Turn or thrust the ship depending on what key is pressed
  if (keyPressed) {
    if (key == CODED && keyCode == LEFT) {
      ship.turn(-0.03);
    } else if (key == CODED && keyCode == RIGHT) {
      ship.turn(0.03);
    } else if (key == 'z') {
      ship.applyThrust(); 
    }
  }
}

// Nature of Code 2011
// Daniel Shiffman
// Chapter 3: Asteroids

class Spaceship { 
  // All of our regular motion stuff
  PVector location;
  PVector velocity;
  PVector acceleration;

  // Arbitrary damping to slow down ship
  float damping = 0.995;
  float topspeed = 6;

  // Variable for heading!
  float heading = 0;

  // Size
  float r = 16;

  // Are we thrusting (to color boosters)
  boolean thrust = false;

  Spaceship() {
    location = new PVector(width/2,height/2);
    velocity = new PVector();
    acceleration = new PVector();
  } 

  // Standard Euler integration
  void update() { 
    velocity.add(acceleration);
    velocity.mult(damping);
    velocity.limit(topspeed);
    location.add(velocity);
    acceleration.mult(0);
  }

  // Newton's law: F = M * A
  void applyForce(PVector force) {
    PVector f = force.get();
    //f.div(mass); // ignoring mass right now
    acceleration.add(f);
  }

  // Turn changes angle
  void turn(float a) {
    heading += a;
  }
  
  // Apply a thrust force
  void applyThrust() {
    // Offset the angle since we drew the ship vertically
    float angle = heading - PI/2;
    // Polar to cartesian for force vector!
    PVector force = new PVector(cos(angle),sin(angle));
    force.mult(0.1);
    applyForce(force); 
    // To draw booster
    thrust = true;
  }

  void wrapEdges() {
    float buffer = r*2;
    if (location.x > width +  buffer) location.x = -buffer;
    else if (location.x < -buffer) location.x = width+buffer;
    if (location.y > height + buffer) location.y = -buffer;
    else if (location.y < -buffer) location.y = height+buffer;
  }


  // Draw the ship
  void display() { 
    stroke(255);
    pushMatrix();
    translate(location.x,location.y+r);
    rotate(heading);
    fill(100);
    if (thrust) fill(255,0,0);
    // Booster rockets
    rect(-r/2,r,r/3,r/2);
    rect(r/2,r,r/3,r/2);
    fill(100);
    // A triangle
    beginShape();
    vertex(-r,r);
    vertex(0,-r);
    vertex(r,r);
    endShape(CLOSE);
    rectMode(CENTER);
    popMatrix();
    
    thrust = false;
  }
}
</script></p>
<p>Source: <a href="http://www.shiffman.net/itp/classes/nature/week04_s11/_03_asteroids.zip">_03_asteroids.zip</a></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/02/13/asteroids-spaceship/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Nature of Code book: PVector Spring example</title>
		<link>http://www.shiffman.net/2011/02/10/nature-of-code-book-pvector-spring-example/</link>
		<comments>http://www.shiffman.net/2011/02/10/nature-of-code-book-pvector-spring-example/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 18:34:52 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[nature of code]]></category>
		<category><![CDATA[processing.org]]></category>
		<category><![CDATA[springs]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=742</guid>
		<description><![CDATA[I&#8217;m working this week on Chapter 3 of my upcoming Nature of Code book. For the most part, if you are looking to connect particles with springs, I recommend the wonderful verlet physics of toxiclibs, and I have some examples &#8230; <a href="http://www.shiffman.net/2011/02/10/nature-of-code-book-pvector-spring-example/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working this week on Chapter 3 of my <a href="https://www.kickstarter.com/projects/shiffman/the-nature-of-code-book-project">upcoming Nature of Code book</a>.   For the most part, if you are looking to connect particles with springs, I recommend the wonderful verlet physics of <a href="http://toxiclibs.org/">toxiclibs</a>, and I have some examples for that <a href="http://www.shiffman.net/teaching/nature/toxiclibs/">here</a>.  Nevertheless, I am including an elementary implementation of a single &#8220;bob&#8221; connected  to an &#8220;anchor&#8221; point via a &#8220;spring&#8221; force.   The example implements <a href="http://en.wikipedia.org/wiki/Hooke's_law">Hooke&#8217;s Law</a> (Spring Force = -k * displacement) with the <a href="http://processing.org/reference/PVector.html">PVector</a> class, using the Euler integration model of all my other examples.  Here it is below.</p>
<p><script type="application/processing">
// Mover object
Bob bob;

// Spring object
Spring spring;

void setup() {
  size(430, 200);
  smooth();
  frameRate(60);
  // Create objects at starting location
  // Note third argument in Spring constructor is "rest length"
  spring = new Spring(width/2,10,100); 
  bob = new Bob(width/2,100); 

}

void draw()  {
  background(50); 
  // Apply a gravity force to the bob
  PVector gravity = new PVector(0,1);
  bob.applyForce(gravity);
  
  // Connect the bob to the spring (this calculates the force)
  spring.connect(bob);
  // Constrain spring distance between min and max
  spring.constrainLength(bob,30,200);
  bob.dragIt(mouseX,mouseY);
  bob.update();

  spring.displayLine(bob);
  bob.display();
  spring.display();

  fill(255);
  text("click on bob to drag",10,height-5);

  
}


// For mouse interaction with bob

void mousePressed()  {
  bob.clicked(mouseX,mouseY);
}

void mouseReleased()  {
  bob.stopDragging(); 
}

class Bob { 
  PVector location;
  PVector velocity;
  PVector acceleration;
  float mass = 10;
  
  // Arbitrary damping to simulate friction / drag 
  float damping = 0.98;

  // For mouse interaction
  PVector drag;
  boolean dragging = false;

  // Constructor
  Bob(float x, float y) {
    location = new PVector(x,y);
    velocity = new PVector();
    acceleration = new PVector();
    drag = new PVector();
  } 

  // Standard Euler integration
  void update() { 
    velocity.add(acceleration);
    velocity.mult(damping);
    location.add(velocity);
    acceleration.mult(0);
  }

  // Newton's law: F = M * A
  void applyForce(PVector force) {
    PVector f = force.get();
    f.div(mass);
    acceleration.add(f);
  }


  // Draw the bob
  void display() { 
    stroke(255);
    fill(100);
    if (dragging) {
      fill(255);
    }
    ellipse(location.x,location.y,mass*2,mass*2);
  } 

  void dragIt(int mx, int my) {
    if (dragging) {
      location.x = mx + drag.x;
      location.y = my + drag.y;
    }
  }
  // This checks to see if we clicked on the mover
  void clicked(int mx, int my) {
    float d = dist(mx,my,location.x,location.y);
    if (d < mass) {
      dragging = true;
      drag.x = location.x-mx;
      drag.y = location.y-my;
    }
  }

  void stopDragging() {
    dragging = false;
  }


}

class Spring { 

  // Location
  PVector anchor;

  // Rest length and spring constant
  float len;
  float k = 0.1;
  
  // Constructor
  Spring(float x, float y, int l) {
    anchor = new PVector(x,y);
    len = l;
  } 

  // Calculate spring force
  void connect(Bob b) {
    // Vector pointing from anchor to bob location
    PVector force = PVector.sub(b.location,anchor);
    // What is distance
    float d = force.mag();
    // Stretch is difference between current distance and rest length
    float stretch = d - len;
    
    // Calculate force according to Hooke's Law
    // F = k * stretch
    force.normalize();
    force.mult(stretch);
    force.mult(-k);
    b.applyForce(force);
  }

  // Constrain the distance between bob and anchor between min and max
  void constrainLength(Bob b, float minlen, float maxlen) {
    PVector dir = PVector.sub(b.location,anchor);
    float d = dir.mag();
    // Is it too short?
    if (d < minlen) {
      dir.normalize();
      dir.mult(minlen);
      // Reset location and stop from moving (not realistic physics)
      b.location = PVector.add(anchor,dir);
      b.velocity.mult(0);
    // Is it too long?
    } else if (d > maxlen) {
      dir.normalize();
      dir.mult(maxlen);
      // Reset location and stop from moving (not realistic physics)
      b.location = PVector.add(anchor,dir);
      b.velocity.mult(0);
    }
  }

  void display() { 
    fill(100);
    rectMode(CENTER);
    rect(anchor.x,anchor.y,10,10);
  }
  
  void displayLine(Bob b) {
    stroke(255);
    line(b.location.x,b.location.y,anchor.x,anchor.y);
  }
  
}
</script></p>
<p>Source: <a href="http://www.shiffman.net/itp/classes/nature/week04_s11/_03spring.zip">_03spring.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/02/10/nature-of-code-book-pvector-spring-example/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Kinect Library Tutorial and Documentation Page</title>
		<link>http://www.shiffman.net/2011/01/15/kinect-library-tutorial-and-documentation-page/</link>
		<comments>http://www.shiffman.net/2011/01/15/kinect-library-tutorial-and-documentation-page/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 15:36:10 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[kinect]]></category>
		<category><![CDATA[processing.org]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=659</guid>
		<description><![CDATA[In preparation for a Kinect hacking session at Microsoft&#8217;s 2011 Social Computing Symposium, I put together a documentation and tutorial page for the Processing kinect library: http://www.shiffman.net/p5/kinect/]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/shiffman/5356776039/" title="Untitled by shiffman, on Flickr"><img src="http://farm6.static.flickr.com/5205/5356776039_6276d464d0_m.jpg" width="240" height="179" alt="" /></a></p>
<p>In preparation for a Kinect hacking session at Microsoft&#8217;s <a href="http://scs.labforsocialcomputing.net/">2011 Social Computing Symposium</a>, I put together a documentation and tutorial page for the Processing kinect library:</p>
<p><a href="http://www.shiffman.net/p5/kinect/">http://www.shiffman.net/p5/kinect/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/01/15/kinect-library-tutorial-and-documentation-page/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Updated Kinect Library for Processing</title>
		<link>http://www.shiffman.net/2010/12/18/updated-kinect-library-for-processing/</link>
		<comments>http://www.shiffman.net/2010/12/18/updated-kinect-library-for-processing/#comments</comments>
		<pubDate>Sun, 19 Dec 2010 03:37:13 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[kinect]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[processing.org]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=645</guid>
		<description><![CDATA[A quick post to announce an updated Kinect library for Processing on github. This new library uses the most recent libfreenect drivers (mac os x only still) and builds off of the existing JNI Java Wrapper. Links: Download library and &#8230; <a href="http://www.shiffman.net/2010/12/18/updated-kinect-library-for-processing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><iframe src="http://player.vimeo.com/video/18058700?title=0&amp;byline=0&amp;portrait=0&amp;color=ff9933" width="435" height="282" frameborder="0"></iframe></p>
<p>A quick post to announce an updated Kinect library for Processing on github. This new library uses the most recent libfreenect drivers (mac os x only still)  and builds off of the existing <a href="http://openkinect.org/wiki/Java_Wrapper">JNI Java Wrapper</a>.  Links:</p>
<p>Download library and example:<br />
<a href="https://github.com/shiffman/libfreenect/raw/master/wrappers/java/processing/distribution/openkinect.zip">openkinect.zip</a></p>
<p>Source:<br />
<a href="https://github.com/shiffman/libfreenect/tree/master/wrappers/java/processing">https://github.com/shiffman/libfreenect/tree/master/wrappers/java/processing</a></p>
<p>My tests show 30 FPS no problem for either the depth or RGB image, if you request both images, however, I&#8217;m only currently getting about 20 FPS.  The update fixes a few bugs, exposes the raw depth data and includes a point cloud demo (see above video).</p>
<p>I have a list of &#8220;to-do&#8221; items here:</p>
<p><a href="https://github.com/shiffman/libfreenect/issues">https://github.com/shiffman/libfreenect/issues</a><br />
 (a shortened version of the very long list in my head)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2010/12/18/updated-kinect-library-for-processing/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
		<item>
		<title>Big Screens 2010</title>
		<link>http://www.shiffman.net/2010/11/15/big-screens-2010/</link>
		<comments>http://www.shiffman.net/2010/11/15/big-screens-2010/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 18:56:41 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[bigscreens]]></category>
		<category><![CDATA[mostpixelsever]]></category>
		<category><![CDATA[mpe]]></category>
		<category><![CDATA[openframeworks]]></category>
		<category><![CDATA[processing.org]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=640</guid>
		<description><![CDATA[http://itp.nyu.edu/bigscreens2010/]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/shiffman/5179462920/" title="Big Screens 2010 by shiffman, on Flickr"><img src="http://farm2.static.flickr.com/1251/5179462920_b564120b73.jpg" width="435" alt="Big Screens 2010" /></a></p>
<p><a href="http://itp.nyu.edu/bigscreens2010/index.php">http://itp.nyu.edu/bigscreens2010/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2010/11/15/big-screens-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kinect and Processing</title>
		<link>http://www.shiffman.net/2010/11/14/kinect-and-processing/</link>
		<comments>http://www.shiffman.net/2010/11/14/kinect-and-processing/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 03:41:08 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[kinect]]></category>
		<category><![CDATA[processing.org]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=635</guid>
		<description><![CDATA[This is all very preliminary, but here is a first pass as a Processing Kinect library: http://www.shiffman.net/p5/kinect.zip (Mac OSX only for now, sorry!) UPDATE (12/18/10): New version of the library can be downloaded from github: openkinect.zip. Source: https://github.com/shiffman/libfreenect/tree/master/wrappers/java/processing None of &#8230; <a href="http://www.shiffman.net/2010/11/14/kinect-and-processing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/shiffman/5176786585/" title="Kinect Processing Library in Action by shiffman, on Flickr"><img src="http://farm2.static.flickr.com/1384/5176786585_7f4e7b534f.jpg" width="500" height="359" alt="Kinect Processing Library in Action" /></a></p>
<p>This is all very preliminary, but here is a first pass as a Processing Kinect library:</p>
<p><del>http://www.shiffman.net/p5/kinect.zip</del><br />
(Mac OSX only for now, sorry!)<br />
UPDATE (12/18/10): New version of the library can be downloaded from github:</p>
<p><a href="https://github.com/shiffman/libfreenect/raw/master/wrappers/java/processing/distribution/openkinect.zip">openkinect.zip</a>.  </p>
<p>Source: <a href="https://github.com/shiffman/libfreenect/tree/master/wrappers/java/processing">https://github.com/shiffman/libfreenect/tree/master/wrappers/java/processing</a></p>
<p>None of this would have been possible without the heroic efforts of <a href="http://marcansoft.com/">Hector Martin</a>, the <a href="https://github.com/OpenKinect/libfreenect">OpenKinect</a> project, and various members of the <a href="http://www.openframeworks.cc/">openFrameworks</a> community.  There&#8217;s a great thread with discussion and code here: </p>
<p><a href="http://www.openframeworks.cc/forum/viewtopic.php?f=14&#038;t=4947">http://www.openframeworks.cc/forum/viewtopic.php?f=14&#038;t=4947</a></p>
<p>Video in action here:</p>
<p><iframe src="http://player.vimeo.com/video/16832724?title=0&amp;byline=0&amp;portrait=0&amp;color=ff9933" width="501" height="282" frameborder="0"></iframe></p>
<p>Processing code looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">shiffman.kinect.*</span><span style="color: #339933;">;</span>
&nbsp;
PImage img<span style="color: #339933;">;</span>
PImage depth<span style="color: #339933;">;</span>
&nbsp;
 <span style="color: #000066; font-weight: bold;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  size<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">640</span>,<span style="color: #cc66cc;">240</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  NativeKinect.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  img <span style="color: #339933;">=</span> createImage<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">640</span>,<span style="color: #cc66cc;">480</span>,RGB<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  depth <span style="color: #339933;">=</span> createImage<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">640</span>,<span style="color: #cc66cc;">480</span>,RGB<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  NativeKinect.<span style="color: #006633;">update</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  img.<span style="color: #006633;">pixels</span> <span style="color: #339933;">=</span> NativeKinect.<span style="color: #006633;">getPixels</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  img.<span style="color: #006633;">updatePixels</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  depth.<span style="color: #006633;">pixels</span> <span style="color: #339933;">=</span> NativeKinect.<span style="color: #006633;">getDepthMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  depth.<span style="color: #006633;">updatePixels</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  image<span style="color: #009900;">&#40;</span>img,<span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">320</span>,<span style="color: #cc66cc;">240</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  image<span style="color: #009900;">&#40;</span>depth,<span style="color: #cc66cc;">320</span>,<span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">320</span>,<span style="color: #cc66cc;">240</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2010/11/14/kinect-and-processing/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
	</channel>
</rss>

