Week 13 - 3d

Today:

  • checkin
  • warmup
  • 3d
  • time to work on final project

Warmup activity

Processing in 3D

There are more rendering modes in Processing. The default renderer is P2D. There is also P3D, PDF and SVG. To use a non-default mode you specify it in the size() function.

example

void setup(){
  size(200,200,P3D)  
}

Different renderers have different libraries under the hood in Processing. This is used for the Java library to change color, shapes, text and more. They run at different speeds and have somewhat different use-cases and features.

Use the P3D render mode for drawing in 3D, and for potentially even in 2D if you need a particular effect that is only available using P3D such as texturing or lighting.

coordinate system in Processing

As you can see in this image, the x and y work as we’ve observed so far. We now add a 3rd dimension, z, which increases moving toward you and decreases moving away.

To work in 3D space you must use translate() and add a 3rd argument

translate(x, y, z);

Example 1 - a square moving toward you

//from Processing.org
float x,y,z;

void setup() {
  size(200,200,P3D);
  x = width/2;
  y = height/2;
  z = 0;
}

void draw() {
  translate(x,y,z);
  rectMode(CENTER);
  rect(0,0,100,100);

  z++; // The rectangle moves forward as z increments.
}

We can rotate around axes

size(200, 200, P3D);
background(100);
rectMode(CENTER);
fill(51);
stroke(255);

translate(100, 100, 0);
rotateZ(PI/8); //try rotating around X or Y axis
rect(0, 0, 100, 100);

There are 3d basic shapes available, as well as lighting

void setup() {
  size(200, 200, P3D);
}

void draw() {
  background(0);
  translate(100, 100, 0);
  if (mousePressed) {
    lights();
  }
  noStroke();
  fill(255);
  sphere(50);
}

There are 4 kinds of lighting

  • ambientLight()
  • directionalLight()
  • spotLight()
  • pointLight()

In addition to lighting we also have access to change the view of the scene, which is called the camera. We can zoom in, rotate and scale. This isn’t an actual camera, but it’s more like we are directing a camera to take a view of a particular virtual scene.

An example with the Camera

void setup() {
  size(640, 360, P3D);
}

void draw() {
  background(0);
  lights();
  camera(mouseX, height/2, (height/2) / tan(PI/6), width/2, height/2, 0, 0, 1, 0);
  translate(width/2, height/2, -100);
  stroke(255);
  box(200);
}

Resources

Much more information can be found at the P3D tutorial page