Translation and Rotation (in 3D!) 247
fill(0,100);
// Note the use of pushMatrix()
// and popMatrix() inside the object's
// display method!
pushMatrix();
translate(x,y);
rotate(theta);
rect(0,0,w,w);
popMatrix();
}
}
Interesting results can also be produced from nesting multiple calls to pushMatrix( ) and popMatrix( ).
ere must always be an equal amount of calls to both pushMatrix( ) and popMatrix( ), but they do not
always have to come one right after the other.
To understand how this works, let’s take a closer look at the meaning of “ push ” and “ pop. ” “ Push ” and
“ pop ” refer to a concept in computer science known as a stack. Knowledge of how a stack works will help
you use pushMatrix( ) and popMatrix( ) properly.
A stack is exactly that: a stack. Consider an English teacher getting settled in for a night of grading
papers stored in a pile on a desk, a stack of papers. e teacher piles them up one by one and reads them
in reverse order of the pile. e fi rst paper placed on the stack is the last one read. e last paper added
is the fi rst one read. Note this is the exact opposite of a queue. If you are waiting in line to buy tickets
to a movie, the fi rst person in line is the fi rst person to get to buy tickets, the last person is the last. See
Figure 14.28 .
INBOX
STACK
First one
out
First one
in
QUEUE
First one in & out
Tickets
fi g. 14.28
Pushing refers to the process of putting something in the stack, popping to taking something out. is
is why you must always have an equal number of pushMatrix( ) and popMatrix( ) calls. You can’t pop
something if it does not exist! (If you have an incorrect number of pushes and pops, Processing will say:
“ Too many calls to popMatrix() (and not enough to pushMatrix). ”
Using the rotating squares program as a foundation, we can see how nesting pushMatrix( ) and
popMatrix( ) is useful. e following sketch has one circle in the center (let’s call it the sun) with another
circle rotating it (let’s call it earth) and another two rotating around it (let’s call them moon #1 and
moon #2).
pushMatrix() and popMatrix() are called
inside the class’ display() method. This
way, every Rotater object is rendered
with its own independent translation
and rotation!