Advertisement
codeanticode

Untitled

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