Category: Creative Coding

Timed Events (system clock, millis, frameCount)

The first assignment using Fisica will be a clock/time visualization app.

This is how to use time functions (you also have day(), month(), year()).

int s = second();  // Values from 0 - 59
int m = minute();  // Values from 0 - 59
int h = hour();    // Values from 0 - 23

They simply read your operating system’s clock.

This sketch prints 3 bars proportional to seconds minutes and hours.

int s;
int m;
int h;
 
void setup()
{
  size(250, 250);
}
 
//this function is called 60 times per second
void draw()
{
  background(0);
 
  //update variables with time and date
  s = second();
  m = minute();
  h = hour();
 
  //change fill
  fill(255, 0, 0);
  //map the lenght of my bar according to my seconds
  float sWidth = map(s, 0, 60, 0, 200);
  //draw a rectangle
  rect(0, 0, sWidth, 50);
 
  //do the same for minutes and hours
  fill(0, 255, 0);
  float mWidth = map(m, 0, 60, 0, 200);
  rect(0,100, mWidth, 50);
 
  fill(0, 0, 255);
  float hWidth = map(h, 0, 23, 0, 200);
  rect(0,200, hWidth, 50);
 
}

How to make something happen every second

int s;
int lastSecond;
 
void setup()
{
  size(200, 200);
}
 
//this function is called 60 times per second
void draw()
{
  s = second();
 
  //if the second was updated then do something once
  if (s != lastSecond)
  {
    println("A second elapsed");
    //update the last second
    lastSecond = s;
    //this variables will be the same until
    //the next second change in the clock
  }
}

Timing events using frame count
frameCount is a processing variable keeping track of the number of seconds since the launch of the program.

The Modulo operator % calculates the remainder of a division so it can be used to repeat event every -multiples of x-

void setup()
{
size(300, 300);
frameRate(60);
}
 
void draw()
{
if(frameCount%60 == 0)
  {
  background(random(255), 255, 255);
  }
 
println(frameRate);
}

millis: how to make something happen between seconds

Common problem: second() is related to the system clock but millis() count starts as you run the applet. Sometimes you need them to be in sync, for example if you want an analog clock with a second arm moving smoothly:

//the function millis() returns the time elapsed since
//the launch of the sketch in milliseconds
 
//millisRolloverTime is the time elapsed since
//the last time a second changed in milliseconds
int millisRolloverTime;
int prevSec;
 
void setup()
{
  size(100, 100);
  millisRolloverTime = 0;
}
 
void draw()
{
  background(0);
 
  if (prevSec != second () ) {
    millisRolloverTime = millis();
  }
 
  prevSec = second();
 
  int milliseconds = millis() - millisRolloverTime;
  text(second() + " " + milliseconds, 10, 20);
 
}

Putting all together in Fisica

Screen Shot 2014-10-06 at 5.00.32 PM

A couple of applications here:

import fisica.*;
 
FWorld world;
 
//declare box as global because I want to be able to access it
FBox b;
 
//same here
FPoly p;
 
//millisRolloverTime is the time elapsed since
//the last time a second changed in milliseconds
int millisRolloverTime;
int lastSecond;
 
void setup() {
  size(800, 600);
 
  Fisica.init(this);
  world = new FWorld();
 
  //creates the edges: 4 static bodies at the edge of the sketch
  world.setEdges();
 
  //their names are world.left, world.right, world.bottom, world.top 
  //set borders invisible (but still active)
  world.top.setDrawable(false);
  world.right.setDrawable(false);
  world.bottom.setDrawable(false);
  world.left.setDrawable(false);
 
  //gravity
  world.setGravity(0, 200);
 
  //create an FBox: a body 30pixels W X 50 pixels H
  b = new FBox(150, 80);
 
  //set its position in the center of the sketch to the left
  b.setPosition(width/2-100, height/2);
 
  //i don't want it to be affected by other bodies
  b.setStatic(true);
 
  //fill
  b.setFill(252, 138, 199);
  //no stroke
  b.setNoStroke();
 
  //add it to the world
  world.add(b);
 
  //create the polygon
  p = new FPoly();
  p.setNoStroke();
 
  //draw like a processing vertex point by point
  p.vertex(0, -50);
  p.vertex(14, -20);
  p.vertex(47, -15);
  p.vertex(23, 7);
  p.vertex(29, 40);
  p.vertex(0, 25);
  p.vertex(-29, 40);
  p.vertex(-23, 7);
  p.vertex(-47, -15);
  p.vertex(-14, -20);
 
  p.setFill(252, 138, 199);
 
  //the center is the position 0, 0
  p.setPosition(200, height-100);
 
  world.add(p);
}
 
 
void draw() {
 
  //change bg according to seconds using HSB mode
  colorMode(HSB, 100); //values from 0 to 99
 
  float bgHue = map(second(), 0, 59, 0, 99);
  color bgColor = color( bgHue, 20, 100);
 
  background(bgColor);
 
  //restore default RGB mode
  colorMode(RGB, 255);
 
  //calculate the current milliseconds
  if (lastSecond != second () ) {
    millisRolloverTime = millis();
  }
 
  int milliseconds = millis() - millisRolloverTime;
 
  //the box moves according to the milliseconds
  float boxRotation = map(milliseconds, 0, 999, -30, 30);
  b.setRotation(radians(boxRotation));
  //note how the rotation doesn't actually push the circles
 
  float boxPosition = map(second(), 0, 59, 200, 600);
  b.setPosition(boxPosition, 400);
 
 
  //every second I create a circle
  if (second() != lastSecond)
  {
  //create new circle 30 pix diameter
  FCircle c = new FCircle(10);
 
  //set its center position
  c.setPosition(width/2, 100);
 
  c.setFill(133, 203, 72);
  c.setNoStroke();
 
  world.add(c);
  }
 
  //every second I also apply a force and a torque to the star
  if (second() != lastSecond)
  {
   p.addImpulse(0, -1000); 
   p.addTorque(1000); 
  }
 
  //obviously update this at the end
  lastSecond = second();
 
  //simulating and drawing are separate steps
  //update the simulation
  world.step();
 
  //draw the physics world
  world.draw();
}

Exercises (drawing, for loops, variables)

Exercise 1

Reproduce the drawing below using one for loop:


10 lines, 500×500 px canvas.

Tips:
.Don’t start coding! Break down the problem on paper first
.Consider using a variable for the lines coordinates like startX, startY and endX, endY.
.Try to draw parallel lines first

Exercise 2

Reproduce the dynamic sketch below:

20 lines on each side, 500×500 px canvas.

Exercise 3

Reproduce the drawing below using nested for loops:


9×9 circles. 50px of distance between the centers, 500×500 px canvas.
The circles gradually fade to black.

Tips:
. break down the problem in different sub-problems
. make a tiling of identical circles first
. implement a variable diameter and figure out a relation with the index variable
. do the same with the alpha channel

ADVANCED EXERCISE

Exercise 4

Reproduce the drawing below using nested for loops and appropriate variables for every quantity (eg. number of concentric circles):

Canvas 500x500px. Rows 4, columns 4, target diameter 80px, distance between centers 100px, target inner circles: 10.

Exercise 5

Reproduce the pattern using nested loops and random:

Anni Albers Second Movement – 1978

Exercise 6

Reproduce this animation by psychedelic gif artist dvdp. You’ll need arc(), degrees() and radians() may help:

Assignment: Order vs. Disorder

Make a composition with controlled randomness which depicts “order” when the mouseX is on the left side of the canvas, and chaos (actually randomness) when it is on the right side. The degree of order/chaos should vary gradually with the position of the mouse.

.Use for loops
.Check the example below for reference but don’t make a variation of it. The grade will be mostly based on the originality of your sketch.
.Try using noise instead of random.

This is a simple, boring example.

 
void setup() {
  size (400, 400);
  fill(255, 255, 255);
  smooth();
  noStroke();
}
 
 
void draw() {
 
  background(255, 255, 255);
  fill(0, 0, 0);
 
  float xPos;
  float yPos;
  int circleSize = 5;
  int circleDistance = 20;
 
  //defines the x-coordinate 
  for (int x=10; x< = width; x=x+circleDistance) {
    //defines the y-coordinate   
    for (int y=10; y<= height; y=y+circleDistance) {
 
      //the position is mostly determined by a grid but it also
      //has a component of randomness
      xPos = x + random(mouseX/50);
      yPos = y + random(mouseX/50);
 
      //80 is a "magic number" I figured out by trial and error
      //it reduces the amount of randomness
 
      //you can use the functions map and constrain for similar purposes
 
      ellipse(xPos, yPos, 10, 10);
    }
  }
}

Transformation Matrix (rotate, translate, scale)

Try this

rect(0, 0, 55, 55);
translate(30, 20);
rect(0, 0, 55, 55);
translate(14, 14);
rect(0, 0, 55, 55);

What happened?

And this:

translate(width/2, height/2);
rotate(radians(45));
rect(-25, -25, 50, 50);

Example of transformation + scale + rotation.
More info here.

void setup()
{
  size(200, 200);
  background(255);
  noStroke();
  rectMode(CENTER);
 
  // draw the original position in gray
  fill(192);
  rect(0, 0, 40, 40);
 
  // draw a translucent blue rectangle in the new position
  fill(0, 0, 255, 128);
 
  pushMatrix();
    translate(100, 100);
    rotate(radians(45));
    scale(0.5);
    rect(0, 0, 40, 40);
  popMatrix();
}

Now reproduce the plotter drawing on the below (Georg Nees Schotter 1968)!

A possible solution:

size(380, 800);
background(255);
noFill();
rectMode(CENTER);
 
int rows = 25;
int cols = 12;
int side = 30;
 
for(int r = 0; r < rows; r++)
  {
  for(int c = 0; c < cols; c++)
    {
    pushMatrix();
 
    float scatteringX = random(-r/2, r/2);
    float scatteringY = random(-r/2, r/2);
 
    translate(25 + scatteringX + c*side, 25 + r*side + scatteringY);
 
    float randomness = r*2;
 
    float angle = random(-randomness, randomness);
 
    rotate(radians(angle));
    rect(0, 0, side, side);
    popMatrix();
    }
  }

Iteration (for loops)


Introducing for loops:

for (int i=1; i< =10; i++)
  {
  println(i);
  }

This draws 10 horizontal lines:

for (int i=1; i< =10; i++)
  {
  line (10, i*10, width, i*10);
  }

Change the color gradually using the counter i!

Generalize the formula using variables for the distance and the number of lines!

There can be multiple instructions in the same loop:

for (int i=0; i<50; i++)
  {
  line (0, i*10, width, i*10);
  ellipse(10*i, i*10, 10, 10);
  }

Make a more complex pattern using at least 3 for loops or multiple instructions in the same loop!

You can add randomness to the order:

 
for (int i=0; i{
line (0, i*10, width, i*10);
float posX = random(0, width);
ellipse(posX, i*10, 10, 10);
}

Create a composition with 12 randomly generated shapes, using iteration!

Embedded iteration

What if you have to iterate on two dimensions?
This is a tiling example using indexes as coordinates.

 
size(500, 500);
smooth();
noFill();
 
background(0);
stroke(18, 255, 233);
 
 for (int x = 0; x <= width; x += 20) {
      for (int y = 0; y <= height; y+=20) {
        rect(x, y, 10, 10);
      }
    }

This is an example using indexes as number of rows and columns.
In this way you have better control over the number of shapes that are being drawn.

size(400, 300);
smooth();
noFill();
 
background(0);
stroke(18, 255, 233);
 
int rows = 8;
int cols = 12;
int circleDiameter = 40;
int distanceX = 30;
int distanceY = 30;
 
for (int r = 1; r <= rows; r++) {
  for (int c = 1; c <= cols; c++) {
 
    ellipse(c*distanceX, r*distanceY, circleDiameter, circleDiameter);
  }
}

Iteration can control other parameters too:

float box_size = 11;
float box_space = 12;
int margin = 7; 
 
size(200, 200);
background(0);
noStroke(); 
 
// Draw gray boxes 
 
for (int i = margin; i < height-margin; i += box_space){
  if(box_size > 0){
    for(int j = margin; j < width-margin; j+= box_space){
      fill(255-box_size*10);
      rect(j, i, box_size, box_size);
    }
    box_size = box_size - 0.6;
  }
}

While loop

Sometimes you don’t know in advance how many times you want to iterate and/or you don’t need an loop counter (variable i). In these cases while loops can be handy. Make sure you exit condition is met at some point:

size(200,200); 
background(255); 
noStroke();
smooth();
 
float w = width; 
while (w > 0) { 
  fill(w); 
  ellipse(width/2,height/2,w,w); 
  w = w - 20; 
}

Repetition and variation

In August 62 I started doing silkscreens. I wanted something stronger that gave more of an assembly line effect. With silkscreening you pick a photograph, blow it up, transfer it in glue onto silk, and then roll ink across it so the ink goes through the silk but not through the glue. That way you get the same image, slightly different each time. It was all so simple quick and chancy. I was thrilled with it.
– Andy Warhol

Sol LeWitt, Successive Rows of Horizontal, Straight Lines from Top to Bottom, and Vertical, Straight Lines from Left to Right, 1972

In Op-Art (60s)
Abstract subgenre, short lived but influential all across interior design, fashion and advertising. Op-artists were exploring the limits of perception, creating visually tense images and optical illusions.

Victor Vasarely – Orion C – 1962 (not quite Op-art yet)
Victor Vasarely, Boglar II
Victor Vasarely – Titan
Bridget Riley – Movement in Squares
Balm by Bridget Riley
Bridget Riley – Cataract 1967
Bridget Riley looking mod in 1964
Edna Andrade – Black Dragons 1969
Edna Andrade finale 1979
Edna Andrade

Repetition + variation in textile design:

Anni Albers Second Movement – 1978

In minimalist music:

Steve Reich – Clapping music 1972

In early computer art:

Manfred Mohr Cubic Limit 72-77

In «Cubic Limit,» Mohr introduces the cube into his work as a fixed system with which signs are generated. In the first part of this work phase (1972–75), an alphabet of signs is created from the twelve lines of a cube. In some works, statistics and rotation are used in the algorithm to generate signs. In others, combinatorial, logical and additive operators generate the global and local structures of the images.


10 PRINT CHR$(205.5+RND(1)); : GOTO 10
From the Commodore 64 manual

In generative art

Every Icon (1997) John F. Simon, Jr.

Can you reverse engineer Every Icon?

Jared Tarbell – click to see it in real time
Jared Tarbell – Quarter Round

Same principle applied to rotational symmetry:

Marius Watz – Illuminations B

Marius Watz – Illuminations B

Video here

We’ll cover more generative art in a couple of weeks…

In level design
Modular generative systems are often used in games to generate levels procedurally:

Forget me not

Spelunky

and also beyond the 2D grid

Minecraft

Love

Fuji by Robert Hodgin (flight404)

Fuji, test render from flight404 on Vimeo.

Art Instruments / Art tools

There is a fine line between making an interactive artwork and making an expressive tool or an instrument.

Golan’s Yellowfish was conceived as a tool for live performance:

Manual input session can function as a musical instrument:

Digital artist often experiment with the aesthetic of the interface:

Arcs21 by LIA (200?)

Jacksonpollock.org by Miltos Manetas (2003) is way better for iPhone


Infinite Sketchbook / infinite doodle

Sound and visual toys became particularly popular with the advent of touchscreens and apps. Somewhere between interactive artworks and musical instruments:

http://vimeo.com/apitaru

Sonic wire sculptor or Rhonda:

Some software artists deconstruct the digital tools we use every day exposing the raw digital matter beneath the user friendly interface.

Auto-illustrator by Adrian Ward (2001)

Signwave Auto-Illustrator is an experimental, semi-autonomous, generative software artwork and a fully functional vector graphic design application to sit alongside your existing professional graphic design utilities.

Software as culture / speculative software…


Shredder by Mark Napier 1998

Web pages are temporary graphic images created when browsing software interprets HTML instructions. As long as all browsers agree (at least somewhat) on the conventions of HTML there is the illusion of solidity or permanence in the web. But behind the graphical illusion is a vast body of text files — containing HTML code — that fills hard drives on computers at locations all over the world. Collectively these instructions make up what we call ‘the web’. But what if these instructions are interpreted differently than intended? Perhaps radically differently?
The web browser is an organ of perception through which we ‘see’ the web.

(See also the more recent and playful Geocities-izer)


WebStalker I/O/D (1998)

Visceral Facades: taking Matta-Clark’s crowbar to software.

More recent artistic interventions in browsing took advantage of plugins and non-proprietary software (easier to expand and modify):


Add-Art by Steve Lambert (2008)

Reading: Glitch

Olga Goriunova is a new media researcher, teacher, and organizer. She is a co- creator of the Readme software art festival series, and a co- organizer of Runme.org software art repository (http://runme.org /).
Alexei Shulgin is an artist, theorist, musician, curator, and photographer. For more
information see http: // www.easylife.org /

PDF Glitch by Olga Goriunova and Alexei Shulgin – from Software Studies

In this chapter from Software Studies the author present the concept of glitch. Glitches as visual motifs are getting increasingly more common in pop culture, games and music but artists have been exploring glitch aesthetics for at least two decades.

Besides Skrillex and the occasional glitched image, can you find artworks that incorporates glitches and explores the aesthetic of error?

Glitch festival is an easy starting point

Examples


In video art: Monster Movie by Takeshi Murata

jodi
In net.art: Jodi
http://asdfg.jodi.org/
http://oss.jodi.org/os.html


In video games: ROM CHECK FAIL by Farbs


In electronic music: Alva Noto

Text fields, strings, and chars

When we want to print messages with println we use text in “quotes”.
Technically we are passing a string as parameter. You can handle text as variable as long as you declare the proper type.

Declaration and assignment:

String name = "paolo";

Also strings:

 
String text1 = "666";
String text2 = "two words";
String text3 = "text on \nTwo lines";
String text4 = " "; //space
String text1 = "6$%#@# AaBb()";

Concatenation:

size(300, 300);
background(0);
String name = "paolo";
String lastName = "pedercini";
text(name + " " + lastName, 15, 30);
 
String nickName = "pizza";
String fullName = name + " \"" + nickName+"\" "+ lastName;
text(fullName, 15, 60);

Comparison:

size(300, 300);
background(0);
String name = "paolo";
 
if (name.equals("Paolo")) {
  text("Yes", 15, 30, 300);
}
else
{
  text("No", 15, 30, 300);
}

Upper case / lower case:

name = name.toUpperCase();
lastName = lastName.toLowerCase();

Char
Sometimes you want to manipulate single characters within a string. The variable type char is what you want to use.

String word = "HELLO WORLD";
 
void setup()
{
  size(300, 300);
  background(255);
  smooth();
}
 
void draw()
{
  background(255);
  fill(0);
 
  //read on character at time from position 0 to the last position: word.length()
  for (int i=0; i<word .length(); i++)
  {
    char letter = word.charAt(i);
 
    //text(letter, mouseX+i*20, mouseY+i*20);
    //note: in text() you cannot define the textfield 
    //size if you are using a char instead of a string
 
    //OR
    String part = word.substring(i, i+1);
    text(part, 40+i*20, 40+i*20, 100, 100);
 
  }
}

Formatting Text

You can change text color, it’s the same as the fill.

size(300,300);
background(0);
 
//text positioning
text("word", 15, 30);
//custom color
fill(0, 102, 153);
text("word", 15, 60);
//with alpha
fill(255, 255, 255, 100);
text("word", 15, 90);

You can use any font as long as you create a processing-friendly version.

Loading a font created with Processing -> tools -> Create font…

PFont font;
// The font must be located in the sketch's 
// "data" directory to load successfully
font = loadFont("CenturyGothic-32.vlw"); 
textFont(font, 32); 
text("word", 15, 50);

Alignment:

size(400, 200);
background(255);
fill(0);
textAlign(CENTER);
text("This text is centered.", width/2, 60); 
textAlign(LEFT);
text("This text is left aligned.", width/2, 100); 
textAlign(RIGHT);
text("This text is right aligned.", width/2, 140);

Assignment: Drawing app

Make a simple mischievous drawing application like Auto-illustrator. You don’t have to make complex interfaces, just use create a similar tension between of randomness vs user agency.
Bonus: making crazy random stuff is quite easy, try to make a tool that always produces good looking, or stylistically consistent imagery.

Use at least one function from the reference we didn’t cover in class. Learn how it works and be prepared to explain it. Good examples are noise, curves, filters.

Recommended screen size is 320 x 480.

You can start from the bingo example to produce unexpected event and from the simple drawing application we made last week:

void setup(){
  size(200,200); 
}
 
//I declare a variable type boolean, I call it mouseIsDown
//and I assign a value false. All in one instruction.
boolean mouseIsDown = false;
 
void setup() {
  size(500, 500);
  background(255, 255, 255);
}
 
void draw() {
 
//variable stroke according to speed
//float strokeW = abs(mouseX - pmouseX);
//strokeWeight(strokeW);
 
  //draw line only if mouse is down
  if (mouseIsDown == true) //same as if(mouseIsDown)
  {
    line(mouseX, mouseY, pmouseX, pmouseY);
  }
 
}
 
 
//this function is called every time you press a mouse button
void mousePressed() {
  mouseIsDown = true;
}
 
//this function is called every time you release a mouse button
void mouseReleased() {
  mouseIsDown = false;
}

Random and Noise

Let’s add a little bit of uncertainty:

void setup() {
  size(500, 500);
  frameRate(10);
}
 
void draw() {
  background(random(255), random(255), random(255));
}

What about creating ellipses in random positions?

int myDiameter = 10;
 
void setup() {
  size(500, 500);
  background(0,0,0);
  noStroke();
  smooth();
  frameRate(10);
}
 
void draw() 
{   
  float posX = 250;
  float posY = 250;
  ellipse(posX, posY, myDiameter, myDiameter);
}

Make them appear only in a central square of 300×300! Random can accept a minimum and a maximum value.

 
fill(0,0,0,2);
rect(0,0, width, height);
fill(255, 255, 255); //back to white
 
float posX = random(100,400);
float posY = random(100,400);
ellipse(posX, posY, myDiameter, myDiameter);

Add a random fill!
Try to restrict the color range!

Random can be used for triggering events every once in a while:

 
 float bingo = round(random(1,60));
 println(bingo);
 
  if(bingo == 2)
  {
 	//do something...
  }

Random positioning vs random walk:

 
void setup() {
  size (300, 300);
}
 
void draw() {
  background(200);
 
  float rx;
  float ry; 
  rx = width/2;
  ry = height/2;
 
  rx = rx + random(-10, 10);
  ry = ry + random(-10, 10); 
  ellipse(rx, ry, 40, 40);
}
 
float rx;
float ry; 
 
void setup() {
  size (300, 300);
  rx = width/2;
  ry = height/2;
}
 
void draw() {
  background(200);
  rx = rx + random(-10, 10);
  ry = ry + random(-10, 10); 
  ellipse(rx, ry, 40, 40);
}

Noise

Perlin noise is an infinite random sequence of values changing harmonically. It is the basis of a lot of special effects and procedural computer graphics and it’s much more interesting than random.

The sequence will appear “natural” if you take contiguous samples (xoff). For advanced use check the reference.

//the sampled coordinate
float xoff = 0.0;
 
//stores the position of the random circle
float randomPosition = 150;
 
void setup()
{	
size(300, 300);
smooth();
}
 
void draw() {
  background(0);
 
  //ellipse moving randomly
  randomPosition += random(-4, 4);
  ellipse(randomPosition, 100, 10, 10);
 
  xoff = xoff + .01;
  float n = noise(xoff) * width;
  ellipse(n, 200, 10, 10);
}

Variables

Let’s have some fun with variables:

int myDiameter = 10;
 
void setup() 
{
  size(500, 500); 
  smooth();
  noStroke();  
}
 
void draw() 
{ 
  background( 0, 0, 0);
  ellipse(250, 250, myDiameter, myDiameter);
}

I use a var for the radius so I don’t have to type the number every time i want to adjust it.

Since it’s a variable it can be changed:

myDiameter = myDiameter+1;

or

myDiameter++;

What if I want the resizing to be slower?

myDiameter = myDiameter+.5;

Error! It has to be declared as float.

Framerate
By the way there’s another way to slow down the *entire* sketch by changing the framerate.

frameRate(10);

Integer vs. Float
Here’s a nice example from processing.org

int a = 0;      // Create a variable "a" of the datatype "int"
float b = 0.0;  // Create a variable "b" of the datatype "float"
 
void setup() {
  size(640, 360);
  stroke(255);
  frameRate(30);
}
 
void draw() {
  background(0);
 
  a = a + 1;
  b = b + 0.2; 
  line(a, 0, a, height/2);
  line(b, height/2, b, height);
 
  if(a > width) {
    a = 0;
  }
  if(b > width) {
    b = 0;
  }
}

It’s good practice to have variables instead of numbers for a number of reasons…

What about the other parameters of the ellipse?
Try to use variables there too!
Give them meaningful names.

Now use that variable to make the circle move from the left to the right!

wrap around the screen! (if)
go back and forth!

Mouse trailer

Some “temporary” variables can be declared inside functions and blocks. Note: these variables won’t be “visible” outside that block (scoping).

void draw() 
{ 
  background( 0, 0, 0);
 
  float dx = mouseX - posX;
  float dy = mouseY - posY;
 
  posX += dx/10;
  posY += dy/10;
 
  ellipse(posX, posY, myDiameter, myDiameter);
}

Let’s analyze this.

How can we make the circle faster?

How can you make the circle follow the mouse pointer only when the mouse button is down?

Digression: something fun with the background

 
//background( 0, 0, 0);
fill(0,0,0);
rect(0,0, width, height);
fill(255, 255, 255); //back to white

Fill as opposed to background can accept an alpha value. Try 10. Why is that?

Assignment: Face

faces

Draw a stylized face in Processing. Requirements:

– A canvas size of 600 x 600

– Front view, not profile

– Use at least 10 graphic elements. Use the drawing functions I covered in class but also try something new from the reference.

– Use colors that don’t suck.
You can steal color palettes from here.
Create a new one with Kuler
Generate one from a picture with this tool

Here are some good examples from the past years, you can check the source code by clicking on code down to the right:
here , here , this one, this one too,
this
this one uses loops which I haven’t covered yet

PART 2: Make it Responsive

For this assignment, you’ll add sound-interactivity to your face using the Minim audio library.

The template files can be downloaded from here

Your Processing project will have two files.

The map function is crucial for this assignment.

float V = map(volume, 0, 100, 2,100);

In this snippet, V will assume a value between 1 and 200 in relation to the value of volume.
0 (silence) -> 1
200 (maximum noise) -> 200
All the in-between values will be scaled proportionally.

Map can produce negative values

float V = map(volume, 0,100, -100,100);

Or invert the scale

float V = map(volume, 0,100, 500,0);

 

Delivery

1. Export it as mac app
2. Zip the project folder with pde and .app
3. Upload the zip on dropbox or similar service
4. Write a blog post with a screenshot of the sketch and a link to the zip

Tips:

  • If stylized character design is not one of your strengths, look for inspirations in the pictoplasma Flickr pool
  • Volume can affect colors, positions, sizes, portion of arcs, control points in curves
  • Always backup your projects. Careful the name of the folder must correspond to the name of the main file. es: soundFaceBackup must contain soundFaceBackup.pde and MyAudioHandler.pde.
  • The easiest way to mash up this sketch with the previous one is copy the instructions from the static face to the dynamic example and not viceversa.
  • Don’t put other .pde files in your folder unless you know what you are doing, it may confuse Processing. You should have only 2 open tabs, the face sketch and the microphone handler.
  • Don’t get too obsessed if some shape breaks or overlaps, the microphone handler is not 100% reliable and may occasionally shoot some weird levels. The function constrain(var, min, max) can also be used to limit values.

Bonus
If this assignment is too easy for you, you can integrate face detection using this super simple package:
FaceOSC + Processing template
Read the readme file for instructions.

Variables

Let’s have more fun with variables:

int myDiameter = 10;
 
void setup() 
{
  size(500, 500); 
  smooth();
  noStroke();  
}
 
void draw() 
{ 
  background( 0, 0, 0);
  ellipse(250, 250, myDiameter, myDiameter);
}

I use a var for the radius so I don’t have to type the number every time i want to adjust it.

Since it’s a variable it can be changed:

myDiameter = myDiameter+1;

or

myDiameter++;

What if I want the resizing to be slower?

myDiameter = myDiameter+.5;

Error! It has to be declared as float.

Framerate
By the way there’s another way to slow down the *entire* sketch by changing the framerate.

frameRate(10);

Integer vs. Float
Here’s a nice example from processing.org

int a = 0;      // Create a variable "a" of the datatype "int"
float b = 0.0;  // Create a variable "b" of the datatype "float"
 
void setup() {
  size(640, 360);
  stroke(255);
  frameRate(30);
}
 
void draw() {
  background(0);
 
  a = a + 1;
  b = b + 0.2; 
  line(a, 0, a, height/2);
  line(b, height/2, b, height);
 
  if(a > width) {
    a = 0;
  }
  if(b > width) {
    b = 0;
  }
}

It’s good practice to have variables instead of numbers for a number of reasons…

What about the other parameters of the ellipse?
Try to use variables there too!
Give them meaningful names.

Now use that variable to make the circle move from the left to the right!

wrap around the screen! (if)
go back and forth!

Mouse trailer

Some “temporary” variables can be declared inside functions and blocks. Note: these variables won’t be “visible” outside that block (scoping).

void draw() 
{ 
  background( 0, 0, 0);
 
  float dx = mouseX - posX;
  float dy = mouseY - posY;
 
  posX += dx/10;
  posY += dy/10;
 
  ellipse(posX, posY, myDiameter, myDiameter);
}

Let’s analyze this.

How can we make the circle faster?

How can you make the circle follow the mouse pointer only when the mouse button is down?

Digression: something fun with the background

 
//background( 0, 0, 0);
fill(0,0,0);
rect(0,0, width, height);
fill(255, 255, 255); //back to white

Fill as opposed to background can accept an alpha value. Try 10. Why is that?

Dynamic Mode

Let’s make our first interactive sketch

void setup() {
size(500, 500);
}
 
void draw() {
background(255, 255, 255);
line(250, 250, mouseX, mouseY);
}

What if we move the background line in the setup function?

void setup() {
background(255, 255, 255);
size(500, 500);
}
 
void draw() {
line(250, 250, mouseX, mouseY);
}

Before, the background was filled every frame, which is very fast 60 fps.
With this layering it works like a creative tool.

Change the rectangle with an ellipse (they happen have the same number of parameters)

void draw() {
line(mouseX, mouseY, pmouseX, pmouseY);
}

pmouseX, pmouseY is the last mouse position, they are useful system variables.

Make a circle that follows the mouse!

Try to switch the mouse:

ellipse(mouseY, mouseX, 50, 50);

And try this:

background(255, 255, 255);
ellipse(mouseX, height-mouseY, 50, 50);

height and width are constant representing the size of the canvas.
The expression width-mouseY will be resolved before the ellipse gets drawn.

Draw an ellipse that mirrors the mouse position on both axis!

You can draw more than one object on each draw iteration:

background(255, 255, 255);
ellipse(mouseX, mouseY, 50, 50);
ellipse(width-mouseX, height-mouseY, 50, 50);

A less predictable behavior:

background(255, 255, 255);
ellipse(mouseX, mouseY, 50, 50);
ellipse(width-mouseY, mouseX, 50, 50);

You can create all sorts of complex relationships starting from the mouse coordinate

ellipse(mouseX, height-mouseY, 50, 50);
ellipse(mouseX/2, height-mouseY/2, 50, 50);

Make a complex set of relationships between 5 or more shapes!
(redraw the background at every refresh)

***

Introducing variables.
Boolean:

//I declare a variable type boolean, I call it mouseIsDown
//and I assign a value false. All in one instruction.
boolean mouseIsDown = false;
 
void setup() {
size(500, 500);
background(255, 255, 255);
}
 
void draw() {
print(mouseIsDown);
}

Note: print() is only for us, the programmers, it doesn’t affect the compiled sketch.

Use println instead and change the variable to true

mouseIsDown is not a system variable like mouseX: we created it, we named it and we have to manage it on our own.

Processing provides a way to detect the mouse clicks:

//I declare a variable type boolean, I call it mouseIsDown
//and I assign a value false. All in one instruction.
boolean mouseIsDown = false;
 
void setup() {
size(500, 500);
background(255, 255, 255);
}
 
void draw() {
println(mouseIsDown);
}
 
//this function is called every time you press a mouse button
void mousePressed() {
mouseIsDown = true;
}
 
//this function is called every time you release a mouse button
void mouseReleased() {
mouseIsDown = false;
}

mouseIsDown is actually used to store the state of the mouse.

Now we can make a simple drawing application that draw a line only if the mouse is down:

void draw() {
if (mouseIsDown == true) //same as if(mouseIsDown)
{
line(mouseX, mouseY, pmouseX, pmouseY);
}
}

if is a condition and uses special operator == != < >

Make the application draw only if the mouse button is up!

Make the application draw only if the mouse position is on the top half of the screen!

Expressions in the conditionals can be combined:

if (mouseIsDown == true && mouseY > 250)

This makes the application draw only if the mouseIsDown is true AND if the mouse position is on the top half of the screen.

Drawing in Processing

Let there be line!

line(10, 10, 40, 60);

Run, commands, syntax, parameters / arguments, typography, non alphanumeric characters, parenthesis vs. brackets, semicolon, coordinates…

 

Canvas

size(500, 500);
background (255, 255, 255);

 

2D Primitives

point(300, 300);
triangle(10, 20, 50, 200, 200, 100);

Make it isosceles!
Make it rectangle!

Quadrilateral

quad(10, 10, 120, 20, 100, 150, 10, 100);

Make a square!
Make a butterfly!

Rectangle

rect(100, 100, 200, 100);

Make a square!
Center it!

Ellipse

ellipse(300, 200, 300, 200);

How does it work? Check the Processing reference manual
Inscribe the circle in the canvas!

Comments

//why comments
/*
Because they make you code readable.
(O_o)
*/

 

Attributes

strokeWeight(4);

Camelback convention. keepItInMind.
Processing is case sensitive strokeWeight and strokeweight are not the same.

size(500, 500);
background (255, 255, 255);
line(10, 10, 360, 50);

Pixelated line: ugly

size(500, 500);
background (255, 255, 255);
smooth();
line(10, 10, 360, 50);

Antialias: pretty

Pen state

size(500, 500);
background (255, 255, 255);
smooth();
line(10, 10, 360, 50);
stroke(255, 0, 0);
line(10, 30, 360, 70);

The state of your pen and your canvas remains the same until you change it.
If you don’t touch it, processing uses the default.

Colors

//try this
background (255, 255, 255);
//and then try this
//background (0, 0, 0);

Red green blue 0-255.
Make it red!
Try the color picker!

...
strokeWeight(4);
stroke(255, 0, 0);
//noStroke();
fill(0, 255, 0);
//noFill()
triangle(10, 20, 50, 200, 200, 100);

Ok, you are an artist now. Reproduce the Mondrian!

 

Transparency

size(500,500);
background (255, 255, 255);
smooth();
noStroke();
fill(255,0,0);
rect(100, 100, 100, 100);
fill(0,0,255,127); //255/2
rect(150, 150, 100, 100);

Also known as alpha channel.

 

Drawing mode
Sometimes you want to draw a circle from the top left corner or a square from the center. Here’s how to do it:

size(500,500);
rectMode(CENTER);
rect(35, 35, 50, 50);
rectMode(CORNER);
fill(102);
rect(35, 35, 50, 50);
size(500,500);
ellipseMode(CENTER);
ellipse(35, 35, 50, 50);
ellipseMode(CORNER);
fill(102);
ellipse(35, 35, 50, 50);

 

Vertex
You can use this combo to draw any polygon specifying the vertexes.

size(500,500);
//remember to specify a noFill() if you don't want a fill
beginShape();
vertex(20, 20);
vertex(40, 20);
vertex(40, 40);
vertex(60, 40);
vertex(60, 60);
vertex(20, 60);
endShape(CLOSE);
//if you don't specify CLOSE the outline will left open

Curves
curveVertex is the easiest way to draw continuous curves. It works like vertex (begin, points, end).

noFill();
beginShape();
curveVertex(84,  91);
curveVertex(84,  91);
curveVertex(68,  19);
curveVertex(21,  17);
curveVertex(32, 100);
curveVertex(32, 100);
endShape();

Arcs

size(500,500);
background (255, 255, 255);
smooth();
fill(142, 199, 242);
arc(150, 150, 300, 300, 0, PI/2);

The beginning and the end are a little tricky.
Remember: 0 is center right, 2*PI is the full circle. PI half circle. PI/2 a quarter etc…

Or just use radians(angleindegrees); to convert:

arc(150, 150, 300, 300, radians(180), radians(360) );

Draw a pacman!
Draw a smiley face!

Hello Processing



Processing is a free and open source programming language created in 2001. It’s is a development environment, a set of tools, and an online community.
It was created to promoted software literacy within the visual arts but developed into a popular artist tool.
Download Processing here

Watch this introduction to Processing to get some basic elements and an overview of the environment.

Here you can find some more examples by various artists.

This Vimeo group is also a good resource to check out finished projects.

openprocessing contains plenty of examples with source code, mostly student’s work. It’s like Youtube for sketches you can upload your own sketches (they must work in javascript mode).

The material here is not comprehensive, you will need to use a variety of resources:

– The official reference to figure out how to use certain functions

– The official forum to see if your problem has been solved before (almost certainly yes). Please don’t ask for help unless you are doing advanced stuff.

– The examples within processing file > examples.

– Online textbooks like learning processing

– Language-agnostic communities like stack overflow

Note that googling Processing + your problem may not be the most effective way to find information because Processing is a very common word, especially in programming.

Next: Processing IDE, sketches and publishing

Reading: Program or be Programmed

programorbeprogrammed

Douglas Rushkoff is an American media theorist, writer, columnist, lecturer, graphic novelist, and documentarian. He is best known for his association with the early cyberpunk culture, and his advocacy of open source solutions to social problems.

One of his most recent books is Program or be Programmed: Ten Commands for a Digital Age. In its ten chapters Rushkoff provides cyberenthusiasts and technophobes alike with guidelines to deal with the digital world without being controlled by it.

Read the introduction. PDF here

And leave a thought in the comment section below. I want more than a summary or a personal reaction (I agree/I disagree). You can start from this question:

Can you think of an example of a computational system or artifact that “programs” our lives or deeply affect our society? What are its bias and problems (if any)? Can you envision a better alternative?

Instructional Drawings

Class Exercise: Blind Drawing

  • Divide students into pairs. Call one person of each pair X, the other Y.
  • X students get drawing 1.
  • Y students get drawing 2.
  • Distribute blank paper and pens if necessary.
  • Pairs sit back to back without looking at the other’s drawing
  • X student describes his drawing to Y; Y tries to draw it from his instructions.
  • Switch at a reasonable time.
  • Y student describes her drawing to X; X tries to draw it from her instructions.
  • Pin up the drawings at the end, so people can see. Group by X/Y.
  • Discuss the results

Class Exercise: reverse engineering

This image is procedurally generated (Click to zoom):

1) Analyze it and try to “reverse engineer” the algorithm that produces similar images (only the lines, colors are not important). Describe the process using the minimum amount of clear, non ambiguous instructions.

2) Give the instructions to a person who has not seen the image and ask him/her to “execute” the process using a pen or pencil and a ruler, without giving him/her additional feedback – like in the exercise we did in class.

Warning: I don’t want exactly the same image line by line, but a universal set of instructions that can produce infinite variations of the pattern.

Here’s another image produced by the same algorithm:

Assignment: Drawing Algorithm

conditional drawings

1) Take a look at the videos and the materials on the conditional design website and manifesto. Also check peg programming for pseudo-code examples.

2) Create a set of instructions able to generate an infinite set of different drawings.

3) Without showing the previous results ask three (or more) people to execute them. You are not allowed to communicate verbally during the execution.

4) Post the results on the blog.

Requirements:

The surface has to be a standard letter sheet (8.5 by 11 inches). The tool should be a provided marker.

Your rules must contain an element of iteration. There should be “loops” in the execution that create repetition, seriality, fractal structures.

If there is repetition in the process you may have to devise an ending condition. You can verbally stop the execution, set up a timer, or prescribe a certain amount of iterations.

Your rules should be as specific as possible but also able to generate different results every time, so you should include at least one element of randomness or ambiguity.

Most importantly: the goal is to create a recipe for interesting drawings, not arbitrary doodles. Can you embed style and composition in a set of rules?