You are on page 1of 24

c  

     


March 12th, 2010 ² Code, Java, Processing, Software

I have recently decided to take on the task of creating a particle system from scratch designed to
work specifically with Processing. I have always been interested in the subject and I wanted to
challenge myself and share something with the Processing community. I am going to write this
series of articles to document my learning process as well as the evolution of this library.

For this first article, I am going to start with the most basic concepts of dealing with particles in
Processing. No differential equations, no numerical methods, just simple linear algebra and Java.
This one may be pretty boring to most Processing users, but I want to start off simple to establish
a good base of knowledge because it will get pretty hairy later. If you are a complete beginner, I
suggest you start here and come back when you have a decent understanding of Processing.

þ 
   

The first thing we want to examine is how to draw and move a single particle. First check out
this code in action here then come back and closely examine the source:

££ 

   

 



££ 
 

££ 

 



 



 
 





 

 

 !

" 

££ 


 

 #

 
%


&  '!!

££ %


%
"



 




£(

(
 


&
  


 

(
""&

 
"
 " 
 

(

 )


*+



*+


££


"  


 
"  #  


 #

 
 #


££ 




" 





+

+
% £'

££ 
%
 "
 

££
&£%
,

*
"&


+
 ",)-
) 


+
 ",) 
)' 

et¶s quickly dissect what is going on here. First we establish the two floats u and  to be the
center point of the particle in screen coordinates. Hopefully you have messed with Processing or
computer animation enough to understand screen coordinates. Then we establish u and  as
the velocity of our particle. As we remember in high school physics, velocity is defined as the
change in position over time. In computer animation, our general unit of time is a ³frame´. As
you should know, the draw() function is called at the framerate that you run the program at
[Processing default is 60 times a second I think]. So every time that function is called, we redraw
a white background drawing over any previous frames:

&  '!!

then we draw the particle as an ellipse at it¶s current x, y position:

 




then we update the position one time step:


*+



*+


and this is done 60 times a second creating the illusion of motion due to persistence of vision.

2 2

†ou may also remember from your childhood science classes that acceleration is the change in
velocity over time. Quickly view this code in action and take note of the now non-uniform speed
of the particle:

 



 



££

 



 
 






 

 

 !

" 

££ 


 

 #

 
%


&  '!!

££ %


%
"



 




£(

(
 

 
&
  




(
""&


"
 " 
 

(

 )


*+



*+


£(

(
 


&
  


 

(
""&

 
"
 " 
 

(

 )


*+



*+


££


"  


 
"  #  


 #

 
 #


££ 




" 





+

+
% £'

££ 
 




+

+



+
 ",) 
) 


+
 ")
) ££ % %

Now that we are adding on the acceleration to the velocity each frame, the velocity increases as
time goes on and the particle moves faster and faster. Kind of like gravity (an acceleration of 9.8
m/s2) or a car accelerating faster and faster. Congratulations! We now have the ability to crudely
describe Newtonian motion!

2   


Now that we can create one particle with ease, let¶s create many. Basically what we need to do is
create an abstraction of what a particle is then turn that into a Java class. This isn¶t a Java lesson
and I hope you know what that means so let¶s jump straight into it. Check out this program then
come back and learn about the code.

#./
 

 
0123#456789:;
+


 
 





 

 

 !

" 

 
%


&  '!!


 
<+



 
 

+


=
0123#456789:;
**


 ./) 

 
"  #  



+
%
#.0123#456789:;/

 
 

+


=
0123#456789:;
**


 ./
+
%
#

&

#


 



 



 



&
#



+
"  >


+
"  ?


+

+



+
 ",)'
)'


+
 ",)@
)!

&
 
 



*+



*+



*+



*+


 




lf course this is too crazy to resemble anything real in the our physical world, but it shows the
point. Basically what we have done is created a Particle class which contains references to it¶s
own state information. Then we can have an array of Particles and update those in a nice loop.
There is still some more improvement that can be done to this though. et¶s talk about vectors.

ƒ

A ƒ is essentially a  row  column matrix. In computer graphics, we use the Vector data
structure to represent multi-dimensional state information such as position, velocity, and
acceleration. Because they are matrices and we set them to have the same dimensions, we can
use standard matrix operations and concepts from linear algebra to help us solve some of the
systems of linear equations we face. Processing contains it¶s own implementation of a vector
called a ³PVector´. It is a 3-dimensional vector so we can represent things in 2d or 3d space.
Check out this re-write of the last program in action and I will explain how it works after the
code:

49 
 

 
97A:;#40
+
'

££ &


#B 

+

%
#B 
)'!

 
 





 

 

 !

" 


+
%
49 

 
%


&  '!!

££ 

%
"  
" 


& "  >, "  >
C
) 


 )  %
