Advertisement
codeanticode

Untitled

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