Processing inside Field

Firstly, the prerequisites: this tutorial is written for an audience that's familiar with Processing, familiar with either Java or Processing "Java-Lite" language, and not very familiar with Field or perhaps Python — the primary (but not the only) language that Field uses.

Secondly, the punch-line: anything that you can do in Processing you can do in Field with one exception: authoring Java applets for web-pages. Field wraps Processing; Field hijacks Processing; it accesses the same extensions and libraries, and yet offers a far wider range of technologies for the "improvising programmer" — our bet is that with Field you'll be writing code faster, and scaling your projects to greater breadths than Processing has been designed to promote. We think that Field fundamentally changes the nature of Processing development — cleaving what's known as "Processing" into two parts: the first a vibrant community of people using and sharing Java-based libraries for making interesting things and the second a rather conservative and minimal development environment and language that's currently boxed in by its need to be "simple". Field isn't simple.

Thirdly, a warning: OpenEnded Group makes art using Field every day, but we've never made art using Processing inside Field. The bridge to Processing is compact enough that we believe that this is sustainable, but we'll need your bug reports and contributions to make this work.

This video gives a motivating whirlwind overview of the early part of this tutorial:

Getting started

Let's assume that you have a working Field installation, a Processing installation (downloaded from http://processing.org ) and a working ProcessingPlugin. To turn Field's Processing Plugin on, go to the Plugins and extensions manager and turn it on there:

Field's ProcessingPlugin automatically looks inside /Applications, ~/Desktop, ~/Documents and ~/fieldwork for a "Processing XXX" directory with a Processing.app in it to establish where your Processing installation is (it will pick up the extra libraries installed there). If, for some reason, you have your Processing.app hanging out in some odd spot, see the the "processingApplication" option at StartupOptions.

If all goes well, you can open Field and be greeted with screen something like:

There's a good chance that your layout won't be as nice as this — take a moment to minimize the unimportant ones and tidy up a bit — the placement of the windows is automatically restored between sessions. Field is also evolving so quickly that it's likely that your screenshot won't look exactly like the above.

You know you have a working ProcessingPlugin when you have a) a blank Processing window and b) notification that Field has found your Processing application directory (check the "p" tab of the Palette). Specifically, on the "p" tab of the Palette window you'll have something like:

If you don't get a 'p' tab in your palette then you probably need to turn the Processing Plugin on, using the Plugin manager and the instructions above (remember to restart Field!).

We'll discuss the meaning of the selection marked "Applet Namespace" shown above. But for now, just check the boxes to make your "p" tab look like the screenshot above.

Your first box of code

Field, like the Processing development environment, is an environment for writing code. You can already see a text editor, but to be able to edit text in it, first we need to create a box on the canvas to house the code that we want to write.

To create a box (or "visual element") right click on The Canvas to bring up a contextual menu:

This gets us a new element, Field asks for a name. Let's call it Box. Now we have our first visual element on the canvas:

With this selected (you can see the black surround) now we can type code, using the text editor, into this box. In Field we can have as many boxes as we like, we can drag them around, resize them and so one. Later, should we choose to, we can begin to give their spatial arrangement meaning (using more code in boxes that talks about boxes with code in them...)

Inside the text editor, with Box selected, type:

print "hello world"