#

 
 

+
 ) , 

C+

,,


#

+
#  )

< ) 




 )" 

&

#


#B 
  

#B 
 

 


&
#


 
+
%
#B "  >
"  ?

££
 
 "




"  
" " 

 
+
%
#B "  >, "  >
"  ?, "  ?


+


&
& 
 


 )  

  )  

   )


  )





C
97A:;#40



 

**




Notice that I changed over the x and y variables to the PVectors and this gives us operations like
add, subtract, multiply, magnitude, normalize, and etc. Check out this article on matrix math if
you don¶t remember it from grade school. In this example, all you need to know is that when you
add two PVectors, it does a matrix add. I do, however, highly suggest that you get real familiar
with matrix math and systems of equations if you want to move on:

 )  

££
D 


 ) 


 )* )

 )* )

 )* )




I also moved the  vector out to have global static scope. And I am getting the
velocity from the changing mouse positions. Remember that velocity is change in position, so we
can get the velocity vector by subtracting the new cursor position from the old.

I don¶t really want to go into Java stuff but notice that I also changed the array to an Arrayist.
And if you are wondering why I didn¶t use a parameterized Arrayist, it is b/c Processing uses a
light-weight open source java compiler that doesn¶t support it.

u

That is it for now. I hope that wasn¶t too boring. In the next article, I am going to talk more about
vectors, different kinds of forces. I will also briefly point out the inaccuracies in our integration
technique and open up a huge can of maths worms.

? ?
c  
    
  

March 17th, 2010 ² Code, Java, Processing, Software

This article is one in a series of articles about particle systems in Processing. To view the first of
the series, click here.

To recap, in my last article, I went over the basics of particles and Newtonian motion in
Processing. In this article, I am going to explain using  and Newton¶s Second aw of
Motion to describe the effects of forces on our particles. I am also going to point out that our
current integration technique is flawed as segway into the next article.



When we last left our particle physics sandbox, it looked liked this:

49 
 

 
97A:;#40
+
'

££ &


#B 

+

%
#B 
)'!

 
 





 

 

 !

" 


+
%
49 

 
%


&  '!!

££ 

%
"  
" 


& "  >, "  >
C
) 


 )  %
#

 
 

+
 ) , 

C+

,,


#

+
#  )

< ) 




 )" 

&

#


#B 
  

#B 
 

 


&
#


 
+
%
#B "  >
"  ?

££
 
 "




"  
" " 

 
+
%
#B "  >, "  >
"  ?, "  ?


+


&
& 
 


 )  

  )  

   )


  )





C
97A:;#40



 

**




The PVector  represents the acceleration resulting from a gravitational force.
Gravity is a force and results in an acceleration of an object. There is an equation to determine
gravity but we usually take it to result in a constant acceleration of 9.8 m/s^2 when viewing
things on earth. This is because our measurements on earth usually involve relatively small and
close things [relative to earth's mass and space] and the difference b/w earth¶s effects on these
objects is negligible.

Anyways, like all other units of motion, a force can be represented as a Vector. And different
forces have different equations to describe their effects. The result a force has on an object is
described by Newton¶s Second aw of Motion:

where is the ,  is the object¶s , and  is . It is usually more helpful to
represent the equation in this alternate form:

Knowing this, we can now calculate the acceleration resulting from a force on an object. First we
will get rid of the global PVector acceleration then we will alter the Particle class to look like
this:

&

#


#B 
  

#B 
 

#B 
 

 
" 

&
#


 
+
%
#B "  >
"  ?

££
 
 "




"  
" " 

 
+
%
#B "  >, "  >
"  ?, "  ?


+
%
#B 



"
+


&
& 
 


 )  

  )  

   )


  )



