9ca1b19d10476ad8e1717fd38c519531a68008f9
[sdlgit/SDL-Site.git] / pages / SDL-Cookbook-PDL.html-inc
1 <div class="pod">
2 <!-- INDEX START -->
3 <h3 id="TOP">Index</h3>
4
5 <ul>
6 <li>
7 <ul><li><a href="#CATEGORY">CATEGORY</a></li>
8 </ul>
9 </li>
10 <li><a href="#Old_SDL_interface">Old SDL interface</a></li>
11 <li><a href="#Perl_s_SDL_in_a_nutshell">Perl's SDL in a nutshell</a></li>
12 <li><a href="#SDL_power_through_simplicity">SDL - power through simplicity</a></li>
13 <li><a href="#Example_1_Model_of_a_2_D_Noninteract">Example 1: Model of a 2-D Noninteracting Gas</a>
14 <ul><li><a href="#Computational_Logic">Computational Logic</a></li>
15 <li><a href="#Animation_Logic">Animation Logic</a></li>
16 <li><a href="#Disappearing_Particles_Some_of_the_p">Disappearing Particles!
17 Some of the particles can drift off the screen.  This is no good. What's causing this problem?</a></li>
18 <li><a href="#Disappearing_Particles_take_2">Disappearing Particles, take 2</a></li>
19 </ul>
20 </li>
21 <li><a href="#What_s_in_a_Name_Pesky_conflicts_wit">What's in a Name?  Pesky conflicts with main::in()</a>
22 <ul><li><a href="#Solution_1_Explicit_scoping_using_pa">Solution 1: Explicit scoping using packages</a></li>
23 <li><a href="#Solution_2_Removing_SDL_s_in_or_PDL_">Solution 2: Removing SDL's in or PDL's in from the symbol table</a></li>
24 </ul>
25 </li>
26 <li><a href="#Making_the_simulation_interactive">Making the simulation interactive</a>
27 <ul><li><a href="#Present_state_of_the_code">Present state of the code</a></li>
28 <li><a href="#Listening_to_Events">Listening to Events</a></li>
29 <li><a href="#Responding_to_events">Responding to events</a></li>
30 <li><a href="#Final_State_of_the_Code">Final State of the Code</a></li>
31 </ul>
32 </li>
33 <li><a href="#Directions_for_future_work">Directions for future work</a>
34 </li>
35 </ul><hr />
36 <!-- INDEX END -->
37
38 <p>PDL provides great number crunching capabilities to Perl and SDL provides game-developer quality real-time bitmapping and sound.  You can use PDL and SDL ''together'' to create real-time, responsive animations and simulations.  In this section we will go through the pleasures and pitfalls of working with both powerhouse libraries.</p>
39 <h2 id="CATEGORY">CATEGORY</h2>
40 <div id="CATEGORY_CONTENT">
41 <p>Cookbook</p>
42
43 </div>
44 <h1 id="Old_SDL_interface">Old SDL interface</h1><p><a href="#TOP" class="toplink">Top</a></p>
45 <div id="Old_SDL_interface_CONTENT">
46 <p>Please be aware that much of the code in this example uses SDL Perl v 2.2.4.  The SDL Perl developers are hard at work rewriting SDL, to be released as SDL 3.0 soon.  The new version of SDL is not backwards compatible.  Check back with this page after SDL 3.0 has been released to get the updated commands.</p>
47
48 </div>
49 <h1 id="Perl_s_SDL_in_a_nutshell">Perl's SDL in a nutshell</h1><p><a href="#TOP" class="toplink">Top</a></p>
50 <div id="Perl_s_SDL_in_a_nutshell_CONTENT">
51 <p>SDL stands for Simple DirectMedia Layer.  It's a cross-platform library written in C that's meant to handle all of the low-level graphics and sound stuff.  You can read more about SDL here: http://www.libsdl.org/.  Because SDL is focused on game programming, it has a raw but clean feel to it.  We will focus for now on using SDL to handle images for us.  Handling sound may some day be the focus of another chapter.</p>
52 <p>We will be using Perl's SDL module, not SDL directly.  Fortunately, Perl's SDL module has a small collection of very simple tutorials that perfectly introduce basic usage.  You can find them here: http://sdl.perl.org/tutorials/.  Another excellent and very substantial introduction can be found here: http://arstechnica.com/gaming/news/2006/02/games-perl.ars</p>
53 <p>SDL is not a Perl core module, so you'll need to install it before moving forward.  Before moving on, go through some of the tutorials and play around with SDL a little bit.  Continue on once you think you've got the hang of it.</p>
54
55 </div>
56 <h1 id="SDL_power_through_simplicity">SDL - power through simplicity</h1><p><a href="#TOP" class="toplink">Top</a></p>
57 <div id="SDL_power_through_simplicity_CONTENT">
58 <p>One of the first questions you're bound to ask when you begin using SDL for your own work is, &quot;How do I draw a line?&quot;  As it turns out, you don't!  SDL's pixmap capabilities are just that - pixmap capabilities.  If you want to draw a line, you'll have to do it manually.</p>
59 <p>For example, here is a very poorly implemented hack (read - don't do this at home) that will draw a simple sine-wave graph:</p>
60 <pre>   #!/usr/bin/perl
61         use warnings;
62         use strict;
63
64         use SDL;
65         use SDL::App;
66         use SDL::Rect;
67         use SDL::Color;
68
69         # User defined pen-nib size.
70         my $nib_size = 3;
71
72         # Create the SDL App
73         my $app = SDL::App-&gt;new(
74                 -width  =&gt; 640,
75                 -height =&gt; 480,
76                 -depth  =&gt; 16,
77                 -title  =&gt; &quot;Hello, World!&quot;,
78         );
79
80         # our nib will be white
81         my $nib_color = SDL::Color-&gt;new(
82                         -r =&gt; 0xff,
83                         -g =&gt; 0xff,
84                         -b =&gt; 0xff,
85                 );
86
87         # and our nib will be represented by a rectangle
88         # (Alternatively, you could use an image, which would allow
89         # for pretty anti-aliasing if you created it in GIMP with
90         # antialiasing)
91         my $nib = SDL::Rect-&gt;new(
92                 -height =&gt; $nib_size,
93                 -width  =&gt; $nib_size,
94         );
95
96         # now draw a sine wave (wthout covering up previously drawn rectangles)
97         my $t = 0;
98         my $t_step = 2**-4;
99         for($t = 0; $t &lt; 50; $t += $t_step) {
100                 $nib-&gt;x( $t * 8 );
101                 $nib-&gt;y( sin($t) * 80 + 240 );
102
103                 $app-&gt;fill( $nib, $nib_color );
104         }
105
106         # Generally use the update command, but if you want to update the whole
107         # surface, use flip
108         $app-&gt;flip()
109
110         sleep 5;
111
112 </pre>
113 <p>Wait a second, you say, this doesn't seem either powerful or simple!  You're right, but that's not because SDL is a poor tool.  Rather, this example targets SDL's weaknesses rather than its strenghts.</p>
114 <p>If you need to make a plot, use PLplot or PGPLOT.  If you need to make something move, use SDL.</p>
115
116 </div>
117 <h1 id="Example_1_Model_of_a_2_D_Noninteract">Example 1: Model of a 2-D Noninteracting Gas</h1><p><a href="#TOP" class="toplink">Top</a></p>
118 <div id="Example_1_Model_of_a_2_D_Noninteract-2">
119 <p>In this section we'll develop a fully working animation/simulation.  We'll start with something quite simple for now and expand it as we go along.  The goal of this example is for it to work, not to be well-designed.  For a discussion of making your simulations well-designed, read below.</p>
120 <p>We will separate our program into two parts: the computational logic and the animation logic.  Here's the introduction and the computational part:</p>
121
122 </div>
123 <h2 id="Computational_Logic">Computational Logic</h2>
124 <div id="Computational_Logic_CONTENT">
125 <pre>
126
127
128         #!/usr/bin/perl
129         # A simple simulation
130         use warnings;
131         use strict;
132         use PDL;
133
134         # Set up the system parameters, including random positions and velocities.
135         my $d_t = 2**-3;
136         my $side_length = 200;
137         my $numb_of_atoms = 100;
138         my $positions = random(2, $numb_of_atoms) * $side_length;
139         my $velocities = random(2, $numb_of_atoms) * 6;
140
141         sub compute {
142                 $positions += $d_t * $velocities;
143         }
144
145 </pre>
146 <p>If you've ever written a simulation, you'll probably object that we don't have any iteration over time.  You're right, but it turns out that the timing works much better in SDL's event loop than in our computational logic.  The purpose of the computational logic is to let us focus on encoding our systems dynamics without having to worry about the application logic.  In this case, the computational logic simply updates the positions of the particles according to their velocities.</p>
147
148 </div>
149 <h2 id="Animation_Logic">Animation Logic</h2>
150 <div id="Animation_Logic_CONTENT">
151 <p>We next need to figure out how the application is actually going to run and display anything.  We'll do this in two stages, the application intialization and the run loop.</p>
152 <p>Here's some initialization code to get started; put this below the code already supplied above:</p>
153 <pre>   use SDL;
154         use SDL::App;
155         use SDL::Rect;
156         use SDL::Color;
157
158         # Create the SDL App
159         my $app = SDL::App-&gt;new( -width  =&gt; $side_length, -height =&gt; $side_length, 
160                                         -title  =&gt; &quot;Simple Simulation!&quot;, -depth  =&gt; 16, );
161
162         # white particles on a black background
163         my $particle_color = SDL::Color-&gt;new( -r =&gt; 0xff, -g =&gt; 0xff, -b =&gt; 0xff, );
164         my $bg_color = SDL::Color-&gt;new( -r =&gt; 0x00, -g =&gt; 0x00, -b =&gt; 0x00, );
165
166         # rectangles for the particles and the background
167         my $particle = SDL::Rect-&gt;new( -height =&gt; 5, -width  =&gt; 5, );
168         my $bg = SDL::Rect-&gt;new( -height =&gt; $side_length, -width =&gt; $side_length, );
169
170 </pre>
171 <p>Hopefully this is straightforward code.  We pull in our library dependencies and then create a few objects with the necessary properties.  Finally, we get to the actual application loop:</p>
172 <pre>   # Run the simulation by (1) computing the updated positions, clearing the canvas, drawing the
173         # new particles, updating the visual display, and pausing before continuing:
174         for(my $t = 0; $t &lt; 20; $t += $d_t) {
175                 compute();
176
177                 # Clean the canvas
178                 $app-&gt;fill( $bg, $bg_color);
179                 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
180                         $particle-&gt;x( $positions-&gt;at(0,$i) );
181                         $particle-&gt;y( $positions-&gt;at(1,$i) );
182                         $app-&gt;fill( $particle, $particle_color );
183                 }
184                 $app-&gt;flip();
185                 $app-&gt;delay(10);
186         }
187
188 </pre>
189 <p>When you run this code (combined with the code already supplied), you should get a bunch of particles slowly drifting down and to the right.  Not all that interesting, but then again, we have a simulation up and working!  Cool!.</p>
190
191 </div>
192 <h2 id="Disappearing_Particles_Some_of_the_p">Disappearing Particles!
193 Some of the particles can drift off the screen.  This is no good. What's causing this problem?</h2>
194 <div id="Disappearing_Particles_Some_of_the_p-2">
195 <p>The root of the problem is that our computational code is, well, rather dumb, it doesn't check to see if the particle is about to go off the screen.  So, we need to update our computational code to look like this:</p>
196 <pre>   sub compute {
197                 $positions += $d_t * $velocities;
198
199                 # Find all particles that are 'outside' the box, place them back in
200                 # box, and reverse their directions
201                 my ($bad_pos, $bad_vel)
202                         = where($positions, $velocities, $positions &gt; $side_length);
203                 $bad_vel *= -1;
204                 $bad_pos .= 2 * $side_length - $bad_pos;
205         }
206
207 </pre>
208 <p>With this change to the code, you should get particles that 'bounce' when the reach the far edge.  This is far from satisfactory, however, because the compute code is adjusting the particle's ''left'' edge, not its center, so the particles nearly go off the screen before they bounce.  To fix this, we work with an effective side length instead:</p>
209 <pre>   my $effective_length = $side_length - 5;
210         sub compute {
211                 $positions += $d_t * $velocities;
212
213                 # Find all particles that are 'outside' the box and push them back in the
214                 # opposite direction, reversing their directions, too.
215                 my ($bad_pos, $bad_vel)
216                         = where($positions, $velocities, $positions &gt; $effective_length);
217                 $bad_vel *= -1;
218                 $bad_pos .= 2 * $effective_length - $bad_pos;
219         }
220
221 </pre>
222 <p>So far I've been carrying that explicit constant of 5 to represent the size of the particles.  We should put that in a variable somewhere so that it's a bitcode&gt; and put it near the top.  Also, the velocities are rather silly - we don't have any negative velocities.  Let's try using &lt;code&gt;grandom&lt;/code&gt; instead.  Now your variable initialization code should look something like this:</p>
223 <pre>   # Set up the system parameters, including random positions and velocities.
224         my $d_t = 2**-3;
225         my $side_length = 200;
226         my $particle_size = 5;
227         my $numb_of_atoms = 100;
228         my $positions = random(2, $numb_of_atoms) * $side_length;
229         my $velocities = grandom(2, $numb_of_atoms) * 5;
230
231 </pre>
232
233 </div>
234 <h2 id="Disappearing_Particles_take_2">Disappearing Particles, take 2</h2>
235 <div id="Disappearing_Particles_take_2_CONTEN">
236 <p>Unless you experience an unusual circumstance, all of the particles will quickly shrivel up and disappear!  What's going on?  It turns out we have a problem with our computational logic again, but we are also running into strange behavior from SDL.  We'll take a look at SDL's weird behavior first.</p>
237 <p>Clearly the particle rectangle's size is not supposed to change, but somehow it does.  To confince yourself of this, modify the &lt;code&gt;for&lt;/code&gt; loop in the application loop so it looks more like this, which explicitly sets the particle size for every particle that's drawn:</p>
238 <pre>   for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
239                 $particle-&gt;x( $positions-&gt;at(0,$i) );
240                 $particle-&gt;y( $positions-&gt;at(1,$i) );
241                 $particle-&gt;height( $particle_size );
242                 $particle-&gt;width( $particle_size );
243                 $app-&gt;fill( $particle, $particle_color );
244         }
245
246 </pre>
247 <p>Now it's clear that although we still have particles flying off the screen up and to the left, they are no longer shriveling away.  This strange behavior is due to SDL's response to a negative position for a rectangle - it just resizes the rectangle so that it only the portion of the rectangle that's in positive territory remains.  The upshot is that you must always be careful about how you handle drawing positons.</p>
248 <p>Now that the particles are no longer disappearing, it's clear that we forgot to set up a physical boundary condition for our particles on the uppper and left edges.  To fix that, we modify the compute function:</p>
249 <pre>   sub compute {
250                 $positions += $d_t * $velocities;
251
252                 # Find all particles that are 'outside' the box and push them back in the
253                 # opposite direction, reversing their directions, too.
254                 my ($bad_pos, $bad_vel)
255                         = where($positions, $velocities, $positions &gt; $effective_length);
256                 $bad_vel *= -1;
257                 $bad_pos .= 2 * $effective_length - $bad_pos;
258
259                 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions &lt; 0);
260                 $bad_vel *= -1;
261                 $bad_pos *= -1;
262         }
263
264 </pre>
265 <p>You can also remove the explicit particle-sizing that we put in before, because it's no longer a problem.</p>
266 <p>And there you have it!  We have a fully fledged simulation of noninteracting particles in a box!</p>
267
268 </div>
269 <h1 id="What_s_in_a_Name_Pesky_conflicts_wit">What's in a Name?  Pesky conflicts with main::in()</h1><p><a href="#TOP" class="toplink">Top</a></p>
270 <div id="What_s_in_a_Name_Pesky_conflicts_wit-2">
271 <p>If you've been running your simulations along with the demo, you'll almost certainly have noticed an error looking something like this:</p>
272 <pre> Prototype mismatch: sub main::in (;@) vs none at ./sdlsandbox.pl line 36
273
274 </pre>
275 <p>This is the unfortunate consequence of both SDL and PDL exporting their &lt;code&gt;in&lt;/code&gt; function to their enclosing namespace.  The standard solution to this is to have modify one of your &lt;code&gt;use&lt;/code&gt; lines so it looks like </p>
276 <pre>    use PDL qw( !in );
277
278 </pre>
279 <p>Unfortunately, PDL doesn't listen you what you say when it imports functions into the namespace.  As far as I can tell, neither does SDL.  The best way to fix this problem is to encapsulate one of the two pieces of code into its own package.  We'll do that with the MyComputation package.</p>
280
281 </div>
282 <h2 id="Solution_1_Explicit_scoping_using_pa">Solution 1: Explicit scoping using packages</h2>
283 <div id="Solution_1_Explicit_scoping_using_pa-2">
284 <p>Tweak your code a bit so that you call <code>use PDL;</code> within the MyCompute package, and place all of the piddles within that package space:</p>
285 <pre>   package MyCompute;
286         use PDL;
287         my $positions = random(2, $numb_of_atoms) * $side_length;
288
289         # ... and later
290         package main;
291         use SDL;
292
293         # ... and later, tweak the application loop
294         for(my $t = 0; $t &lt; 20; $t += $d_t) {
295                 MyCompute::compute();
296
297 </pre>
298 <p>And now everything should run fine, without any more warnings!</p>
299
300 </div>
301 <h2 id="Solution_2_Removing_SDL_s_in_or_PDL_">Solution 2: Removing SDL's in or PDL's in from the symbol table</h2>
302 <div id="Solution_2_Removing_SDL_s_in_or_PDL_-2">
303 <p>Sometimes you have to mix your animation code with computational code, in which case the above solution doesn't solve your problem.  If you find that you don't need to use one of PDL's or SDL's &lt;code&gt;in&lt;/code&gt; function in your own code, go ahead and remove it from the main symbol table.  You can always get back to it later by fully qualifying the function call.  To remove SDL's &lt;code&gt;in&lt;/code&gt; function, use code like this:</p>
304 <pre>   # use SDL, but remove SDL's in function before loading PDL
305         use SDL;
306         BEGIN {
307                 delete $main::{in};
308         }
309         use PDL;
310
311 </pre>
312 <p>If you would rather have SDL's <code>in</code> function in your main symbol table, reverse the placement of &lt;code&gt;use SD<a href="#code">code</a> and &lt;code&gt;use PD<a href="#code">code</a> in the previous example:</p>
313 <pre>   # use PDL, but remove its 'in' function before loading SDL
314         use PDL;
315         BEGIN {
316                 delete $main::{in};
317         }
318         use SDL;
319
320 </pre>
321
322 </div>
323 <h1 id="Making_the_simulation_interactive">Making the simulation interactive</h1><p><a href="#TOP" class="toplink">Top</a></p>
324 <div id="Making_the_simulation_interactive_CO">
325 <p>As the closing portion of this chapter, we'll consider how to make the simulation interactive.  SDL captures keyboard and mouse behavior, so putting this into our simulator is straightforward.</p>
326
327 </div>
328 <h2 id="Present_state_of_the_code">Present state of the code</h2>
329 <div id="Present_state_of_the_code_CONTENT">
330 <p>Before moving into getting user interaction, I first want to be sure we're working with the same code.  In particular, I've made a couple of important modifications so that this code is slightly different from what we were working with above.  I'll point out those differences as we come to them.  Here's the program as it stands, from top to bottom:</p>
331 <pre>   #!/usr/bin/perl
332         # A simple simulation
333         use warnings;
334         use strict;
335
336         ## Global Variables ##
337
338         # Set up the system parameters, including random positions and velocities.
339         my $d_t = 2**-3;
340         my $side_length = 200;
341         my $particle_size = 5;
342         my $numb_of_atoms = 100;
343
344         ## Computational Stuff ##
345
346         package MyCompute;
347         use PDL;
348         my $positions = random(2, $numb_of_atoms) * $side_length;
349         my $velocities = grandom(2, $numb_of_atoms) * 6;
350         my $effective_length;
351
352         sub compute {
353                 my $effective_length = $side_length - $particle_size;
354
355                 # update the a real simulation, this is the interesting part
356                 $positions += $d_t * $velocities;
357
358                 # Check boundary conditions.  Find all particles that are 'outside' the box,
359                 # place them back in the box, and reverse their directions
360                 my ($bad_pos, $bad_vel)
361                         = where($positions, $velocities, $positions &gt; $effective_length);
362                 $bad_vel *= -1;
363                 $bad_pos .= 2 * $effective_length - $bad_pos;
364
365                 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions &lt; 0);
366                 $bad_vel *= -1;
367                 $bad_pos *= -1;
368         }
369
370
371
372
373         ## Animation Code ##
374
375         package main;
376
377         use SDL;
378         use SDL::App;
379         use SDL::Rect;
380         use SDL::Color;
381
382         # Create the SDL App
383         my $app = SDL::App-&gt;new( -width  =&gt; $side_length, -height =&gt; $side_length, 
384                                 -title  =&gt; &quot;Simple Simulation!&quot;, -depth  =&gt; 16, );
385
386         # white particles on a black background
387         my $particle_color = SDL::Color-&gt;new( -r =&gt; 0xff, -g =&gt; 0xff, -b =&gt; 0xff, );
388         my $bg_color = SDL::Color-&gt;new( -r =&gt; 0x00, -g =&gt; 0x00, -b =&gt; 0x00, );
389
390         # rectangles for the particles and the background
391         my $particle = SDL::Rect-&gt;new( -height =&gt; 5, -width  =&gt; 5, );
392         my $bg = SDL::Rect-&gt;new( -height =&gt; $side_length, -width =&gt; $side_length, );
393
394         # Run the simulation
395         for(my $t = 0; $t &lt; 20; $t += $d_t) {
396                 MyCompute::compute();
397
398                 # Clean the canvas
399                 $app-&gt;fill( $bg, $bg_color);
400                 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
401                         $particle-&gt;x( $positions-&gt;at(0,$i) );
402                         $particle-&gt;y( $positions-&gt;at(1,$i) );
403                         $app-&gt;fill( $particle, $particle_color );
404                 }
405                 $app-&gt;flip();
406                 $app-&gt;delay(10);
407         }
408
409 </pre>
410 <p>So there it is, top to bottom, in about 75 lines.</p>
411
412 </div>
413 <h2 id="Listening_to_Events">Listening to Events</h2>
414 <div id="Listening_to_Events_CONTENT">
415 <p>To respond to user interactions, we have to listen to user events using an SDL::Event object.  So first, add this line with our other use statements:</p>
416 <pre> use SDL::Event;
417
418 </pre>
419 <p>and then be sure to create an event object amongst the animation initialization code:</p>
420 <pre> my $event = new SDL::Event;
421
422 </pre>
423 <p>Finally, we need to update the application loop so that it examines and responds to events.  Replace the current application loop with this code:</p>
424 <pre>   # Run the simulation
425         while(1) {
426                 MyCompute::compute();
427
428                 # Clean the canvas
429                 $app-&gt;fill( $bg, $bg_color);
430                 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
431                         $particle-&gt;x( $positions-&gt;at(0,$i) );
432                         $particle-&gt;y( $positions-&gt;at(1,$i) );
433                         $app-&gt;fill( $particle, $particle_col10);
434
435                 while($event-&gt;poll()) {
436                         if($event-&gt;type() =head1  SDL_QUIT) {
437                                 exit;
438                         }
439                 }
440         }
441
442 </pre>
443 <p>Now the animator will run indefinitely, until you explicitly tell it to close.  (You may have noticed before that the application would not close even if you told it to close.  Now we've fixed that.)</p>
444
445 </div>
446 <h2 id="Responding_to_events">Responding to events</h2>
447 <div id="Responding_to_events_CONTENT">
448 <p>When SDL gets a mouse response or a keyboard key press, it tells you with an event.  The naive way to process these event is with a series of if statements.  Don't do that.</p>
449 <p>Instead, create a dispatch table, which is nothing more than a hash whose values are the subroutines you want to have run when an event happens.  Replace the application loop with the following code:</p>
450 <pre>   # event dispatch table
451         my $keyname_dispatch_table = {
452                 'up'    =&gt; \&amp;incr_particle_size, # up key makes particles larger
453                 'down'  =&gt; \&amp;decr_particle_size, # down key makes particles smaller
454                 'space' =&gt; sub { $d_t = -$d_t        },      # space-bar reverses time
455                 '.'     =&gt; sub { $d_t *= 1.1 },      # right-angle-bracket fast-forwards
456                 ','     =&gt; sub { $d_t /= 1.1 },      # left-angle-bracket slows down
457                 'q'     =&gt; sub { exit;               },      # q exits
458         };
459
460         sub incr_particle_size {
461                 $particle_size++;
462                 $particle-&gt;height($particle_size);
463                 $particle-&gt;width($particle_size);
464         }
465
466         sub decr_particle_size {
467                 $particle_size-- if $particle_size &gt; 1;
468                 $particle-&gt;height($particle_size);
469                 $particle-&gt;width($particle_size);
470         }
471
472
473
474
475         # Run the simulation
476         while(1) {
477                 MyCompute::compute();
478
479                 # Clean the canvas
480                 $app-&gt;fill( $bg, $bg_color);
481                 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
482                         $particle-&gt;x( $positions-&gt;at(0,$i) );
483                         $particle-&gt;y( $positions-&gt;at(1,$i) );
484                         $app-&gt;fill( $particle, $particle_color );
485                 }
486                 $app-&gt;flip();
487                 $app-&gt;delay(10);
488
489                 while($event-&gt;poll()) {
490                         if($event-&gt;type() =head1  SDL_QUIT) {
491                                 exit;
492                         } elsif($event-&gt;type() =head1  SDL_KEYDOWN) {
493                                 if(exists $keyname_dispatch_table-&gt;{$event-&gt;key_name()}) {
494                                         $keyname_dispatch_table-&gt;{$event-&gt;key_name()}-&gt;();
495                                 }
496                         }
497                 }
498         }
499
500 </pre>
501 <p>Dispatch tables allow for powerful methods of abstracting your program logic.  Now adding a new event handler is as easy as updating the dispatch table!</p>
502 <p>As written, you can now increase or decrease the particle size using the up and down arrow keys, you can increase ory using the right or left angle-brackets, you can reverse time using the space bar, or you can quit by pressing q.</p>
503
504 </div>
505 <h2 id="Final_State_of_the_Code">Final State of the Code</h2>
506 <div id="Final_State_of_the_Code_CONTENT">
507 <p>Just so that you've got a complete working example, here is the final state of the code, clocking in at a mere 115 lines:</p>
508 <pre>   #!/usr/bin/perl
509         # A simple simulation
510         use warnings;
511         use strict;
512
513         ## Global Variables ##
514
515         # Set up the system parameters, including random positions and velocities.
516         my $d_t = 2**-3;
517         my $side_length = 200;
518         my $particle_size = 5;
519         my $numb_of_atoms = 100;
520
521         ## Computational Stuff ##
522
523         package MyCompute;
524         use PDL;
525         my $positions = random(2, $numb_of_atoms) * $side_length;
526         my $velocities = grandom(2, $numb_of_atoms) * 6;
527         my $effective_length;
528
529         sub compute {
530                 my $effective_length = $side_length - $particle_size;
531
532                 # update the positions.  For a real simulation, this is the interesting part
533                 $positions += $d_t * $velocities;
534
535                 # Check boundary conditions.  Find all particles that are 'outside' the box,
536                 # place them back in the box, and reverse their directions
537                 my ($bad_pos, $bad_vel)
538                         = where($positions, $velocities, $positions &gt; $effective_length);
539                 $bad_vel *= -1;
540                 $bad_pos .= 2 * $effective_length - $bad_pos;
541
542                 ($bad_pos, $bad_vel) = where($positions, $velocities, $positions &lt; 0);
543                 $bad_vel *= -1;
544                 $bad_pos *= -1;
545         }
546
547
548
549
550         ## Animation Code ##
551
552         package main;
553
554         use SDL;
555         use SDL::App;
556         use SDL::Rect;
557         use SDL::Color;
558         use SDL::Event;
559
560         # Create the SDL App
561         my $app = SDL::App-&gt;new( -width  =&gt; $side_length, -height =&gt; $side_length, 
562                                 -title  =&gt; &quot;Simple Simulation!&quot;, -depth  =&gt; 16, );
563
564         # white particles on a black background
565         my $particle_color = SDL::Color-&gt;new( -r =&gt; 0xff, -g =&gt; 0xff, -b =&gt; 0xff, );
566         my $bg_color = SDL::Color-&gt;new( -r =&gt; 0x00, -g =&gt; 0x00, -b =&gt; 0x00, );
567
568         # rectangles for the particles and the background
569         my $particle = SDL::Rect-&gt;new( -height =&gt; 5, -width  =&gt; 5, );
570         my $bg = SDL::Rect-&gt;new( -height =&gt; $side_length, -width =&gt; $side_length, );
571
572         # event listener
573         my $event = new SDL::Event;
574
575         # event dispatch table
576         my $keyname_dispatch_table = {
577                 'up'    =&gt; \&amp;incr_particle_size, # up key makes particles large
578                 'down'  =&gt; \&amp;decr_particle_size, # up key makes particles large
579                 'space' =&gt; sub { $d_t = -$d_t        },      
580                 '.'     =&gt; sub { $d_t *= 1.1 },      # right-arrow fast-forwards
581                 ','     =&gt; sub { $d_t /= 1.1 },      # left-arrow slows down
582                 'q'     =&gt; sub { exit;               },      # q exits
583         };
584
585         sub incr_particle_size {
586                 $particle_size++;
587                 $particle-&gt;height($particle_size);
588                 $particle-&gt;width($particle_size);
589         }
590
591         sub decr_particle_size {
592                 $particle_size-- if $particle_size &gt; 1;
593                 $particle-&gt;height($particle_size);
594                 $particle-&gt;width($particle_size);
595         }
596
597
598
599
600         # Run the simulation
601         while(1) {
602                 MyCompute::compute();
603
604                 # Clean the canvas
605                 $app-&gt;fill( $bg, $bg_color);
606                 for(my $i = 0; $i &lt; $numb_of_atoms; $i++) {
607                         $particle-&gt;x( $positions-&gt;at(0,$i) );
608                         $particle-&gt;y( $positions-&gt;at(1,$i) );
609                         $app-&gt;fill( $particle, $particle_color );
610                 }
611                 $app-&gt;flip();
612                 $app-&gt;delay(10);
613
614                 while($event-&gt;poll()) {
615                         if($event-&gt;type() =head1  SDL_QUIT) {
616                                 exit;
617                         } elsif($event-&gt;type() =head1  SDL_KEYDOWN) {
618                                 if(exists $keyname_dispatch_table-&gt;{$event-&gt;key_name()}) {
619                                         $keyname_dispatch_table-&gt;{$event-&gt;key_name()}-&gt;();
620                                 }
621                         }
622                 }
623         }
624
625 </pre>
626 <p>Next, if you want to model interactions among particles, you could write code in the compute function to handle that for you.  If you wanted to use little balls instead of the boxes we've used here, you could create your own images and use an SDL::Surface to load the image.  You can't resize an image using SDL, but then you'd probably be working with real interactions anyway, like a Coulomb force, in which case you'd really be adjusting the interaction strength, not the particle size.</p>
627
628 </div>
629 <h1 id="Directions_for_future_work">Directions for future work</h1><p><a href="#TOP" class="toplink">Top</a></p>
630 <div id="Directions_for_future_work_CONTENT">
631 <p>I have a couple of ideas for future work combining PDL and SDL.</p>
632 <dl>
633         <dt>PLplot driver thingy that creates plots that can be blitted onto an app.  This way, having a graph plotting along side your simulation would be straightforward.
634 =item  Write a function to convert SDL::Surface to a collection of rgba piddles.  We might even be able to convince the piddle to work directly with the memory allocated for the SDL::Survace object for super-fast PDL-based image manipulations.  As an added bonus, you'd be able to slice and dice!</dt>
635 </dl>
636
637 </div>
638 </div>