Advertisement
codeanticode

Untitled

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