££%

 "


 






&  )
=
)
EE
&  )
=
) 



 

 )"
££ 







 
 A #B 
 


 ) #B )  


" 

First, note the changes to the Particle class structure:

á? ?
? ?? ? ?? ? 
 ?
?  ?
????  ? ??? ? ?á? ?   ?
? ???
   !  "? ?
#? ?? ?  ??
? ???  ??
?

?$
??  ?

?

Take a look at the applyForce method. There are a few things to note about this method in
particular:

á ? ð  ????$ 

?ð  ?% ? ?? ? ? ? &?Ê  ?


 ? ?? 

 ?Ê? ? 
 ?$' ? ??$?
 ? ?  ? ??
 ?(??

?? ? 
 ?
? ?)? ??
 ?
 ?? 
 ?? ?
 ?*
+ ???  ?$' ? ? ?  ??  ? ?? ? 
?  ?
,? ? ?  ? ?  ? ??  ?
 ? ð ?????-?
 ?$?  ??(??? ?V  V  Ê?
 ?? ? ? ?  ?  ?? ? ? ??
? ??
 ??  ?  ? ??  ? ? ?? !  ???
 ?  ? ? ?  ? ??
?  ? ??? 
?$ ? $ ??
?
 ?

2 

Now we want to actually apply a force to a particle. There are many types of forces and many
equations to describe their behavior. By far, one of the easiest to understand is a  
. It most commonly manifests itself in day to day life in the form of  but can also be
used to simulate other phenomena. The equation is:

?
where is the  , is a mathematical  known as the ³  
³, and  is the object¶s . lbviously, the larger is, the more friction is applied
and the quicker your object will come to a state of rest. It is usually between 0.0 and 1.0 . To
implement this, I added this global function:

 
 F  A #

 
 


#B 

+
#B )" ) 
, 

) A 

Pretty self-explanatory. We take the velocity of the particle that we are applying this force to and
we multiply it by the coefficient * -1. et¶s put all this together. Check out the code in action,
then come back and examine the whole source:

49 
 

 
 





 

 

 !

" 


+
%
49 

 
%


&  '!!

££ 

%
"  
" 


& "  >, "  >
C
) 


 )  %
#

 
 

+
 ) , 

C+

,,


#

+
#  )

££
 " 

 

  

 F  A  


)@

< ) 




 )" 

 
 F  A #

 
 


#B 

+
#B )" ) 
, 

) A 

&

#


#B 
  

#B 
 

#B 
 

 
" 

&
#


 
+
%
#B "  >
"  ?

££
 
 "




"  
" " 

 
+
%
#B "  >, "  >
"  ?, "  ?


+
%
#B 



"
+


&
& 
 


££%

 "


 






&  )
=
)
EE
&  )
=
) 



 

 )  

  )  

   )


  )



 )"




 
 A #B 
 


 ) #B )  


" 

2 2 2

Now we are going to implement a more complicated force, attraction. This force could be used to
simulate gravitational force, without all that Einstein, space-time continuum craziness of course.
The equation we are going to use is:

where is the , ! is the  [defines the apparent 'strength'],  and
" are the  of the two bodies in effect, and is the  between the two bodies. The
problem is that this equation computes the  , or the power, of the force; but not the
direction. With the dissipative force, the direction was the opposite of the velocity. This was
obvious in the equation. The force in this situation however is between the 2 bodies, so naturally,
the equation will involve subtracting the positions. Here it is:

where is  and # and #" are the  of the bodies.

Now we will implement the global function to apply an attractive force on two particles. We will
also have to modify the Particle class:

 
 4A #

#
&
 
 
 

" F  


#B 

+
#B ) &)  
&)  

 

+
)"



=
" F  

+
" F  

) "

 
 
+
  
(
)"
(
&)" 
£

(


)" 


