Mon
Apr 20th

Beautiful Algorithms 2: Tunnels

I spent weeks trying to reproduce dot tunnel effects on my Amiga back in the 90s.  Demo groups used to get thousands of points animated as complex 3D shapes and tunnels, but their techniques were way beyond me.  This tutorial introduces one such effect, and a few common techniques programmers use to improve performance.

For a video of the effect, check out my tunnel screencast.

This tutorial uses Ruby Processing.  See Fire Part 1 on how to get started.

Note: The code examples in this article might not appear in your feed reader.

Algorithm

The illusion of a 3D tunnel is creating by plotting rings.  For each frame of animation, each ring is scaled up.  The scaling rate of change increases as the rings get larger, giving the illusion of movement in 3D.

  1. Create a small ring
  2. Plot dots to display the ring
  3. Make it slightly larger
  4. If it’s large enough, add another ring
  5. If it’s too large, delete it

Modern Interpretation

Back in the 90s most people would have implemented this as a set of loops, iterating through preset positions for the dots.  Since these tutorials use Ruby, we can represent a ring using a class.

Of course, this isn’t terribly efficient, but it makes the algorithm much easier to follow.

The class will look something like this:

Then the main loop will look like this:

As you can see, this algorithm is essentially very simple.

Lookup Tables

Lookup tables are a major technique for performance improvements.  Even modern videogames use them in some form.  Before drawing is performed, common calculations can be stored and referred to later.

The tunnel algorithm relies on sin and cos for plotting a circle: this is pretty basic trigonometry.  Even though these operations are incredibly fast on a modern computer, calculating thousands of them per frame of animation is not trivial.  Looking up values in an array is much faster.

Part 2

In part 2 I’ll show you how to fill a lookup table with values and plot the tunnel.  If you want to ignore all that and run the example now, get it off my GitHub account: tunnel-p5r.

Comments (View)
Related Posts Widget for Blogs by LinkWithin