/** * Show effects of different orders of rotation. * pressing x rotates about x axis, y about y, z about z, r resets things */ import java.awt.*; import java.awt.event.*; import javax.media.opengl.*; import javax.media.opengl.glu.*; import com.sun.opengl.util.*; public class Toy3 extends Frame implements GLEventListener, KeyListener { GLCanvas glc = null; int aWidth = 400; int aHeight = 400; float[] identity = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; float[] currentRotation; char lastKey; public static void main(String[] args){ Toy3 t = new Toy3(); } public Toy3(){ super("Toy3"); glc = new GLCanvas(); add("Center", glc); glc.addGLEventListener(this); glc.addKeyListener(this); currentRotation = (float []) identity.clone(); setSize(aWidth,aHeight); setVisible(true); } public void init(GLAutoDrawable drawable){ GL gl = drawable.getGL(); gl.glClearColor(0.2f, 0.3f, 0.2f, 1.0f); } public void keyTyped(KeyEvent evt){ if ( evt.getKeyChar() == 'q' || evt.getKeyChar() == 'Q' ) { dispose(); } lastKey = evt.getKeyChar(); //save the key typed glc.repaint(); return; } public void keyReleased(KeyEvent evt){ } public void keyPressed(KeyEvent evt){ } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height){ GL gl = drawable.getGL(); gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(-2, 2, -2, 2, -5, 10); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); gl.glEnable(GL.GL_DEPTH_TEST); } public void rotate(GL gl, float[] currentRotation, int angle, int x, int y, int z){ gl.glPushMatrix(); gl.glLoadIdentity(); gl.glRotatef(angle, x, y, z); gl.glMultMatrixf(currentRotation, 0); //multiply rotation matrices together gl.glGetFloatv(GL.GL_MODELVIEW_MATRIX, currentRotation, 0); //save result gl.glPopMatrix(); } void doRotate(GL gl) { if ( lastKey == 'x' || lastKey == 'X' ) { rotate(gl, currentRotation, 10, 1, 0, 0); } if ( lastKey == 'y' || lastKey == 'Y' ) { rotate(gl, currentRotation, 10, 0, 1, 0); } if ( lastKey == 'z' || lastKey == 'Z' ) { rotate(gl, currentRotation, 10, 0, 0, 1); } if ( lastKey == 'r' || lastKey == 'R' ) { //reset currentRotation to be identity currentRotation = (float []) identity.clone(); } lastKey = 0; } public void display(GLAutoDrawable drawable){ float[] teapotMat = {0.2f, 0.2f, 0.9f, 1.0f}; float[] lightpos = {0f, 0.0f, 4.0f, 1.0f}; GL gl = drawable.getGL(); gl.glShadeModel(GL.GL_SMOOTH); gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, lightpos, 0); gl.glEnable(GL.GL_LIGHTING); gl.glEnable(GL.GL_LIGHT0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, teapotMat, 0); doRotate(gl); gl.glPushMatrix(); gl.glMultMatrixf(currentRotation, 0); GLUT glut = new GLUT(); glut.glutSolidTeapot(1); gl.glPopMatrix(); } /** This method handles things if display depth changes */ public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged){ } }