<&) 
&) A  


<) 


)", 

) A  

&

#


#B 
  

#B 
 

#B 
 

 
" 

& 
 

&
#


 
+
%
#B "  >
"  ?

££
 
 "




"  
" " 

 
+
%
#B "  >, "  >
"  ?, "  ?


+
%
#B 



"
+



+
 

&
& 
 



 


'!!

$
 


 )  

  )  

 )"

 !

   )


  )






 
 A #B 
 


 ) #B )  


" 

I added a u property. If the Particle is fixed, it is not affected by outside forces. They also
render red.

As for the  2$%, for the most part, it follows our two equations above. The
first thing to note is that we are constraining the distance:



=
" F  

+
" F  

This is because too small a distance value will create too large a force and the particles will go
flying off. Also notice that we are applying ³equal but opposite´ forces on each particle:


<&) 
&) A  


<) 


)", 

) A  

Now let¶s look at the whole thing. Check out this code in action then come back and view the
source:

49 
 

#


 
 


@
G

 

 

 !

" 


+
%
49 


+
%
#

) 
+
%
#B % £'
£'

)
+


)"
+
!)

 ) 

 
%


&  '!!

 
 

+
 ) , 

C+

,,


#

+
#  )

££
 " 

 

  

 F  A  


) 

££ " 
%
 

" F  


" F  
& %


 4A 

!
!

< ) 




 )" 

 
"  F 


 )  %
#

 
 F  A #

 
 


#B 

+
#B )" ) 
, 

) A 

 
 4A #

#
&
 
 
 

" F  


#B 

+
#B ) &)  
&)  

 

+
)"



=
" F  

+
" F  

) "

 
 
+
  
(
)"
(
&)" 
£

(


)" 


<&) 
&) A  


<) 


)", 

) A  

&

#


#B 
  

#B 
 

#B 
 

 
" 

& 
 

&
#


 
+
%
#B "  >
"  ?

££
 
 "




"  
" " 

 
+
%
#B "  >, "  >
"  ?, "  ?


+
%
#B 



"
+



+
 

&
& 
 



 


'!!

$
 


 )  

  )  

 )"

 !

   )


  )






 
 A #B 
 


 ) #B )  


" 

Hopefully this code is pretty easy to understand.  is the center red particle. We set it¶s
location to the center of the screen, set it as fixed, then give it a bigger mass. For every particle,
we are applying both the dissipative force and the attraction to particle a:

 F  A  


) 

 4A 

!
!

&u'þ (

If you took the time to closely examine our technique for determining a particle¶s position at
each frame, you may have noticed some inaccuracies. et¶s use an analogy. Switch over your
thought process from 2d down to 1d. et¶s say we are in a car travelling down a road [is
commonly described as if it is one dimension]. If we know the car¶s acceleration, and u
 , we can theoretically calculate the position after a given time with the
equation:

where  is the ,  is the ,  is the , and  is . So if we


have an initial velocity of ), an acceleration of ) meters per second every second and we travel
for ) seconds, we end up with a distance of *)). Now let¶s try this with our
methodology. Here is a python script to simulate our technique:


+



+



+



+


%

=+
H

 
I
+
J I
J


 
I
+
J I
J

 
I
+
J I
J


 
I,,,,,,,,,,,,,,,,,,,I


*+



*+



*+

If we run this, we get:

t=0
pos = 0
vel = 0
²²²²²²-
t=1
pos = 10
vel = 10
²²²²²²-
t=2
pos = 30
vel = 20
²²²²²²-
t=3
pos = 60
vel = 30
²²²²²²-
t=4
pos = 100
vel = 40
²²²²²²-
t=5
pos = 150
vel = 50
²²²²²²-
t=6
pos = 210
vel = 60
²²²²²²-
t=7
pos = 280
vel = 70
²²²²²²-
t=8
pos = 360
vel = 80
²²²²²²-
t=9
pos = 450
vel = 90
²²²²²²-
t = 10
pos = 550
vel = 100
²²²²²²-