This is just the hello world program for Python (Java programmers will note that it's quite a bit shorter than the hello world program for Java). To execute this code we have a range of options (see TextEditor for a complete list) since executing code is what Field is all about. Three main ways: we can just hit command-return while our cursor is on that line, or while we have that line selected — this runs the current line or current selection; we can hit command-0 (zero) to execute everything inside the box; or we can option-left-click on the box itself (we can do this without even selecting the box).

Do any of these things and you'll see, in the bottom half of the text editor, instant gratification:

Field's text editor is just letting you write and execute Python. Now would be a good time to avail yourself of one of many of the excellent, Python learning resources (for example: http://wiki.python.org/moin/BeginnersGuide or, in hardcopy form, Mark Luz's book http://www.oreilly.com/catalog/9780596513986/) Anything that's Python the language (strictly speaking, Python version 2.5-ish) should work just fine; Python the set of libraries is a slightly different story. Field uses Jython a Java implementation of Python. Some Python libraries are unavailable, in exchange for having access to any and all Java libraries, including Java that you write yourself, and, of course, Processing.

Your first line of Processing

First you need to tell Field that the code in the box wants to talk to the Processing environment. A right-click on the box itself brings up:

To indicate that this 'box' is now connected to Field's Processing Applet, a badge appears:

Select this box again and now in our text editor we can write:

background(100)

Executing this line (remember: command-enter, command-0, or option click on the box) our Processing window a mid grey. Notice, again, the instant-feedback. Writing:

background(0)
background(255)

and hopping between the two lines with your cursor jamming command-return causes the window to flash. There is none of Processing's play-button, stop-button, compile & go cycle here. Code executes directly inside the Processing window as soon as you decide to execute it. Notice also that, for very simple kinds of code, Python is identical to Processing's Java-Lite language.

The rest of this tutorial, and introduction to Field, is really about unpacking this example and answering the questions — a) what it means to have an environment without a stop-compile-go cycle, one where you can write and experiment with Processing code non-linearly; and b) what extra tools Field provides for making this experimentation as fast as possible. Brief examples of the key ideas will be given below, and then a link to the more complete documentation for Field (elsewhere the documentation won't mention Processing, but hopefully this page will motivate those features enough that you'll get what they are for).

Not just text

The first feature that Field provides of interest is simply in the text editor itself: the text editor doesn't limit itself to just text. You can embed graphical user interface elements into the document.

A right-click inside the text editor brings up an ever growing list of things to insert:

Selecting "Slider (returns float)" gives us a slider

Which we can drag around. This slider is a stand-in for the text that is its value. In fact, all such GUI elements actually just "compile" down to some text (it's just, in some cases, like a graph or a tree view, an awful lot of text) — so remember to include the close parenthesis ) after the slider.

Now you can execute this line (command-return etc.) while moving the slider around. You'll see the background color of the Processing window change as you do this. To make this even faster, right click on the slider and select "Always" from the list of options. Now that line of code will automatically be executed as you move the slider around.

The truth of digital art is that you spend as least as much the time "exploring" the code that generates an artwork as you do writing the code in the first place. Much work is dedicated to finding the value of parameters. Things like these sliders speak directly to making this experimentation happen as fast as possible. Thus, all kinds of things can be embedded in the text editor, and we're very open to hear future suggestions. Take a look at the growing documentation for the embeddable-GUI elements at EmbeddingGui .

Not just lines of code

Fun as exploring a range of background-grays is, we need some larger scale constructs. Python is a very advanced language (with classes, even meta-classes and all manner of rocket-science things), but how to map these language features into Processing through Field ?

Let's start with one of the Processing examples — LightsGL (by Simon Greenwold). In Processing's Java-Lite:

/**
 * LightsGL. 
 * Modified by an example by Simon Greenwold. 
 * 
 * Display a box with three different kinds of lights. 
 */


import processing.opengl.*;

void setup() 
{
  size(800, 600, OPENGL);
  noStroke();
}

void draw() 
{
  defineLights();
  background(0);
  
  for (int x = 0; x <= width; x += 100) {
    for (int y = 0; y <= height; y += 100) {
      pushMatrix();
      translate(x, y);
      rotateY(map(mouseX, 0, width, 0, PI));
      rotateX(map(mouseY, 0, height, 0, PI));
      box(90);
      popMatrix();
    }
  }
}

void defineLights() {
  // Orange point light on the right
  pointLight(150, 100, 0,   // Color
             200, -150, 0); // Position

  // Blue directional light from the left
  directionalLight(0, 102, 255, // Color
                   1, 0, 0);    // The x-, y-, z-axis direction

  // Yellow spotlight from the front
  spotLight(255, 255, 109,  // Color
            0, 40, 200,     // Position
            0, -0.5, -0.5,  // Direction
            PI / 2, 2);     // Angle, concentration
}

Let's begin to convert this to Python in Field (if you are interested we show the conversion of longer applets here and here these pages have much more information about the small differences between Field and Processing's language).

