TweetFollow Us on Twitter

From Algorithm to Animation: the Sequel

Volume Number: 19 (2003)
Issue Number: 7
Column Tag: QuickTime

From Algorithm to Animation: the Sequel

Making QuickTime movies which illustrate abstract processes

by Jay Martin Anderson

THE ORIGINAL

In the November 1993 issue of MacTech (volume 9, number 11), I described how I made a QuickTime movie of an algorithm from computational mathematics. In the intervening ten years, QuickTime has grown and matured, the Mac OS has crossed the divide between Classic and OS X, and several generations of IDEs have come and gone.

My interest in making QuickTime movies to illustrate algorithms from computer science and mathematics has not. Consequently, I wish to present an update of the technique used to make animations of algorithms, and apply it to a theorem from beginning calculus which my colleagues challenged me to illustrate this year.

THE PROBLEM

The Department of Mathematics at Franklin and Marshall College includes both mathematics and computer science and frequently enjoys sharing problems in one area with the other. In the spring of 2003, my mathematician colleagues challenged me to construct a way to depict the Mean Value Theorem (MVT) which states that, for a suitably "nice" function f(x) on a range a <= x <= b, somewhere (some x = c, a <= c <= b) the slope of the function, f'(c) is equal to the "rise over run" of the function, (f(b)-f(a))/(b-a).

I chose to take a particular function f(x) = x3 on the range -1 <= x <= 1, trace along the function showing a line tangent to the curve at each point, and stop when the tangent line had the same slope as the "rise over run," which is 1.

THE PARADIGM

At F&M we have developed a paradigm for constructing algorithm animations. We divide the moviemaking application into three parts: the model, the view, and the controller.

The model contains the algorithm to be visualized. In this example, it is the function and its derivative. The state of the model is the value of x, along with the value of f(x) and f'(x).

The view contains the graphical elements necessary to illustrate the model. It is in the view that a single picture of a single state of the model is developed. In our work beginning in 2003, the view is developed with OpenGL. In the view we will draw the graph of the function, the tangent line at every value of x, the line which represents the "rise over run," and any tangent line with the same slope as "rise over run."

The controller does all the initialization and cleanup necessary for the moviemaking application. In particular, it does all the work necessary to pass individual views to QuickTime for the formation of a movie. Most importantly, the controller contains the timing, which signals the model to change its state and the view to generate a new picture. The controller will continue to ask the model to change its state until the value of x has spanned the entire range of interest.

Many movies are divided into "acts" and "scenes," much like a real theater piece. This provides a simple way to modularize the model and the view, and is particularly useful if the animated view of the model is more complex than simply moving an object along a path. For this simple example, acts and scenes are not necessary.

Our movies are also annotated. A view of a state of the model is also accompanied by a few sentences of text which explain what the view shows. The resulting QuickTime movie has one video track, and one text track for each (natural) language necessary. The natural language feature of QuickTime makes it particularly easy to construct movies in English, German, Italian, etc. The text annotation in this movie gives numerical values for x and f'(x).

Beginning in 2003, our development platform for algorithm animation is Apple's Developer Tools, including Project Builder and Interface Builder. The application is developed in Objective-C, using Cocoa classes. The model is a subclass of NSObject; the view is a subclass of NSOpenGLView; and the controller is also a subclass of NSObject. Since the movie, and not the application which creates it, is the object of this exercise, the graphical user interface is kept as simple as possible, often including only a button "Make Movie" and perhaps some widgets to select among choices for the movie.

The connection between the strictly object-oriented Objective-C and Cocoa classes, and the older QuickTime API is not always elegant. Nonetheless, it is that connection which is perhaps the most significant contribution of this article. Almost every time the controller has to move information between the model or the view and QuickTime, some conversion is necessary.

Using Interface Builder

We begin with Project Builder and construct a new project, a Cocoa application. Interface Builder allows us easily to construct a window and view of appropriate size, place whatever GUI widgets we need in the window, construct the model and controller objects, and generate some source code for the model-view-controller system.