Position = **)!?!? Why is it so far off? After 10 seconds in the simulation we have already
drifted off 50 meters from where we should be. Another problem we see is that this error is
accumulating [or compounding]. So as time goes on, our calculations of the particle¶s positions
will become farther and farther away from the truth. The solution to this problem requires a
closer examination of the mathematics behind our process and Newton¶s Second aw in general.
In the next article, I am going to attempt to explain how this error occurs and how we can reduce
it to a manageable level.

? ?
c  
      
 

March 18th, 2010 ² Code, Java, Processing, Software

This article is one in a series of articles about particle systems in Processing. To view the first of
the series, click here.

In the last article, we discussed forces and left off with questions about our technique for
determining the particle¶s position at each frame. It turns out that it was wildly inaccurate. In this
article, I am first going to try to explain the mathematics behind what we are doing and use that
knowledge to expose the source of our problem. Then I am going to try to present a solution.

 +   ,

Recall the equation I presented in the last article which gives us distance given the state of a
body and a time period:

This equation gives us an u distance for the given acceleration, initial velocity, and time
period and we used it to measure the error of our technique. So the question remains, why not
use this equation to determine the particle position at each frame? Well, the problem is
unfortunately too complicated for me to explain easily but I am going to try. From my
understanding, that equation only works when acceleration is constant over time. If you take a
hard look at it, this property will become apparent. The equation gives you a distance for a given
 of time but is not actually a continuous function with respect to time. In other words, you
cannot use it to solve acceleration for any given point in time. In a particle system, there may be
 forces acting on a given particle at any time. ln top of that, those forces are
changing the acceleration of the particle in seemingly erratic ways. In fact, it is said that the
function which determines the acceleration with respect to time is u&   but is actually
-u. Therefore, we cannot get an exact value at any given point, we can only approximate
it. Given that our calculations are  u, we have to assume there will always be an
error. All we can do is find techniques to make the error manageable.

..!  -u

So, how exactly were we solving this unknown function before? et¶s step away from our
particle system for a very brief moment. †ou may remember from high school maths that you
can solve the integral of a function by integrating that function over an interval when given
boundary conditions. †ou may also remember that in certain situations, such as when f(t, y) is
unknown or cannot be solved analytically, you can solve these problems by taking an 
 and solving in steps. This is called an    and follows this form:

?
Some tricky manipulating of this formula results in a  which usually looks something like
this:

So, I am pretty bad at all this maths o_0 but hopefully you are starting to see something here. In
this series, we are determining the next value [y_n+1] using the current value [y_n] and adding
the differential function. Just like we did with our particles, we found velocity by adding the last
velocity plus the difference in velocity[acceleration]. Then we did the same for position.
Acceleration is a    derivative so when using this method which solves first order
diffEQs, we must break it down into two first order derivatives:

where  is  and is .

Now let¶s try and make sense out of this mess.

/0   .1 + /(

†ou may not have known it, but the method we were using before in our code is known as
Euler¶s Method and is the defacto, inherent approach to this problem. The only thing I left out is
the  . The actual process should look something like this:

 ) #B )" 




  ) #B )" 




where is the time step in the simulation. As an astute reader, you may realize that the h was
actually accounted for before. It was just assumed to be µ1ƍ ;) The common way to make the
Euler method more accurate is to reduce the time-step [h]. I will explain why in a second, let¶s
just quickly alter the code to see what happens. Go check it out in action then come back and
examine the source:

49 
 

#


 

+
)'
££ %
"

=

 
 


G
G

 

 

 !

" 


+
%
49 



+
%
#

) 
+
%
#B % £'
£'

)
+


 ) 

 
%


&  '!!

 
 

+
 ) , 

C+

,,


#

+
#  )

££
 " 

 

  

 F  A  


) 

 4A 

!
!

< ) 




 )" 

 
"  F 


 )  %
#

 
 F  A #

 
 


#B 

+
#B )" ) 
, 

) A 

 
 4A #

#
&
 
 
 

" F  


#B 

+
#B ) &)  
&)  

 

+
)"



=
" F  

+
" F  

) "

 
 
+
  
(
)"
(
&)" 
£

(


)" 