width = p.width
height = p.height

def setup():
    #some versions of processing have trouble resizing the canvas
    #size(width, height, p.OPENGL, None)
    noStroke()

def draw():   
    pointLight(150, 100, 0, 200, -150, 0)
    directionalLight(0, 102, 255, 1, 0, 0)
    spotLight(255, 255, 109, 0, 40, 200, 0, -0.5, -0.5, 3.14/ 2, 2)

    background(0)

    for x in range(0, width, 100):
        for y in range(0, height, 100):
            pushMatrix()
            translate(x, y)
            rotateX(map(p.mouseX, 0, width, 0, 3.14))
            rotateY(map(p.mouseY, 0, height, 0, 3.14))      
            box(70)
            popMatrix()

As you can see the conversion is basically 1-to-1. I've taken the liberty of putting the contents of the defineLights() function directly into draw().

Execute this code and you'll find that absolutely nothing happens (except for a check to make sure there aren't any syntax errors). Why? All we've done is defined two functions, we haven't called them or caused them to be called by anybody. We haven't actually run anything!

We could append:

setup()
draw()

to the code in this box, and execute that, then we'll see some boxes. But they won't move when we wave the mouse over the top of them. After all, we've just called draw() once. We need it to be called every frame.

This is obviously not an unusual request — both in Processing and in Field we expect to have to set things up in ways that get called "every frame" of an animation. So we need one more line of code to get things running by themselves. Field has built-in support for running things every frame through its "special variable" _r. By assigning different things to _r we can cause different things to execute for the lifecycle of the code-box's execution. A code-box has an execution lifecycle when it executes for more than one frame at a time (unlike, say, when you are executing a few lines in the editor with command-return).

For example, this life-cycle starts when it gets an option-mouse-down and ends and continues until it receives an option-mouse-up (if you release option before the mouse button the box will keep on going). In general, boxes turn pale green when they are executing. See OptionClicking for a little more on this topic.

In the example above, we can complete our reconstruction of LightsGL by adding:

_r = (setup, draw, None)

_r is a Python 'tuple' of three things (here, three functions) that describe what to do at the start of execution, what to keep on doing while the box is executing, and what to do at the end, just before it stops executing. In this case Field calls setup() at the first frame draw() while it runs and then just stops when the box is not going to execute any more.

By pushing option-mouse-down on the box, you'll see LightsGL in all its interactive glory:

If you'd like, you can take a look at the documentation for all of the kinds of things that you can set _r to, at VisualElementLifecycles.

More boxes, more code

While a box is running, editing the text to those functions draw() and setup() doesn't do anything. You have to restart the box. But haven't we just re-invented Processing's stop-compile-go cycle ? No. The rest of Field is still running, we can still execute code that directly effects the Processing environment in other boxes (and even in this same box). While we can't redefine draw() on the fly we can redefine anything that draw() calls and we can manipulate any variables that draw() calls upon. Two vistas then open up: adding additional boxes that also do things to Processing that may or may not run simultaneously with other boxes; and techniques for keeping code "live" even when it's running.

Firstly, some more boxes. Let's make a second visual element, (right-click on the canvas), called Box2 (make sure you remember to bridge it to Processing as well). Inside this, we'll put:

def draw():      
    for x in range(0, width, 90):
        for y in range(0, height, 90):
            pushMatrix();
            translate(x, y);
            rotateX(map(p.mouseX, 0, width, 0, 3.14))
            rotateY(map(p.mouseY, 0, height, 0, 3.14))          
            box(70);
            popMatrix();

_r = draw

