Processing 101

A Processing sketch in active or continuous mode has two fundamental methods: setup() and draw(). The first method is invoked when your application starts and the second is invoked over and over again. It is the main loop of your application.

setup()

Any instructions put in the setup() method run when the application first starts. It is where you prepare the application, like setting up the size and the frame rate.
void setup(){
     size(400,400);
     frameRate(30); //number of times per second that the draw() method is called
     print("all done setting up");
 }
void setup(){
  size(400,400);
}
void draw(){
  stroke(0x33FF0000);
  fill(0x330000FF);
  strokeWeight(random(10));
  ellipse(mouseX, mouseY, 200,200);
}




Setting the size of your sketch is easy:

To set the size of your application you use the following command specifying the width and the height: size(200,100);

Keep in mind that if your size is set to 200,100, while it may be 200 pixels wide, you will only see pixels 0 through to 199, pixel number 200 is off the edge, in the same way that the 30th centimeter on a 30cm ruler is 'outside' of the measured area.

If you run this code:
size(200,100);
background(0,0,0);
stroke(255,0,0);
point(50,50);
stroke(0,255,0);
point(100,50);
stroke(0,0,255);
point(150,50);
you will see this:


The screen is basically a graph of pixels - each individually addressable by a unique (X,Y) coordinate. The origin (0,0) is at the top left corner of the rectangle. As you add to Y, you move down. As you add to X, you move to the right. It's similar to playing the classic game Battleship.

size(200,100);
Calling the size function lets the size of the canvas to 200 pixels high, 100 pixels wide. If you do not call this at the beginning, the default will be 100x100.

background(0,0,0); Calling the background function lets you change the color of the entire canvas. 0,0,0 translates to 100% black. If you never call background in Processing, then the default will be gray.

stroke(255,0,0); Calling the stroke function lets you change the current drawing color so that every drawing command called after it will draw using that color. 255,0,0 translates to 100% red. If you never call stroke in Processing, then the default will be black.

point(50,50); Calling the point function will set the pixel at 50,50 to the current stroke color. In this case, red.




Putting something on the screen is easy:

Using built in commands like line() means everything you do can give you immediate visual response. line() does what you think it does. It takes four simple arguments-two pairs of x and y coordinates. One for the start point and another for the end point.
line(0,0,200,200);

Processing has several built in functions for creating 2D primitive shapes:

When drawing ellipses and rects you can also specify where to start drawing by calling the ellipseMode() or rectMode() functions before drawing your shapes:



There are a few basic drawing functions:






Exercise Draw the following shapes:
lorenzobraviEsercizio01.png
from Lorenzo Bravi's Procedure di Basic Design




Processing is Interactive:

Add a draw() method, and the line you draw can become interactive if you use the coordinates of the mouse.
void setup() {  
	size(400,400);  
}  
void draw() {  
	//try moving this line to setup and watch what happens!  
	line(0,0,mouseX,mouseY);  
} 
To only see one line at a time, you need to call background()
void setup() {  
	size(400,400);  
}  
void draw() {  
	background(255);
	//try moving this line to setup and watch what happens!  
	line(0,0,mouseX,mouseY);  
} 
You can add math to these coordinates:
void setup() {  
	size(400,400);  
}  
void draw() {  
	background(255);
    ellipse(mouseX-100,mouseY-20,30,30); 
} 




Exercise Recreate the following sketches:
lorenzobraviEsercizio01.png
from Lorenzo Bravi's Procedure di Basic Design





Processing uses variables:

Using variables in place of fixed number values allows you to adjust those values – over time for animation, to transform the value aesthetically, and to experiment with how code works. In fact, the best way to start to figure out code – even before you're sure how it works – is often to start messing around with values. Sometimes breaking code you don't understand can be a great learning experience. Watch what happens when you move mouseX and mouseY with the interactive line:
void setup() {  
	size(400,400);  
}  
  
void draw() {  
	background(200);  
	line(mouseY,height/2,width/2,mouseX);  
} 
By placing the c=variable at the top of your sketch, all of your functions can use this variable
float k;
void setup() {
  size(500,500);
  background(255);
}
void draw() {
  k=mouseX/10;
  ellipse(mouseX,mouseY,k,k);
}
 




Processing uses conditionals

float k;
void setup() {
  size(500,500);
  background(255);
}
void draw() {
  k=mouseX/10;
  if (mouseX<250){
    fill(255);
  }else{
    fill(0);
  }
ellipse(mouseX,mouseY,k,k);
}
Your conditionals can become increasingly complex by using and and or
AND


OR




Exercise Recreate the following sketch:
lorenzobraviEsercizio01.png
from Lorenzo Bravi's Procedure di Basic Design




Processing uses loops

Seeing a loop happen – even a simple one – illustrates the way the process of iteration can work in more complex problems.


int numOfLines = 10;  
int distance = 10;  
  
size(200,200);  
background(0);  
stroke(255);  
strokeWeight(3);  
  
int yPos = 20;  
for(int i=0; i<numOfLines; i++) {  
  line(20,yPos,width-20,yPos);  
  yPos += distance;  
}  

//bonus!  
/* 
//int yPos = 20; 
for(int i=0; i<numOfLines; i++) { 
  line(20,yPos,width-20,yPos); 
  yPos += distance; 
  distance += 2; 
} 
*/ 
Here's another for loop example:
//Continuous radial gradient
size(200,200);
background(0);
for (int i=255; i>0; i--){
    noStroke();
    fill(255-i);
    ellipse(width/2, height/2, i, i);
}
And another:
for (int i = 0; i < classes; i++) {
   doHomework();
}



