Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (476)
Games in Android Showcase (106)
games submitted by our members
Games in WIP (532)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Game Loop runs slow in Mac OS X  (Read 266 times)
0 Members and 1 Guest are viewing this topic.
Offline Jikid

Innocent Bystander





« Posted 2013-08-19 08:37:20 »

I'm reading the book 'Killer Game Programming in Java' by Andrew Davison. The animation framwork example in Chapter 2, takes less than 20fps on my Macbook pro 15' Retina with Java 1.6.0 installed. However, the code runs perfectly on my old P4 pc with WinXP.. The example uses Java 3D timer, and active rendering with method paintScreen() instead of repaint()
It seems that the JPanel's size has great impact on the fps, as a JPanel with size of (1280, 800) is much slower than one of (400, 300). I've google that but couldn't get any specific answer, and I did try the following setting of Properties, but It didn't work either.
1  
System.setProperty("apple.awt.graphics.UseQuartz","true"); System.setProperty("apple.awt.graphics.EnableQ2DX","true");

Here is the code just for reference as most of them is not relevant to the problem. I think it's something to do with the java rendering setting on Mac OS X. Thank you in advance!
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
314  
315  
316  
317  
318  
319  
320  
321  
322  
323  
324  
325  
326  
327  
328  
329  
330  
331  
332  
333  
334  
335  
336  
337  
338  
339  
340  
341  
342  
343  
344  
345  
346  
347  
348  
349  
350  
351  
352  
353  
354  
355  
356  
357  
358  
359  
360  
361  
362  
363  
364  
365  
366  
367  
368  
369  
370  
371  
372  
373  
374  
375  
376  
377  
378  
379  
380  
381  
382  
383  
384  
385  
386  
387  
388  
389  
390  
391  
392  
393  
394  
395  
396  
397  
398  
399  
400  
401  
402  
403  
404  
405  
406  
407  
408  
409  
410  
411  
412  
413  
414  
415  
416  
417  
418  
419  
420  
421  
422  
423  
424  
425  
426  
427  
428  
429  
430  
431  
432  
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Toolkit;
import java.text.DecimalFormat;
import com.sun.j3d.utils.timer.J3DTimer;

public class Framework
{
    public static void main(String[] args)
    {
        new Framework().go();
    }

    public void go()
    {
        JFrame frame = new JFrame("Animation Framework");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GamePanel mainPanel = new GamePanel(this, 16L * 1000000L);
        frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
    }
}

public class GamePanel extends JPanel implements Runnable
{
    // size of panel
   private static final int PWIDTH = 1024;
    private static final int PHEIGHT = 768;

    // number of frames with delay of 0 ms before the animated thread yields to others
   private static final int NO_DELAYS_PER_YIELD = 16;

    // number of frames that can be skipped in any one animation loop
   // i.e the games's state is updated but not rendered
   private static final int MAX_FRAME_SKIPS = 5;

    // number of FPS stored to get an average
   private static final int NUM_FPS = 10;

    // unit change
   private static final double S2NS_D = 1000000000.0;
    private static final long S2NS_L = 1000000000L;
    private static final double MS2NS_D = 1000000.0;
    private static final long MS2NS_L = 1000000L;

    // record stats every 1 second(roughly)
   private static final long MAX_STATS_INTERVAL = S2NS_L;

    // used for gathering statistics
   // in nanoseconds
   private long statsInterval = 0L;
    private long prevStatsTime;  
    private long totalElapsedTime = 0L;
    private long gameStartTime;
    // in seconds
   private double timeSpentInGame = 0;

    private long frameCount = 0;
    private double[] fpsStore;
    private long statsCount = 0;
    private double averageFPS = 0.0;

    private long framesSkipped = 0L;
    private long totalFramesSkipped = 0L;
    private double[] upsStore;
    private double averageUPS = 0.0;

    private DecimalFormat df = new DecimalFormat("0.##");
    private DecimalFormat timedf = new DecimalFormat("0.####");

    // for the animation
   private Thread animator;

    private Framework top;

    // period between drawing in nanoseconds
   private long period = 16L * MS2NS_L;

    // stop the animation
   private volatile boolean running = false;
    // for the game termination
   private volatile boolean gameOver = false;
    // pause the game
   private volatile boolean isPaused = false;

    // global variables for off-screen rendering
   private Graphics dbg;
    private Image dbImage = null;