We can start and stop this independently of our original Box. While it's running, a new set of lit cubes, slightly out of frequency with the original set appear:

Note that Box2 's draw doesn't call background() to clear the background (other wise it would clobber what Box drew). When started (with, say, the mouse) after Box, Box2 's draw really does run after Box 's draw).

Up until this point, Field's Canvas has just acted as a kind of "desktop metaphor" — the spatial arrangement of boxes has meant, at best, something to you, but ultimately nothing to Field. Maybe you can decide to put your working code on the left and the code that your working on on the right...

But it's worth taking a look at the documentation (TheCanvas) to see what kinds of things can end up on the canvas. It's much more than just a space to put 'files'. Here we'll mention just one here — timelines.

The red line that's almost hiding at the edge of the canvas is a timeline. In the most simple scenario it executes things that it passes over (just as if you were option-clicking on them). Try dragging it around the red line and seeing what happens:

As the line gets dragged across "box" the box begins to execute.In more advanced contexts you can make new, independent timelines and scrub them programmatically. In our case here, however, we'll do something quite simple: control them from the keyboard.

Right click on a blank part of the canvas and select "create time marker here":

This will give you a vertical looking marker, which you can drag around (horizontally). If you create another, and drag the boxes around a bit, you'll have something like:

Using the Inspector window, you can change the name of these markers to something other than "untitled" and, more impressively, assign a keyboard shortcut to them.

Call the first one A and give it the shortcut 'a' and call the second one B and give it the shortcut 'b'. Set the "transition duration" for b to something like 1000 (frames).

Now, inside the canvas, pressing 'a' and 'b' will cause the red-timeline to shuttle forth between the two time markers (holding down shift will cause it to jump). If you have your canvas arranged as above then when the red line strikes Box2 the second set of boxes will appear; and then disappear when the red-line leaves again. The purpose of Field is to support as many graphical metaphors for manipulating code as people can think of, and to promote the creation of others. Field has been used to make timelines, graph-based control flow metaphors and many other kinds of "notation" for boxes.

Keeping things Live

While these two boxes are running, you can interact with the Processing applet with the mouse. But the code itself is still pretty much fixed. How to keep this code malleable even when it's running? The first trick is to simply use techniques offered by the language that we are writing in (Python): specifically global variables.

We rewrite our original Box to introduce a global variable red:

width = p.width
height = p.height

red = 0

def start():
    #some versions of processing have trouble resizing the canvas
    #size(width, height, p.OPENGL, None)
    noStroke()

def draw():   
    pointLight(150, 100, 0, 200, -150, 0)
    directionalLight(red, 102, 255, 1, 0, 0);
    spotLight(255, 255, 109, 0, 40, 200, 0, -0.5, -0.5, 3.14/ 2, 2);     

    background(0)

    for x in range(0, width, 100):
        for y in range(0, height, 100):
            pushMatrix();
            translate(x, y);
            rotateX(map(p.mouseX, 0, width, 0, 3.14))
            rotateY(map(p.mouseY, 0, width, 0, 3.14))       
            box(70);
            popMatrix();
    
_r = (start, draw, None)    

Now, while this is running, we can modify the value assigned to red and the color of the directional light will change, in real-time. We can "animate" this global variable from anywhere (including, for example, another box) or we can use a slider or something instead of 0 inside this very box.

Global variables are generally frowned upon by programmers that have been programming big and complicated things for a long time. With good reason: they break the modularity of code. For example, now you can't just copy and paste code boxes from somebody else (or a previous self) without carefully looking at it, because they might use global variables that stomp all over your global variables creating a hard to understand broken mess of implicit assumptions. Field has more sophisticated scoping techniques available, but keeps this global variable access possible and the default — because when you're in a rush there's nothing faster or more straightforward. Take a look at the documentation for visual element delegation and scoping.

So let's just flesh out this global variable option, just a little. In a new visual element, we'll can it "sin box", we'll write this code:

def animateRed():
    global red
    red = Math.sin(_t*20)*128+128

_r = animateRed

And arranged on the canvas:

_t is another Field "special variable" (like the _r). _t is a number that goes from 0 to 1 as the time slider moves across the box (or from 1 to 0 if it's moving backwards). See VisualElementLifecycles for more documentation on these variables.

Given that, it should come as no surprise that, when we scrub from A to B we have an interactive Processing Applet with a light that smoothly oscillates color (with its frequency and phase controlled by the position and dimensions of "sin box" no less). Again, just to drive the point home, we can start and stop the oscillation independently of the rest of the applet, to tweak it, or "score" it in longer sequences.

Laziness

That said, it's still a lot of typing and mousing around just to manipulate a number. Powerful, yes — it allows us to keyframe and visually script the parameters to our Processing applets — but overkill if we are just trying to find the color of the light that we like.

In this case we could use a slider, but there's an even faster option — the Lazy Text Box.

Let's go back to our original Box code (without the global variable red):

width, height =  p.width, p.height

def start():
    #some versions of processing have trouble resizing the canvas
    #size(width, height, p.OPENGL)
    noStroke()

def draw():   
    pointLight(150, 100, 0, 200, -150, 0)
    directionalLight(0, 102, 255, 1, 0, 0);
    spotLight(255, 255, 109, 0, 40, 200, 0, -0.5, -0.5, 3.14/ 2, 2);     

    background(0)


    for x in range(0, width, 100):
        for y in range(0, height, 100):
            pushMatrix();
            translate(x, y);
            rotateX(map(p.mouseX, 0, width, 0, 3.14))
            rotateY(map(p.mouseY, 0, width, 0, 3.14))       
            box(70);
            popMatrix();

_r = (start, draw, None)    

Now select the first parameter (the zero), right click and select "Lazy Text Box":

This replaces that zero with a zero in a box:

Now when we execute (option-click, or scrub with the timeline) we'll find that that zero acts just like any other zero, but we can in fact change it live:

Edit the zero, press return to accept your changes (or escape to forget them) and you'll find that the color of the directional light will change while the code itself is running.

What's going on here? Surprisingly little. The lazy text box "evaluates" to a piece of rather tedious code that ends up referencing the text box itself (if it exists, it might not be on the screen) — the contents of this box can be almost anything. Specifically, the contents of the text box has to be valid Python — that is, anything that Python finds acceptable inside an eval statement. You can even use a Lazy Text Box to introduce a global variable, a function and so on.

A quiz for those learning Python — explain why the following lazy box (which lazy-ifies all of the parameters to directionalLight) works:

Conclusions

This ends the main body of this teaser-tutorial. Hopefully this is enough to let your enthusiasm take you further. You should look at the text editor which has all kinds of things to help you write code quickly and experiementally (don't miss the auto-complete), the canvas where you'll create boxes (and interactive diagrams, and images and so on). For some more Processing -> Field related documentation (and some observations about the differences between these envrionments) see here. To jump straight to some example Processing / Field code, go here.

The rest of what follows on this page is a more general motivation for Python for Processing, and some notes about the current status of our Processing plugin (the part of Field which connects to the Processing libraries). Field wasn't designed to work with Processing — it was designed to work with any Java code-base — but it seems that it is turning into a particularly good way of interacting with existing Processing libraries and doing the kinds of small experimental things that Processing encourages. Hopefully, and with your bug-reports, contributed code and documentation, we'll construct something that's a better Processing for Processing.

Three things you'll like about Python & Processing

Fundamentally Field came about because of some firm beliefs: firstly that Python was a fine programming language for small, tight, elegant pieces of code that tie together larger things written in "larger" languages (in our case Java); secondly that Python was a better language than we would come up with if we tried to do it ourselves: better made, better thought about and better maintained. Some 7 years on we still believe this to be the case. This site is not a good place to learn Python, but the combination of Python and Processing in Field probably is a fine place to learn Python, and perhaps even programming in general. For those coming from Java and/or Processing's pseudo-java, here are three cool features of Python that will hopefully pique your interest, and sustain it while you learn some new syntax.

These comparisons with Processing (or NodeBox for that matter) are largely unfair. Both environments are designed for simplicity first; all the arguments below trade at least a little conceptual overhead for expressivity. These environments (and their languages, and their libraries) are therefore not really competing, because they are not playing the same game.

1. Generators

We've seen that "Doing something every frame" is a situation that happens a lot when working with Processing or in Field in general. In fact it's fundamental to animation itself. This actually turns out to be quite a poor fit for most languages, including Java. These languages want you to define a method (in Java) or a function (in Python) that, say, draws something:

def drawTheFrame():
   global x
   x += 1
   drawALineFromLeftToRightAt(x, x/2)

or in hypothetical-Java:

public class AnimationDrawer implements Drawer
{
      float x = 0;
      public void drawTheFrame()
      {
             x += 1;
             drawALineFromLeftToRightAt(x, x/2)
      }
}

Animation usually ends up more complex than this. Once we've swept the line from left to right for a bit, we might want to sweep it from top to bottom, for another 100 frames, and then back to left and right. In pure Java we end up with horrible looking things like:

public class AnimationDrawer implements Drawer
{
      float x = 0;
      public void drawTheFrame()
      {
             x += 1;
             if (x< 100)
             {
                   drawALineFromLeftToRightAt(x, x/2)
             }
             else if (x<200)
             {
                   drawALineFromTopToBottomAt(x-100, (x-100)/2)
             }
             else
             {
                   drawALineFromLeftToRight(x-200, (x-200)/2)
             }
      }
}

This grade-school math review isn't going anywhere! To drive this point home, a) just look at the amount of code you'd have to touch if you wanted to change the length of the first part of the animation. The equivalent in Python or Processing's Java-Lite is a few lines shorter, but no better.

In Field we always have the option that we could start arranging visual elements in a timeline. And sometimes this is exactly what we'll do, especially when the chunks are large, intricate and self-contained. But for the example above? overkill.

Enter Python's "Generator". It's a lot like a function, but with a crucial difference. When a function "returns" or falls off the end of it's definition the next time you call it, it starts at the top again — this is what's happening with the drawTheFrame function: each time it's called, we start again at the top, with a slightly different x variable and we keep passing through enough grade-school math and decision logic to get to mainly where we were before or the next step of the animation.

In a generator, when a generator "yields" (rather than returns), subsequent calls of this generator pick up just where it left off. If it returns (or runs out of definition) that's it, it's "over", you need to go an get a new generator from somewhere.

Look again at the code above: the key problem is that we have to keep returning control back to the thing that called us — specifically the main animation loop. This problem isn't ever going to go away (unless we get to turn everything on it's head and call the main animation loop itself, which we don't get to do).

Using generators we can rewrite the code above (in Python) as:

def drawTheFrame():
    for x in range(0, 100):
         yield drawALinefromLeftToRight(x,x/2)

    for x in range(0, 100):
         yield drawALinefromTopToBottom(x,x/2)

   x = 0
    while 1:
         yield drawALinefromLeftToRight(x,x/2)
         x+=1

This code is easier to read, easier to write and easier to maintain. As you begin to combine generators together, you'll realize that it's hard to overstate it's importance for people who are looking to animate things. Field includes special facilities] for running generators instead of functions (in short, you can assign them to _r's whenever you could use a function, and generators that yield other generators build in a stack). Generators are a simple but essential concept, but they will change how you think about coding animation, music and other temporal forms. If you want to know more where this concept leads, see GeneratorExamples.

2. Customizable classes mean a customizable language

Python, like many languages, lets you add and overload operators in class definitions. Simply put this allows you make classes like Vector3 and Quaternion that you can add, multiply and subtract just like you'd add, multiply and subtract numbers (see SimpleLinearAlgebra). This becomes important quickly in basic 3d-animation, which is often little more than a 3d-linear algebra workout. Even better, using Field's Java-based Python you can add overloaded operators to your own Java classes so that you can manipulate them quickly (indeed Vector3 is actually a Java class in Field). There are compelling arguments against permitting operator overloading in "large" languages like Java, but for the kind of scale that short amounts of Processing-like code is aiming for, nothing can beat being able to quickly manipulate points, lines, triangles and cameras using simple operators.

And it gets better. Python allows you to not only state and restate what + and * are when defining a class but also what . and [] do. This allows you to completely rewrite the rules of member access to suit your pleasing, creating micro languages that are better suited to your task at hand. This allows "library" designers to craft extremely tight interfaces to their libraries in ways that go beyond adding features, towards adding techniques. For some examples that are built into Field see LazyFunctionalHelpers, KeyframingInCode, and the property delegation system itself, DelegationAndVisualElements / SelfAndProperties / ExtendingFieldInField. These extensions are mainly just pure Python, but they speak directly to the problems of making live digital art in terse code.

3. Python has keyword arguments (and so on)

After the transformative features of Generators and malleable operators and classes, it seems a little strange to choose this feature for special highlighting. But again, this aspect of the language attacks directly to the problems familiar to Processing-ers everywhere, who are very much in the business of making and using (often other people's) libraries of routines, trying to make these libraries fast to use while simultaneously as powerful and as generic as possible.

If we look at Greenwold's original LightsGL example, we see a series of commented sections:

...

  // Yellow spotlight from the front
  spotLight(255, 255, 109,  // Color
            0, 40, 200,     // Position
            0, -0.5, -0.5,  // Direction
            PI / 2, 2);     // Angle, concentration 

...

Other than an inexplicable love of the number 255 held by the library creators, some features stand out. The "library designer" who had to make up his mind about how to implement spotLight here is in a bad spot. He has to choose between adding features (say, the angle and focus of the light) and avoiding secret knowledge (what all those parameters actually mean). Because this is example code, there are comments. But I know that if I was writing this code curled up on the floor in a machine closet of a gallery somewhere, or renting theater time I know two things for sure: a) I would have to look up what the 4th parameter of spotLight was (quick: does the direction come before or after the position of the light?) and b) I wouldn't bother writing the comments.

