/** * A little toy program for showing students of COMP3421 * the basics of 3D rendering. * */ import java.awt.*; import java.awt.event.*; import javax.media.opengl.*; import javax.media.opengl.glu.*; import com.sun.opengl.util.*; public class Toy1 extends Frame implements GLEventListener, KeyListener { GLCanvas glc; int aWidth = 400; int aHeight = 400; public static void main(String[] args){ Toy1 t = new Toy1(); } public Toy1(){ super("Toy1"); glc = new GLCanvas(); glc.addGLEventListener(this); glc.addKeyListener(this); setLayout(new BorderLayout()); add("Center", glc); setSize(aWidth,aHeight); setVisible(true); } /* The functions below are required because we are a GLEventListener. We could also have put them in another class and put that class in the addGLEventListener method above. */ /** * Executed exactly once to initialize the * associated GLDrawable */ public void init(GLAutoDrawable drawable) { GL gl = drawable.getGL(); /** * Set the background colour when the GLDrawable * is cleared */ gl.glClearColor( 1.0f, 1.0f, 1.0f, 1.0f ); //white } /** * Executed if the associated GLDrawable is resized */ public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL gl = drawable.getGL(); GLU glu = new GLU(); gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(-2, 2, -2, 2, -4, 4); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); gl.glEnable(GL.GL_DEPTH_TEST); } /** This method handles the painting of the GLDrawable */ public void display(GLAutoDrawable drawable) { float[] teapotMat = {0.2f, 0.9f, 0.2f, 0.5f}; // The material for the teapot. float[] lightpos = {-4f, 0.0f, 4.0f, 1.0f}; // This is where the light source goes. GL gl = drawable.getGL(); // Tell it to use Gouraud shading. gl.glShadeModel(GL.GL_SMOOTH); gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); // Switch on the light. gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, lightpos, 0); gl.glEnable(GL.GL_LIGHTING); gl.glEnable(GL.GL_LIGHT0); // Set the material gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, teapotMat, 0); gl.glPushMatrix(); // Here are some random transformations to uncomment. //gl.glTranslatef(-1.0f,-1.0f,-1.0f); gl.glRotatef(45, 1,0,0); //gl.glRotatef(-90, 1, 1,1); //gl.glScalef(0.5f,-1,1); // Draws a teapot ... GLUT glut = new GLUT(); glut.glutSolidTeapot(1); gl.glPopMatrix(); } public void keyTyped(KeyEvent evt){ } public void keyReleased(KeyEvent evt){ } public void keyPressed(KeyEvent evt){ if(evt.getKeyChar() == 'q') dispose(); } /** This method handles things if display depth changes */ public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged){ } }