Launch Interface Builder by double-clicking the MainMenu.nib icon, which is found inside the Resources folder of the Files pane of the project. Make the window an appropriate size, and drag a Custom View onto the window. Make the Custom View be an appropriate size as well. Create a subclass of NSOpenGLView, such as MyOpenGLView, and make the Custom View be an instance of MyOpenGLView.

Drop whatever widgets you need into the window. In this example, we use only a button, labeled Make Movie.

Create a subclass of NSObject called MyController and a subclass of NSObject called MyModel. Within MyController, create an Action method, for example, createMovie. Also within MyController, create Outlets, which are instances of the classes MyModel and MyOpenGLView, respectively. Likewise, in the class MyOpenGLView, create an Outlet, which is an instance of the class MyModel.

Make instances of these classes, and generate code for these classes.

Build connections as follows: from any widgets, such as the Make Movie button to the instance of MyController, with the target of the createMovie method; from the instance of MyController to the instance of MyModel; from the instance of MyController to MyOpenGLView; and finally from the instance of MyOpenGLView to the instance of MyModel. The connection from the button to the method means that the button sends the createMovie message to the controller. The connection from the controller to the model means that the controller can send messages (usually inquiries) to the model, and likewise to the view. The connection from the view to the model means that the view can send messages (again, usually inquiries) to the model.


Figure 1. Using Interface Builder. The window contains the view, a subclass of NSOpenGLView, and one button. The view is connected to the class MyModel, so that the view may inquire the state of the model.

This completes the work with interface builder; save the nib and continue with Project Builder.

The Code

The work of managing QuickTime is done with the createMovie method of the controller object. This also includes code to provide an interface, albeit awkward, between the Objective-C classes of Cocoa and the "legacy" code of QuickTime. Three points bear special mention.

First, OpenGL draws into a context, which is described by a pixel format. QuickTime accepts images from a pixMap, which is part of the GWorld data structure. The function CopyNSBitmapImageRepToGWorld accomplishes the task of copying pixels from the first to the second environment. It is based on the assumption of 32-bit pixels in each structure. Curiously, the copying of pixels requires an NSBitmapImageRep, which is four bytes wider than the context.

Second, QuickTime constructs a movie file using an FSSpec. The FSSpec must be derived from a path or file name in the "classic" Macintosh format, and it must appear as a Pascal string. The function QTUtils_ConvertCToPascalString serves to convert a C-string to a Pascal string.

Finally, the image drawn by OpenGL is inverted when it is copied to QuickTime. Given that the QuickTime movie is the object of this exercise, it seems simplest to construct the OpenGL drawings upside-down, and let the pixel copying to QuickTime invert them to the proper orientation.

The code for the class MyController, as well as for portions of the classes MyModel and MyOpenGLView, along with all header files, can be found on the website

http://eDisk.fandm.edu/~jay.anderson/mactech/example.html

The model is the simplest unit in this example. The methods f and ff serve to calculate the function and its derivative. The method changeState advances a point along the curve by equal increments in the x-direction, and computes the corresponding value of the function and its derivative. The method changeState also looks for matches between the slope of the curve and the "rise over run," and records the matches.

Listing 1: MyModel.m

MyModel

A portion of the class MyModel, which encapsulates the algorithm to be illustrated and its data 
structures.  Shown here are the method changeState, and the methods that evaluate the function and 
its derivative.  The remainder of the class, and the header file MyModel.h are found on the website.