Some of the burden involved in writing code like this lightened by Field's autocomplete — pressing command-period after typing spotLi will give you assistance on the parameter names of spotLight and these names are hopefully things like color_red and position_x (the names are taken from the actual source code to PApplet so they never get out of date or need to be maintained). Currently, completion on spotLi gives:

This would be more impressive if there were actually some JavaDoc's for PApplet — we're considering scraping the Processing website for their documentation, but it does include parameter names (and even the source). Note, there's nothing special about Processing — any and all code gets autocompletion including your own. If it's your own code, make sure Field knows where to find the source as wwll as the class files.

Regardless of Field's wonderful autocomplete, the same argument still goes for the burden of reading this code and remembering what it does. But in Python, given a suitable definition of spotLight:

def spotlight(color=(1,1,1), direction=(1,0,0), position=(100,0,0), angle=3.14/2, conc=1):
...

we could get away with writing:

spotLight(color=(1, 1, 0.5), direction=(0,-0.5, -0.5), position=(0,40,200), conc=2)

Three things to notice: 1) it's self-documenting; 2) the parameters can come in any order; 3) if you miss a parameter out (here, the angle) a sensible default is supplied.

This last point is bigger than it seems. Should the library designer upgrade their library they to add a cornerFuzz and a cornerAngle parameter (perhaps it controls the sharpness and orientation of the barn-doors on our spotlight) they can do so:

def spotlight(color=(1,1,1), direction=(1,0,0), position=(100,0,0), angle=3.14/2, conc=1, cornerFuzz=0, cornerAngle=0):
...

Nobody else's code needs to change. The additional parameters can be added, as needed, as people begin to play with the fuzziness of their spotlight corners. Tension between features (as many parameters as possible) and complexity (as few parameters as possible) is defused. Python is an excellent small-library-making language. In Java one requires recourse to larger structures than the essentially pure-constructors being used in Processing to obtain this kind of convenience. If you choose not to do that, you end up with the kind of organic mess that the PApplet class has become: easy to write, hard to read, and an extreme pain to change.

Namespaces, Field, Processing and that odd menu at the start

Processing's structure — at least before you add contributed libraries — encourages a flat namespace. Specifically, there are lots of functions like smooth() and background() that are written just like that. This keeps things "simple" (less typing) at the cost of a different kind of complexity — now we have all of these functions sharing the same global space of names. In order to remain compatible with Processing, and to ease transition to Python, Field can't do much about the original design of Processing's PApplet class (where all of these functions live and grow), so we offer a choice, represented by the button on the palette labelled "Applet Namespace". Should you choose to push this button then everything that's inside the Processing Applet gets stuck into Python's global namespace, so you can just write background(0) like you have always done. Should you (or anybody else whose code you incorporate) define a background() function you are then strictly out of luck (your code will call that function rather than the Processing one, or their code will call Processing's one, or both, or neither...).

