Sunday, July 26, 2009

Simplified 2D Particle Systems In Ruby & SVG

Last year, I read Chapter 1 of Topher Cyll's Practical Ruby Projects and used it to build an improvising AI drum machine. The other day, I read Chapter 2.

Chapter 2 explains how to create animated graphics in Ruby, using ERB to generate SVG. A lot of the code in this chapter deals with animating text in isographic pseudo-3D cubes. That didn't interest me, so I cut to the chase with a much smaller code base just animating a circle moving across the screen.

Once this worked, I knew I could get started doing some more sophisticated stuff. Rather than re-use Topher's isometric text animations, I wanted to see if I could re-create a Flash animation I made around 2005-ish.

This animation came almost entirely from a tutorial by Keith Peters, aka bit101. It didn't take long to write some new code which recreated the Flash animation in its basic form. To be honest, however, I skipped a lot of the subtleties that make the Flash version interesting to watch.

SVG defines Photoshop-style filters, so I changed the code a little and re-rendered. Practical Ruby Projects starts you off with convert, the command-line tool for ImageMagick which includes the ability to render SVGs. However, ImageMagick's implementation of the SVG spec is incomplete, and to render filters, I had to switch to Apache Batik.

Practical Ruby Projects also points out that you can use convert to turn the rendered JPEGs into movie files. However, it recommends iMovie instead, because convert takes a long time. I rendered all these animations in Adobe After Effects, the professional standard for motion graphics and compositing, but this highlights a flaw in the whole project: struggling with SVG's quirky spec and a Java renderer just to put Gaussian blur on an image is pretty pointless when you can do so much more in After Effects with so much less effort.

For contrast, here's a version with no SVG effects, only effects added in After Effects.

I'm not sure how useful this code will be, but if you're interested, it's on GitHub. The bit101 tutorial is available on his site, but only as a Word doc, so I've reposted it in PDF format. If it's not obvious where the 2D particle animation comes in, I made the particles invisible and only drew the lines between them, just because I like the look of it better.

Related: in the past I've blogged about similar projects built with JRuby/Processing, Ruby plus OpenGL, and a custom OS X Scheme.