Processing can iterate over arrays:

Using arrays (lists) with loops can help to simplify code, even in a simple example – loops and lists are a natural match for one another, since the former lets you iterate through the latter.
int[] circles = {170,113,78,30,13};  
size(400,400);  
background(150);  
noStroke();  
smooth();  
  
for (int i=0;i<circles.length;i++){  
  fill(random(0,255),random(0,255),random(0,255));  
  ellipse(width/2,height/2,circles[i],circles[i]);  
}

Nested Loops

You can also place a loop inside a loop.
Huh?


It helps to see the result.


You can extend the loops within loops concept to more involved iteration, such as iterating through columns, then rows – essential to processing the individual pixels in an image.

Exercise Recreate the following sketch:
lorenzobraviEsercizio01.png
from Lorenzo Bravi's Procedure di Basic Design





Transformations exist in 2d and 3D space

translate() specifies an amount to displace objects within the display window. The x parameter specifies left/right translation, the y parameter specifies up/down translation, and in 3D the z parameter specifies translations toward/away from the screen. Using this function with the z parameter requires using the P3D or OPENGL parameter in combination with size().

Transformations apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling translate(50, 0) and then translate(20, 0) is the same as translate(70, 0). If translate() is called within draw(), the transformation is reset when the loop begins again. This function can be further controlled by the pushMatrix() and popMatrix().
float v;
void setup() {
  size(500,500);
smooth(); }
void draw() {
  translate(250,250);
  v=mouseX;
  ellipse(-100,-100,20+v/10,20+v/10);
  ellipse(100,-100,20+v/10,20+v/10);
  ellipse(0,100,10+v/2,10+v/2);
}




Exercise Design a minimal geometric face. Next, write code in Processing to draw your face in a 500 x 500 pixel window. Then, extend your code by adding one variable called "v" that controls the face so the expression continuously changes as the mouse moves from left to right across the display window.
reas_bravi.png
from Casey Reas's Interactivity UCLA Design Media Arts 2012 class and Lorenzo Bravi's Procedure di Basic Design




Curly braces{}

The curly brace is a syntactical structural element. They always appear in balanced pairs (an open and closed brace), and are used to structure blocks of code. Here’s a conditional if...else example:
if (thisSeason == "summer") {
    enjoySummerVacation();
} else {
    studyInSchool();
}


Functions:

Functions can be understood as recipes. In pseudo-code:
makes cake "Cakemaker" (eggs, flour, ingredients, etc...) {  
  step 1  
  step 2  
  step 3  
  return cake, serves 8  
}  


Here's a function example:
void  enjoySummerVacation() {
    println("sleep late and no homework");
}


Dot syntax and Objects

Another syntactical structure is the dot (.)

Object-oriented programming may seem mystical, but it's really just a way to better organize code functions. For instance, in the case of the cake:
makes cake "Cakemaker" (eggs, flour, ingredients, etc...) {  
  step 1  
  step 2  
  step 3  
  return cake, serves 8  
}  
you might consider the cake's attributes and what can be done to it (make a cake, eat a cake, throw a cake on the ground), and then organize your cake class relative to smaller categories of related things (cupcakes) and bigger categories of things (dessert).

Procedural programming uses functions to organize a program. In OOP, you build much more complex structures called classes. A class is the specification for an object. A class is like a blueprint for a house, and the object is like the house itself. Each house made from the blueprint can have variations. The blueprint is only the specification, not a built structure. Using classes, you can create a blue house or a red one; one house might come with a screened-in porch and the other with just a deck. The class defines the data types and behaviors, but each object (house) made from a single class (blueprint) has variables (color, deck) that are set to different values. To use a more technical term, each object is an instance of a class and each instance has its own set of variables and methods.

To use a class, you create instances of it, known as objects.
Cat myCat=new Cat();


Classes contain properties and methods. You can think of the properties as the traits of the object and the methods as actions you perform on/with the traits. For example, if you create a class called Cat, some of the properties might be color, weight, and markings, and a method might be getBreed(). You use the dot syntax as a way to connect an object with its properties and/or methods.

If you create an object Clark from the Cat class, the object can call the getBreed() method using dot syntax, like this:
Cat Clark=new Cat();
String breed = Clark.getBreed();




As your code becomes more complicated, using classes helps because it is easier to write and maintain smaller, understandable pieces of code that work together than dealing with one large piece of code that does everything at once.

For more information on OOP see
Syntax Structure
Statements —>elements that make up programs.

; or statement terminator—>used to end statements.
If you leave it off the end of your statement, the program will not run.

//Comments —>used for making notes to help people better understand programs.
// A comment begins with two forward slashes

The size() function is a statement that tells the computer how large to make the window.

Function statements take zero or more parameters.

Parameters are data passed into the method and used as values for specifying what the computer will do.
size(200, 200);

The background() function is a statement that tells the computer which color to make the background of the window
background(102);

Processing uses println() to print data, followed by a carriage return, to the output window.
Program/Language Code
Processing println()
Java System.out.println()
Flash/ActionScript trace()




Processsing uses typed variables. If you are using a variable that is a number you must declare what type of number your variable is:

byte,short,int,long,float, or double

Because you set the data type of variables when they are declared in Processing and Java, and that information gets put in the compiled bytecode, the virtual machine (the language interpreter) needs to do less work. Languages like Processing and Java that work this way are called statically typed languages. Languages like Python are dynamically typed, and, due in part to dynamic typing, run slower than Java and Processing.



Processing comes with several code examples. To open them select: File>Sketchbook>Examples>...