<&) 
&) A  


<) 


)", 

) A  

&

#


#B 
  

#B 
 

#B 
 

 
" 

& 
 

&
#


 
+
%
#B "  >
"  ?

££
 
 "




"  
" " 

 
+
%
#B "  >, "  >
"  ?, "  ?


+
%
#B 



"
+



+
 

&
& 
 



 


'!!

$
 


 ) #B )" 




  ) #B )" 




 )"

 !

   )


  )






 
 A #B 
 


 ) #B )  


" 

All I did was alter the integration part, added the float at 0.2, and increased the strength to *)))
to speed things up a little. What you should have noticed is that it has gotten a lot slower and it
should be obvious why: lur framerate is the same but we are stepping ahead in the simulation in
smaller steps of time.

What you probably did not notice is the huge increase in accuracy. To prove this, let¶s re-
implement our python script experiment from the last article and compare it with the exact
results again. This time we will have a time step-size of 0.1:


+



+
)


+



+



+


%

=+
H

 
I
+
J I
J


 
I
+
J I
J

 
I
+
J I
J


 
I,,,,,,,,,,,,,,,,,,,I


*+

(



*+

(



*+


When we run this script we get [middle cut out for brevity]:

t=0
pos = 0
vel = 0
²²²²²²-
t = 0.1
pos = 0.1
vel = 1.0
²²²²²²-
t = 0.2
pos = 0.3
vel = 2.0
²²²²²²-
t = 0.3
pos = 0.6
vel = 3.0
²²²²²²-
t = 0.4
pos = 1.0
vel = 4.0
²²²²²²-
t = 0.5
pos = 1.5
vel = 5.0
²²²²²²-
.
.
.
²²²²²²-
t = 9.6
pos = 465.6
vel = 96.0
²²²²²²-
t = 9.7
pos = 475.3
vel = 97.0
²²²²²²-
t = 9.8
pos = 485.1
vel = 98.0
²²²²²²-
t = 9.9
pos = 495.0
vel = 99.0
²²²²²²-
t = 10.0
pos = 505.0
vel = 100.0

2*)*. †ou may remember that using these initial values with our equation:
?

yielded an exact end position of *)). Now we are only   * whereas with a &  
we were   *)! This should show you that the error for this method is close to [i think?]:

There is a mathematical way to determine the real error but we aren¶t going to go into it because
we will be abandoning this method soon and it is too complicated for the little value it provides
us. If you really want to know, check out the Wikipedia article on Euler¶s method.

  . 3 2,

The question arises, why is it more accurate? The answer may help you better understand what is
happening. et¶s look at a graphic representation of the Euler method in action:

Graphical representation of Euler's method (Source: Wikipedia)

Pretend that the blue line is our unknown but well-defined function in which the acceleration is
the dependent variable and that A0, A1, A2, A3, and A4 are the acceleration values we calculate.
Essentially, at each step, we know the derivative [the tangent to the curve] and multiply it by the
time step, then add it to the current 2 value to guess the next value. At that point, we assume we
are at the correct spot and do this again and again and again. †ou can now see why the error
accumulates. We are basically walking a dark path using a slow strobe light. Now imagine that
the 2 values were taken in smaller intervals [the strobe light is blinking faster] and you can see
that we would be closer to the blue line [exact solutions]. But if you took a bigger step size, you
would be farther away from the exact values. The following pictures illustrate the point perfectly.
The red line is the exact solution and the blue is the approximation:
?

big step of h

medium sized step of h

small step of h
?

tiny step of h

Here is the source of these photos.

So as h gets smaller, our approximated curve inches closer to the exact curve.

-u  

Where do we go from here? Well, we have determined that the Euler method is just not really
feasible. Sure, it may have worked out for our little examples but we can achieve more stability
and accuracy with some other methods. Plus we can¶t pump up the framerate enough to get a
realistic speed. It just doesn¶t look believable. In the next article, I am going to show you how to
implement the Runge-Kutta methods, particularly the Fourth lrder Runge-Kutta method. I am
also going to try to explain the differences between implicit and explicit integration.

You might also like