Advertisement
codeanticode

Untitled

Feb 22nd, 2012
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.22 KB | None | 0 0
  1. package p5.test_awt_applet;
  2.  
  3. import java.applet.Applet;
  4. import java.awt.Frame;
  5. import java.awt.GraphicsDevice;
  6. import java.awt.GraphicsEnvironment;
  7. import java.awt.Insets;
  8. import java.awt.event.WindowAdapter;
  9. import java.awt.event.WindowEvent;
  10. import java.util.Timer;
  11. import java.util.TimerTask;
  12.  
  13. import javax.media.opengl.*;
  14. import javax.media.opengl.awt.GLCanvas;
  15. import com.jogamp.opengl.util.AnimatorBase;
  16.  
  17. public class MiniPApplet extends Applet {
  18.   private static final long serialVersionUID = 1L;
  19.  
  20.   /////////////////////////////////////////////////////////////
  21.   //
  22.   // Test parameters  
  23.  
  24.   public int frameRate = 120;
  25.   public boolean printThreadInfo = false;
  26.   public boolean restartCanvas = true;
  27.   public boolean resizeableFrame = false;
  28.  
  29.   /////////////////////////////////////////////////////////////
  30.   //
  31.   // Internal variables
  32.  
  33.   private Frame frame;
  34.   private GLProfile profile;
  35.   private GLCapabilities capabilities;
  36.   private GLCanvas canvas;
  37.  
  38.   private SimpleListener listener;
  39.   private CustomAnimator animator;
  40.  
  41.   private long beforeTime;
  42.   private long overSleepTime;
  43.   private long frameRatePeriod = 1000000000L / frameRate;
  44.  
  45.   private boolean initialized = false;  
  46.  
  47.   private double theta = 0;
  48.   private double s = 0;
  49.   private double c = 0;  
  50.  
  51.   private long millisOffset;
  52.   private int fcount, lastm;
  53.   private float frate;
  54.   private int fint = 3;
  55.  
  56.   void run() {
  57.     Thread loop = new Thread("Animation Thread") {
  58.       public void run() {
  59.         int frameCount = 0;
  60.         while (true) {          
  61.           if (!initialized) {
  62.             setup();            
  63.           }
  64.          
  65.           if (restartCanvas && 300 == frameCount) {
  66.             restart();
  67.           }
  68.          
  69.           animator.requestRender();
  70.          
  71.           clock();
  72.          
  73.           frameCount++;
  74.         }
  75.       }
  76.     };
  77.     loop.start();        
  78.   }
  79.  
  80.   void setup() {
  81.     if (printThreadInfo) System.out.println("Current thread at setup(): " + Thread.currentThread());
  82.    
  83.     millisOffset = System.currentTimeMillis();    
  84.  
  85.     // Frame setup ----------------------------------------------------------
  86.    
  87.     GraphicsEnvironment environment =
  88.       GraphicsEnvironment.getLocalGraphicsEnvironment();
  89.     GraphicsDevice displayDevice = environment.getDefaultScreenDevice();
  90.     frame = new Frame(displayDevice.getDefaultConfiguration());
  91.    
  92.     frame.setLayout(null);
  93.     frame.setTitle("MiniPApplet");
  94.     frame.pack();
  95.     frame.setResizable(resizeableFrame);
  96.    
  97.     Insets insets = frame.getInsets();
  98.     int windowW = 300 + insets.left + insets.right;
  99.     int windowH = 300 + insets.top + insets.bottom;
  100.     int locationX = 100;
  101.     int locationY = 100;
  102.    
  103.     frame.setSize(windowW, windowH);    
  104.     frame.setLocation(locationX, locationY);  
  105.    
  106.     frame.add(this);
  107.     frame.addWindowListener(new WindowAdapter() {
  108.       public void windowClosing(WindowEvent e) {
  109.           System.exit(0);
  110.       }
  111.     });    
  112.    
  113.     int usableWindowH = windowH - insets.top - insets.bottom;
  114.     this.setBounds((windowW - 300)/2, insets.top + (usableWindowH - 300)/2, 300, 300);
  115.    
  116.     frame.setVisible(true);
  117.  
  118.     // Canvas setup ----------------------------------------------------------
  119.    
  120.     profile = GLProfile.getMaxFixedFunc();
  121.     capabilities = new GLCapabilities(profile);
  122.     capabilities.setSampleBuffers(false);
  123.    
  124.     canvas = new GLCanvas(capabilities);
  125.     canvas.setBounds(0, 0, 300, 300);
  126.    
  127.     this.add(canvas);
  128.    
  129.     // Setting up animation
  130.     listener = new SimpleListener();
  131.     canvas.addGLEventListener(listener);
  132.     animator = new CustomAnimator(canvas);
  133.     animator.setThreadName("OpenGL");
  134.     animator.start();
  135.    
  136.     initialized = true;    
  137.   }
  138.  
  139.   void restart() {
  140.     System.out.println("Restarting surface...");
  141.    
  142.     // Stopping animation, removing current canvas.
  143.     animator.stop();
  144.     animator.remove(canvas);    
  145.     canvas.removeGLEventListener(listener);
  146.     this.remove(canvas);    
  147.        
  148.     capabilities = new GLCapabilities(profile);
  149.     capabilities.setSampleBuffers(true);
  150.     capabilities.setNumSamples(4);
  151.    
  152.     canvas = new GLCanvas(capabilities);
  153.     canvas.setBounds(0, 0, 300, 300);
  154.    
  155.     // Setting up animation again
  156.     this.add(canvas);
  157.     canvas.addGLEventListener(listener);
  158.     animator.add(canvas);
  159.     animator.start();
  160.    
  161.     System.out.println("Done");
  162.   }
  163.  
  164.   void draw(GL2 gl) {
  165.     if (printThreadInfo) System.out.println("Current thread at draw(): " + Thread.currentThread());          
  166.    
  167.     gl.glClearColor(0, 0, 0, 1);
  168.     gl.glClear(GL.GL_COLOR_BUFFER_BIT);
  169.    
  170.     theta += 0.01;
  171.     s = Math.sin(theta);
  172.     c = Math.cos(theta);      
  173.    
  174.     gl.glBegin(GL.GL_TRIANGLES);
  175.     gl.glColor3f(1, 0, 0);
  176.     gl.glVertex2d(-c, -c);
  177.     gl.glColor3f(0, 1, 0);
  178.     gl.glVertex2d(0, c);
  179.     gl.glColor3f(0, 0, 1);
  180.     gl.glVertex2d(s, -s);
  181.     gl.glEnd();    
  182.    
  183.     gl.glFlush();
  184.    
  185.     fcount += 1;
  186.     int m = (int) (System.currentTimeMillis() - millisOffset);
  187.     if (m - lastm > 1000 * fint) {
  188.       frate = (float)(fcount) / fint;
  189.       fcount = 0;
  190.       lastm = m;
  191.       System.err.println("fps: " + frate);
  192.     }    
  193.   }
  194.  
  195.   void clock() {
  196.     long afterTime = System.nanoTime();
  197.     long timeDiff = afterTime - beforeTime;
  198.     long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime;
  199.  
  200.     if (sleepTime > 0) {  // some time left in this cycle
  201.       try {
  202.         Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L));
  203.       } catch (InterruptedException ex) { }
  204.  
  205.       overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
  206.  
  207.     } else {    // sleepTime <= 0; the frame took longer than the period
  208.       overSleepTime = 0L;
  209.     }
  210.  
  211.     beforeTime = System.nanoTime();    
  212.   }  
  213.  
  214.   class SimpleListener implements GLEventListener {
  215.     @Override
  216.     public void display(GLAutoDrawable drawable) {
  217.       draw(drawable.getGL().getGL2());
  218.     }
  219.  
  220.     @Override
  221.     public void dispose(GLAutoDrawable drawable) { }
  222.  
  223.     @Override
  224.     public void init(GLAutoDrawable drawable) { }
  225.  
  226.     @Override
  227.     public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { }    
  228.   }
  229.  
  230.   public static void main(String[] args) {
  231.     MiniPApplet mini;
  232.     try {
  233.       Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(MiniPApplet.class.getName());
  234.       mini = (MiniPApplet) c.newInstance();
  235.     } catch (Exception e) {
  236.       throw new RuntimeException(e);
  237.     }    
  238.     if (mini != null) {
  239.       mini.run();
  240.     }
  241.   }      
  242.  
  243.   /** An Animator subclass which renders one frame at the time
  244.    *  upon calls to the requestRender() method.
  245.    **/
  246.   public class CustomAnimator extends AnimatorBase {    
  247.       private Timer timer = null;
  248.       private TimerTask task = null;
  249.       private String threadName = null;
  250.       private volatile boolean shouldRun;
  251.  
  252.       protected String getBaseName(String prefix) {
  253.           return "Custom" + prefix + "Animator" ;
  254.       }
  255.  
  256.       /** Creates an CustomAnimator with an initial drawable to
  257.        * animate. */
  258.       public CustomAnimator(GLAutoDrawable drawable) {
  259.           if (drawable != null) {
  260.               add(drawable);
  261.           }
  262.       }
  263.      
  264.       public void setThreadName(String name) {
  265.         threadName = name;
  266.       }
  267.  
  268.       public synchronized void requestRender() {
  269.           shouldRun = true;
  270.       }
  271.  
  272.       public final boolean isStarted() {
  273.           stateSync.lock();
  274.           try {
  275.               return (timer != null);
  276.           } finally {
  277.               stateSync.unlock();
  278.           }
  279.       }
  280.  
  281.       public final boolean isAnimating() {
  282.           stateSync.lock();
  283.           try {
  284.               return (timer != null) && (task != null);
  285.           } finally {
  286.               stateSync.unlock();
  287.           }
  288.       }
  289.  
  290.       private void startTask() {
  291.           if(null != task) {
  292.               return;
  293.           }
  294.          
  295.           task = new TimerTask() {
  296.               private boolean firstRun = true;
  297.               public void run() {
  298.                   if (firstRun) {
  299.                     if (threadName != null) Thread.currentThread().setName(threadName);
  300.                     firstRun = false;
  301.                   }
  302.                   if(CustomAnimator.this.shouldRun) {
  303.                      CustomAnimator.this.animThread = Thread.currentThread();
  304.                       // display impl. uses synchronized block on the animator instance
  305.                       display();                
  306.                       synchronized (this) {
  307.                         // done with current frame.
  308.                         shouldRun = false;
  309.                       }                    
  310.                   }
  311.               }
  312.           };
  313.  
  314.           fpsCounter.resetFPSCounter();
  315.           shouldRun = false;
  316.          
  317.           timer.schedule(task, 0, 1);
  318.       }
  319.      
  320.       public synchronized boolean  start() {
  321.           if (timer != null) {
  322.               return false;
  323.           }
  324.           stateSync.lock();
  325.           try {
  326.               timer = new Timer();
  327.               startTask();
  328.           } finally {
  329.               stateSync.unlock();
  330.           }
  331.           return true;
  332.       }
  333.  
  334.       /** Stops this CustomAnimator. */
  335.       public synchronized boolean stop() {
  336.           if (timer == null) {
  337.               return false;
  338.           }
  339.           stateSync.lock();
  340.           try {
  341.               shouldRun = false;
  342.               if(null != task) {
  343.                   task.cancel();
  344.                   task = null;
  345.               }
  346.               if(null != timer) {
  347.                   timer.cancel();
  348.                   timer = null;
  349.               }
  350.               animThread = null;
  351.               try {
  352.                   Thread.sleep(20); // ~ 1/60 hz wait, since we can't ctrl stopped threads
  353.               } catch (InterruptedException e) { }
  354.           } finally {
  355.               stateSync.unlock();
  356.           }
  357.           return true;
  358.       }
  359.      
  360.       public final boolean isPaused() { return false; }
  361.       public synchronized boolean resume() { return false; }
  362.       public synchronized boolean pause() { return false; }    
  363.   }
  364. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement