Guest User

Untitled

a guest
Mar 27th, 2019
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.64 KB | None | 0 0
  1.  
  2. import java.util.HashMap;
  3.  
  4. /*
  5.  * Copyright (c) 2002-2012 LWJGL Project
  6.  * All rights reserved.
  7.  *
  8.  * Redistribution and use in source and binary forms, with or without
  9.  * modification, are permitted provided that the following conditions are
  10.  * met:
  11.  *
  12.  * * Redistributions of source code must retain the above copyright
  13.  *   notice, this list of conditions and the following disclaimer.
  14.  *
  15.  * * Redistributions in binary form must reproduce the above copyright
  16.  *   notice, this list of conditions and the following disclaimer in the
  17.  *   documentation and/or other materials provided with the distribution.
  18.  *
  19.  * * Neither the name of 'LWJGL' nor the names of
  20.  *   its contributors may be used to endorse or promote products derived
  21.  *   from this software without specific prior written permission.
  22.  *
  23.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  25.  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  26.  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  27.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  28.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  29.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  30.  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  31.  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  32.  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  33.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34.  */
  35.  
  36. /**
  37. * A highly accurate sync method that continually adapts to the system
  38. * it runs on to provide reliable results.
  39. *
  40. * @author Riven
  41. * @author kappaOne
  42. */
  43. public class Sync {
  44.  
  45.     /** number of nano seconds in a second */
  46.     private static final long NANOS_IN_SECOND = 1000L * 1000L * 1000L;
  47.  
  48.     /** The time to sleep/yield until the next frame */
  49.     private static HashMap<Thread,Long> nextFrameMap;
  50.    
  51.     /** whether the initialisation code has run */
  52.     private static HashMap<Thread,Boolean> initialisedMap;
  53.    
  54.     /** for calculating the averages the previous sleep/yield times are stored */
  55.     private static HashMap<Thread,RunningAvg> sleepDurationsMap;
  56.     private static HashMap<Thread,RunningAvg> yieldDurationsMap;
  57.    
  58.     /** initialise above fields */
  59.     static {
  60.         nextFrameMap = new HashMap<Thread,Long>();
  61.         initialisedMap = new HashMap<Thread,Boolean>();
  62.         sleepDurationsMap = new HashMap<Thread,RunningAvg>();
  63.         yieldDurationsMap = new HashMap<Thread,RunningAvg>();
  64.     }
  65.    
  66.    
  67.     /**
  68.      * An accurate sync method that will attempt to run at a constant frame rate.
  69.      * It should be called once every frame.
  70.      *
  71.      * @param fps - the desired frame rate, in frames per second
  72.      */
  73.     public static void sync(int fps) {
  74.         Thread c = checkThread();
  75.         if (fps <= 0) return;
  76.         if (!initialisedMap.get(c)) initialise();
  77.        
  78.         Long nextFrame = nextFrameMap.get(c);
  79.         RunningAvg sleepDurations = sleepDurationsMap.get(c);
  80.         RunningAvg yieldDurations = yieldDurationsMap.get(c);
  81.        
  82.         try {
  83.             // sleep until the average sleep time is greater than the time remaining till nextFrame
  84.             for (long t0 = getTime(), t1; (nextFrame - t0) > sleepDurations.avg(); t0 = t1) {
  85.                 Thread.sleep(2);
  86.                 sleepDurations.add((t1 = getTime()) - t0); // update average sleep time
  87.             }
  88.    
  89.             // slowly dampen sleep average if too high to avoid yielding too much
  90.             sleepDurations.dampenForLowResTicker();
  91.    
  92.             // yield until the average yield time is greater than the time remaining till nextFrame
  93.             for (long t0 = getTime(), t1; (nextFrame - t0) > yieldDurations.avg(); t0 = t1) {
  94.                 Thread.yield();
  95.                 yieldDurations.add((t1 = getTime()) - t0); // update average yield time
  96.             }
  97.         } catch (InterruptedException e) {
  98.             //
  99.         }
  100.        
  101.         // schedule next frame, drop frame(s) if already too late for next frame
  102.         nextFrameMap.put(c, Math.max(nextFrame + NANOS_IN_SECOND / fps, getTime()));
  103.     }
  104.    
  105.     private static Thread checkThread() {
  106.         Thread c = Thread.currentThread();
  107.  
  108.         if ( !nextFrameMap.containsKey(c) )
  109.             nextFrameMap.put(c, (long) 0);
  110.        
  111.         if ( !initialisedMap.containsKey(c) )
  112.             initialisedMap.put(c, false);
  113.        
  114.         if ( !sleepDurationsMap.containsKey(c) )
  115.             sleepDurationsMap.put(c, new RunningAvg(10));
  116.        
  117.         if ( !yieldDurationsMap.containsKey(c) )
  118.             yieldDurationsMap.put(c, new RunningAvg(10));
  119.  
  120.         return c;
  121.     }
  122.  
  123.     /**
  124.      * This method will initialise the sync method by setting initial
  125.      * values for sleepDurations/yieldDurations and nextFrame.
  126.      *
  127.      * If running on windows it will start the sleep timer fix.
  128.      */
  129.     private static void initialise() {
  130.         Thread c = checkThread();
  131.        
  132.         initialisedMap.put(c,true);
  133.        
  134.         sleepDurationsMap.get(c).init(1000 * 1000);
  135.         yieldDurationsMap.get(c).init((int) (-(getTime() - getTime()) * 1.333));
  136.        
  137.         nextFrameMap.put(c, getTime());
  138.        
  139.         String osName = System.getProperty("os.name");
  140.        
  141.         if (osName.startsWith("Win")) {
  142.             // On windows the sleep functions can be highly inaccurate by
  143.             // over 10ms making in unusable. However it can be forced to
  144.             // be a bit more accurate by running a separate sleeping daemon
  145.             // thread.
  146.             Thread timerAccuracyThread = new Thread(new Runnable() {
  147.                 public void run() {
  148.                     try {
  149.                         Thread.sleep(Long.MAX_VALUE);
  150.                     } catch (Exception e) {}
  151.                 }
  152.             });
  153.            
  154.             timerAccuracyThread.setName("LWJGL Timer");
  155.             timerAccuracyThread.setDaemon(true);
  156.             timerAccuracyThread.start();
  157.         }
  158.     }
  159.  
  160.     /**
  161.      * Get the system time in nano seconds
  162.      *
  163.      * @return will return the current time in nano's
  164.      */
  165.     private static long getTime() {
  166.         return System.nanoTime();
  167.     }
  168.  
  169.     private static class RunningAvg {
  170.         private final long[] slots;
  171.         private int offset;
  172.        
  173.         private static final long DAMPEN_THRESHOLD = 10 * 1000L * 1000L; // 10ms in nanoseconds
  174.         private static final float DAMPEN_FACTOR = 0.9f; // don't change: 0.9f is exactly right!
  175.  
  176.         public RunningAvg(int slotCount) {
  177.             this.slots = new long[slotCount];
  178.             this.offset = 0;
  179.         }
  180.  
  181.         public void init(long value) {
  182.             while (this.offset < this.slots.length) {
  183.                 this.slots[this.offset++] = value;
  184.             }
  185.         }
  186.  
  187.         public void add(long value) {
  188.             this.slots[this.offset++ % this.slots.length] = value;
  189.             this.offset %= this.slots.length;
  190.         }
  191.  
  192.         public long avg() {
  193.             long sum = 0;
  194.             for (int i = 0; i < this.slots.length; i++) {
  195.                 sum += this.slots[i];
  196.             }
  197.             return sum / this.slots.length;
  198.         }
  199.        
  200.         public void dampenForLowResTicker() {
  201.             if (this.avg() > DAMPEN_THRESHOLD) {
  202.                 for (int i = 0; i < this.slots.length; i++) {
  203.                     this.slots[i] *= DAMPEN_FACTOR;
  204.                 }
  205.             }
  206.         }
  207.     }
  208. }
Advertisement
Add Comment
Please, Sign In to add comment