If you don't select to do this (and even if you do) the current Processing Applet is available as the global variable p. So, you can always write p.background(0) and get a black background in your window. Now everybody, including Field, will know what specific background() you are talking about. An important note: as it currently stands, only methods are copied correctly into the global namespace: to access instance variables that change like mouseX, the p. prefix is always required.

Finally, a word about Python's own name-space rules and conventions. To import a Java package one writes, in Python:

from some.package.called.something import *
from some.other.package.called.somethingelse import someclass

What this does should be pretty clear from the Java (and Processing) equivalent. Field automatically looks around your hard-drive for a Processing application, and when it finds one, does the right thing with the libraries directory — you should be able to from X import * from them just as you would import X.*; in Java.

While in Processing libraries are automatically included if you manage to put their .jar files in the correct spot in your 'sketchbook' directory; in Field you add things through the Plugin Manager. Directories added are recursively searched for .jar files and .class files (and .py files too).

Event hooks

One last thing is missing from the discussion above: events. In Processing you can define some special methods: mousePressed and mouseMoved and so on to have code called when the mouse is pressed or moved over your applet. Having a single point of definition (you only get to have one method) doesn't fit well, architecturally, with Field's non-linear execute some-code-here, some-code-there approach.

So a different approach is to use some Python function Decorators:

@p.onMouseClick
def click():
    print "click!!"

You can also do this longhand:

def click():
    print "click!!"

p.onMouseClick(click)

Either of these registers the method click as a handler for mouse clicks for the Applet.

Note you only have to do this once — there's no need to make sure that this code "keeps on running" like you'd do for the equivalent of a draw() method. A handler is registered while a draw method is executed directly.

A couple of things about these registration methods (onMouseClick, onMouseMove, onMousePress, onMouseRelease, onMouseDrag, onKeyPressed, onKeyReleased (each of these has an equivalent @ form (i.e. @p.onMousePress)).

Firstly, you can do things like this:

p.onMouseClick("click", click) # is equivalent to p.onMouseClick(click)
p.onMouseClick("someName", click) # registers click under then name someName

p.onMouseClick.remove(click) # click will no longer be called
p.onMouseClick.remove("someName") # whatever is under name "someName" will not be called again
p.onMouseClick.remove() # whatever onMouseClick handler we're currently "in" will not be called again

Multiple handlers can be registered under different names, only one can be registered under a particular name, and the name defaults to the name of the function. This allows you to write code that is idempotent — which is a fancy word for 'can be safely executed over and over again'. This is our favorite style in Field — changing a little code and jabbing command-0 to execute everything in the text editor without ever having to worry about _un_registering things that we registered the last time we executed something.