    public GamePanel(Framework top, long period)
    {
        this.top = top;
        this.period = period;

        setBackground(Color.red);
        setPreferredSize(new Dimension(PWIDTH, PHEIGHT));
        //setSize(PWIDTH, PHEIGHT);

        setFocusable(true);
        // JPanel now receives key events
       requestFocusInWindow();
        readyForTermination();

        // create game components
       // ..

        // listen for mouse presses
       addMouseListener( new MouseAdapter() {
            public void mousePressed(MouseEvent e)
            {
                testPress(e.getX(), e.getY());
            }
        });

        // initialise timing elements
       fpsStore = new double[NUM_FPS];
        upsStore = new double[NUM_FPS];
        for (int i = 0; i < NUM_FPS; i++)
        {
            fpsStore[i] = 0.0;
            upsStore[i] = 0.0;
        }
    }

    // wait for the JPanel to be added to the JFrame/JApplet before starting
   public void addNotify()
    {
        // create the peer
       super.addNotify();
        // start the thread
       startGame();
    }

    // initialize and start the thread
   private void startGame()
    {
        if (animator == null || !running)
        {
            animator = new Thread(this);
            animator.start();
        }
    }

    // called by the user to stop execution
   public void stopGame()
    {
        running = false;
    }

    // called by the user to pause
   public void pauseGame()
    {
        isPaused = true;
    }

    // called by the user to resume
   public void resumeGame()
    {
        isPaused = false;
    }

    // is (x, y) important to this game?
   private void testPress(int x, int y)
    {
        if (!gameOver && !isPaused)
        {
        }
    }

    private void readyForTermination()
    {
        addKeyListener( new KeyAdapter() {
            // listen for esc, q, end, ctrl-c
           public void keyPressed(KeyEvent e)
            {
                int keyCode = e.getKeyCode();
                if (keyCode == KeyEvent.VK_ESCAPE ||
                    keyCode == KeyEvent.VK_Q ||
                    keyCode == KeyEvent.VK_END ||
                    keyCode == KeyEvent.VK_C && e.isControlDown())
                {
                    running = false;
                }

                if (keyCode == KeyEvent.VK_P)
                {
                    pauseGame();
                }

                if (keyCode == KeyEvent.VK_R)
                {
                    resumeGame();
                }
            }
        });
    }

    // repeatedly update, render, sleep so loop takes close to period ms.
   // sleep inaccuracies are handled.
   // overruns in update/renders will cause extra updates to be carried out.
   // so UPS ~= requested FPS.
   public void run()
    {
        long beforeTime, afterTime, timeDiff, sleepTime;
        long overSleepTime = 0L;
        int noDelays = 0;
        long excess = 0L;

        gameStartTime = J3DTimer.getValue();
        prevStatsTime = gameStartTime;
        beforeTime = gameStartTime;

        running = true;
        while (running)
        {
            // game state is updated
           gameUpdate();
            // render to a buffer
           gameRender();
           
            /*
            // request painting with the buffer
            repaint();
            */


            // draw buffer to screen
           paintScreen();

            afterTime = J3DTimer.getValue();
            timeDiff = afterTime - beforeTime;
            sleepTime = (period - timeDiff) - overSleepTime;

            if (sleepTime > 0)
            {
                try
                {
                    // sleep a bit in millisecond
                   Thread.sleep((long)((double)sleepTime / MS2NS_D + 0.5));
                }
                catch (InterruptedException ex)
                {}

                overSleepTime = (J3DTimer.getValue() - afterTime) - sleepTime;
            }
            else
            {
                // sleepTime <= 0; frame took longer than the period
               overSleepTime = 0L;
                // store excess time value
               excess -= sleepTime;

                if (++noDelays >= NO_DELAYS_PER_YIELD)
                {
                    // give another thread a chance to run
                   Thread.yield();
                    noDelays = 0;
                }
            }

            beforeTime = J3DTimer.getValue();

            // if frame animation is taking too long, update the game state without rendering it,
           // to get the updates/sec nearer to the required FPS
           int skips = 0;
            while (excess > period && skips < MAX_FRAME_SKIPS)
            {
                excess -= period;
                // udpate state without rendering
               gameUpdate();
                skips++;
            }

            framesSkipped += skips;
            storeStats();
        }

        printStats();
        // so enclosing JFrame/JApplet exits
       System.exit(0);
    }

    private void gameUpdate()
    {
        if (!gameOver && !isPaused)
        {
        }
    }

