Week 8 -- Intro to 3D concepts

back to syllabus

Push and Pop (the stack)

In computer science, a "stack" is an area of memory used to implement a data structure that follows the last in, first out method of access. It's called a "stack" b/c it follows the physical principals of a stack of stuff, such as papers -- one adds papers to the top and remove papers from the top. If we wrote down a sequence of information on pieces of paper and stacked them, that physical stack would provide us with a method of tracking that information in reverse order

As we saw with recursion, a stack is used by the processor to keep track of subroutine calls and returns. In the case of 3d transformations, the stack is used to keep track of the current transformation matrix. "The push() function saves the current coordinate system to the stack and pop() restores the prior coordinate system. push() and pop() are used in conjuction with the other transformation methods and may be embedded to control the scope of the transformations."

For example, examine the different result between the following two applets:

float angle1 = radians(30);
float angle2 = radians(60);

void setup() {
  size(100,100);
}

void loop() {
  background(0);
  stroke(255);
  //translate origin to center of the screen
  translate(50,50,0);
  //rotate by first angle and draw line
  rotateZ(angle1);
  line(0,0,0,-50);
  //rotate by second angle and draw line
  rotateZ(angle2);
  line(0,0,0,-50);

}
float angle1 = radians(30);
float angle2 = radians(60);

void setup() {
  size(100,100);
}

void loop() {
  background(0);
  stroke(255);
  //translate origin to center of the screen
  translate(50,50,0);
  //rotate by first angle and draw line
  /***add push and pop to save the current transformation and
      restore it before rotating the second time***/
  push();
  rotateZ(angle1);
  line(0,0,0,-50);
  pop();
  //rotate by second angle and draw line
  rotateZ(angle2);
  line(0,0,0,-50);

}


If we increment the angle values to animate the rotation, the difference is even more apparent.

angle1 += 0.01f;
angle2 += 0.01f;
angle1 += 0.01f;
angle2 += 0.01f;
It's important to learn and understand the concepts of "push" and "pop". However, Amit Pitaru has written an external Processing library that helps with the placement and transformation of graphical content, called BSpace. For a full explanation with instructions and samples using BSpace, visit: http://www.pitaru.com/processing/BSpace/.

CONTINUE ON TO 4. . .

back to syllabus