@implementation MyModel
- (void)changeState:(int)frNo
{
   if (frNo == 0)
   {
      // beginning frame is blank, with only an annotation
      strcpy(annotation, "MEAN VALUE THEOREM.  Compare
 rise/run to slope of graph.");
   }
   else
   {
      // as frame number goes from 0 to 200, x goes from -1.0 to 1.0 in 200 steps
      x = -1.0 + frNo/100.0;
      y = [self f:x];
      slope = [self ff:x];
      sprintf(annotation, "x = %5.2f, y = %5.2f, slope =
 %5.2f", x, y, slope);
      if (fabs(slope - ror) < 0.01) 
      {
         // slope matches rise/run; record this position, append extra annotation
         match = 1;
         xMatch[nMatches++] = x;
         strcat(annotation, "\rSlope matches rise/run: mean
 value theorem!");  
      }
      else                          
         match = 0;
   }
}
- (float)f:(float)z
{ return z*z*z; }
- (float)ff:(float)z
{ return 3*z*z; }
@end

The view is responsible for drawing the curve, the "rise over run" line, a point and tangent line which moves along the curve as the state of the model changes, and any matches between the slope of the curve and the rise-over-run line. These are simple OpenGL primitives: point, line and line-strip. Colors, the point size and the line width are chosen for viewing ease.

Listing 2: MyOpenGLView.m

MyOpenGLView

The method drawRect from the class MyOpenGLView; the remainder of the class and the header file 
MyOpenGLView.h are found on the website.  This method is invoked when the display message is sent 
to the view.  It draws each frame of the movie.  

@implementation MyOpenGLView
- (void)drawRect:(NSRect)rect
{
   float x, y, slope;
   short match;
    
   glClear(GL_COLOR_BUFFER_BIT);   // clear the screen
   x = model->x;
   y = model->y;
   slope = model->slope;
   match = model->match;
   
   /* Draw the components of the frame:  the graph of the function, the rise/run line,
      the point at (x, y), and the slope of the graph at that point.
   */
   [self drawGraph];                  
   [self drawRR];
   [self drawPoint:x:y];
   [self drawSlope:x:y:slope];
 
   /* Draw a tangent line at each place where the slope of the function matches the
      rise/run line.
   */   
   if (model->nMatches > 0)
   {
      int i;
      for (i = 0; i < model->nMatches; i++)
         [self drawMatch:i];
   }
   // show it!
   glFlush();
}
@end

The text annotations are developed within the model, and left in a string. In the controller, this string is copied to the text handler, just as the image is copied to an image compressor. Color, font, and size of text can be chosen when the text handler is constructed.

Lights! CAMERA!  ACTION!

The controller runs a simple loop to construct successive frames of the movie. In particular, the controller sends the changeState message to the model, and then the display message to the view. This image is then copied to QuickTime and compressed. In addition, the controller sends a getText message to the model to acquire the annotation to be placed into the text track.

Results

The model-view-controller paradigm has been implemented for making QuickTime movies that illustrate algorithms in Java and in Cocoa/Objective-C. The Cocoa/Objective-C implementation allows the use of OpenGL with QuickTime in a workable, if awkward, marriage of Objective-C classes with "legacy" QuickTime APIs. This opens up abstract moviemaking to the standard of OpenGL, including three-dimensional graphics. The Java implementation, which is not described here, does not require the awkward connection between software components, but does not provide easy access to OpenGL.


Figure 2. One frame of the Mean Value Theorem movie. The test point has moved from x = -1.00 to x = -0.32, and has found one spot where the slope of the curve matches the rise/run line. The text track is shown in white on blue beneath the video track.

Besides the sample movie described here, our work in 2003 and beyond includes constructing animations of algorithms from computational geometry, such as the triangulation of a polygon, constructing and searching in kd-trees and range trees, and more. Our recent work includes animations of algorithms for computing the convex hull, for the intersection of many line segments and for recognizing the polygon in which a point lies. Sample movies are posted on our web site (begin at http://eDisk.fandm.edu/~jay.anderson) as they become available.

ACKNOWLEDGMENTS

Significant assistance has come from Apple Computer, from whom code to construct QuickTime movies, media, and tracks has been borrowed; and from Big Nerd Ranch and Aaron Hillegass, whose Cocoa programming book, course and advice were enormously useful.


Jay Martin Anderson is the Richard S. and Ann B. Barshinger Professor of Computer Science at Franklin and Marshall College in Lancaster, Pennsylvania. Once a physical chemist, he has been teaching computer science since 1978 and making QuickTime movies since 1992. His interests include many aspects of computer graphics, including cartography and computational geometry; opera, theatre, and bicycling. He can be reached at jay.anderson@fandm.edu.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.