    // draw the current frame to an image buffer
   private void gameRender()
    {
        // create the buffer
       if (dbImage == null)
        {
            dbImage = createImage(PWIDTH, PHEIGHT);
            if (dbImage == null)
            {
                System.out.println("dbImage is null");
                return;
            }
        }

        dbg = dbImage.getGraphics();

        // clear the background
       dbg.setColor(Color.black);
        dbg.fillRect(0, 0, PWIDTH / 2, PHEIGHT / 2);

        // draw game elements
       // ..

        if (gameOver)
        {
            gameOverMessage(dbg);
        }
    }

    // center the game-over message
   private void gameOverMessage(Graphics g)
    {
        //g.drawString(msg, x, y);
   }

    // actively render the buffer image to the screen
   private void paintScreen()
    {
        Graphics g;

        try
        {
            // the panel's graphics context must be freshly obtained
           // each time it's needed, as it may be changed bye the JVM
           g = this.getGraphics();
            if (g != null && dbImage != null)
            {
                g.drawImage(dbImage, 0, 0, null);
            }
            // syn the display on some systems(i.e. Linux)
           Toolkit.getDefaultToolkit().sync();
            g.dispose();
        }
        catch (Exception e)
        {
            System.out.println("Graphics context error: " + e);
        }
    }

    private void storeStats()
    {
        ++frameCount;
        statsInterval += period;

        if (statsInterval >= MAX_STATS_INTERVAL)
        {
            long timeNow = J3DTimer.getValue();
            timeSpentInGame = (double)(timeNow - gameStartTime) / S2NS_D;

            // time since last stats collection
           long realElapsedTime = timeNow - prevStatsTime;
            totalElapsedTime += realElapsedTime;

            double timingErr = (double)(realElapsedTime - statsInterval) / (double)statsInterval *
                100.0;

            totalFramesSkipped += framesSkipped;

            double actualFPS = 0.0;
            double actualUPS = 0.0;

            if (totalElapsedTime > 0)
            {
                actualFPS = (double)frameCount / totalElapsedTime * S2NS_D;
                actualUPS = (double)(frameCount + totalFramesSkipped) / totalElapsedTime * S2NS_D;
            }

            // store the latest FPS and UPS
           fpsStore[(int)statsCount % NUM_FPS] = actualFPS;
            upsStore[(int)statsCount % NUM_FPS] = actualUPS;
            ++statsCount;

            double totalFPS = 0.0;
            double totalUPS = 0.0;
            for (int i = 0; i < NUM_FPS; i++)
            {
                totalFPS += fpsStore[i];
                totalUPS += upsStore[i];
            }

            if (statsCount < NUM_FPS)
            {
                assert(statsCount > 0);
                averageFPS = totalFPS / statsCount;
                averageUPS = totalUPS / statsCount;
            }
            else
            {
                averageFPS = totalFPS / NUM_FPS;
                averageUPS = totalUPS / NUM_FPS;
            }

            System.out.println(timedf.format((double)statsInterval / S2NS_D) + "s " +
                               timedf.format((double)realElapsedTime / S2NS_D) + "s " +
                               df.format(timingErr) + "% " + frameCount + "c " +
                               framesSkipped + "/" + totalFramesSkipped + " skips; " +
                               df.format(actualFPS) + " " + df.format(averageFPS) + " afps; " +
                               df.format(actualUPS) + " " + df.format(averageUPS) + " aups");

            framesSkipped = 0;
            prevStatsTime = timeNow;
            statsInterval = 0L;
        }
    }

    private void printStats()
    {
        System.out.println("Frame Count/Loss: " + frameCount + " / " + totalFramesSkipped);
   System.out.println("Average FPS: " + df.format(averageFPS));
   System.out.println("Average UPS: " + df.format(averageUPS));
        System.out.println("Time Spent: " + timeSpentInGame + " secs");
    }
}
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

pw (16 views)
2014-07-24 01:59:36

Riven (16 views)
2014-07-23 21:16:32

Riven (14 views)
2014-07-23 21:07:15

Riven (16 views)
2014-07-23 20:56:16

ctomni231 (43 views)
2014-07-18 06:55:21

Zero Volt (40 views)
2014-07-17 23:47:54

danieldean (32 views)
2014-07-17 23:41:23

MustardPeter (36 views)
2014-07-16 23:30:00

Cero (51 views)
2014-07-16 00:42:17

Riven (50 views)
2014-07-14 18:02:53
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!