Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2 3 ... 5
  ignore  |  Print  
  Reasons why Java is not a good language for game development  (Read 25303 times)
0 Members and 1 Guest are viewing this topic.
Offline mgianota

Senior Newbie





« Posted 2008-11-12 05:07:23 »

After having read kev's post on reasons why Java is a good development choice for game programming I felt it necessary to balance things out with a list of reasons why Java is not a good choice.

[1] Native libs. Currently the only way to get decent graphics performance is to use native libraries. Native libraries such as LWJGL rely on the fact that the player has a decent video card, otherwise the library won't even open up a window. Most PCs have low-end video cards in them.

[2] Java2D's performance is awful. Even when using the hardware accelerated graphics you still find that the game's main loop stutters and lags.

[3] Bloated API. Many method names and class names are stupidly, anally long. For example, how many times have you had to type System.out.println("some string");? This is a ridiculous amount of typing for such a simple task.

[4] The garbage collector makes games slow and unpredictable. Good time management is a crucial aspect of any game. When you think about it a large chunk of the playability tuning that goes on in game development comes down to adjusting the timed appearance of game objects such as aliens and other moving objects. For a large game, the garbage collector makes it nearly impossible to perform synchronised screen updates.

[5] Write once, run anywhere is a complete myth. It is write once, debug everywhere and if you are writing applets then that means testing it in IE, Mozilla & Opera running on a combination of Mac, Linux and Windows. Because of the run anywhere myth developers rarely take the time to produce different versions of their software tuned for different machines, something that happens in the C++ world all the time as a matter of routine.

[6] The lack of function pointers is a major pain in the arse. Having no closures is also a major pain. True, Java has anonymous inner-classes but anonymous inner-classes are ugly as Hell; they hang off your code in the editor like a wart.

[7] The security restrictions on applets have rendered them almost useless; you can't even read and write a temporary cache which means that games can't save state for the player. Games that force a player to revisit completed levels are a bit lame.

[8] Size. At 14.5Mb the Java runtime is a huge lump of code for a casual game to be dependant upon. Flash games use only a small 1.8Mb runtime.

That's it for now. I'm sure if I thought about it I could come up with a much longer list, but for the moment I think the above pretty much covers it for me. What are my top hates for programming games in Java? Number one is the stutter and lag closely followed by the garbage collector which cannot be switched off.

--Mario
Offline bobjob

JGO Knight


Medals: 10
Projects: 4


David Aaron Muhar


« Reply #1 - Posted 2008-11-12 07:48:43 »

[1] Native libraries such as LWJGL rely on the fact that the player has a decent video card
all modern video games rely heavily on the video card

Quote
[2] Java2D's performance is awful. Even when using the hardware accelerated graphics you still find that the game's main loop stutters and lags.
i wouldnt say awful but it can be a bit slow at times, if someone really wants to get performace out of java2D, there are ways such as using fullscreen exclusive mode. but your right for games, using Java2D probably isnt a good idea.

Quote
[3] Bloated API. Many method names and class names are stupidly, anally long. For example, how many times have you had to type System.out.println("some string");? This is a ridiculous amount of typing for such a simple task.
I dont see this as a problem as the library is very logical, and can help a new programer learn how to program without knowing every detail.
Programming isnt really a fluid motion, alot of time is spent thinking about what needs to be done. so its not like typing is a real restraint.

Quote
[4] The garbage collector makes games slow and unpredictable. Good time management is a crucial aspect of any game. When you think about it a large chunk of the playability tuning that goes on in game development comes down to adjusting the timed appearance of game objects such as aliens and other moving objects. For a large game, the garbage collector makes it nearly impossible to perform synchronised screen updates.
this is just not true. I have minimul problem maintaining the framerate. but if you find your having problems. Try calling System.gc() after loading, and quiting the realtime play part of the game. also dont load so many resources that java needs to find memory.

Quote
[5] Write once, run anywhere is a complete myth. It is write once, debug everywhere and if you are writing applets then that means testing it in IE, Mozilla & Opera running on a combination of Mac, Linux and Windows. Because of the run anywhere myth developers rarely take the time to produce different versions of their software tuned for different machines, something that happens in the C++ world all the time as a matter of routine.
Fair enough, you need to test the application on all platforms you plan to use it. But it is alot easyer in Java than any other lanuage, IMO. I havnt had any problems running my webstart apps on the three main OS's except for problems in 3th party libraries, which again i find very simple and somewhat fun to fix. Overcoming problems is actually very rewarding.

Quote
[6] The lack of function pointers is a major pain in the arse. Having no closures is also a major pain. True, Java has anonymous inner-classes but anonymous inner-classes are ugly as Hell; they hang off your code in the editor like a wart.
ok this is a little dramatic. but if thats really whats holding you back from programming games in java, then I guess its not a language you should use.

Quote
[7] The security restrictions on applets have rendered them almost useless; you can't even read and write a temporary cache which means that games can't save state for the player. Games that force a player to revisit completed levels are a bit lame.
certificates help, If you are not fimilar with them what they do is give you access to restricted resources. All the user needs to do is click "accept" problems solved. I personally would be scared of a web app that can use any resource via the internet.

Quote
[8] Size. At 14.5Mb the Java runtime is a huge lump of code for a casual game to be dependant upon. Flash games use only a small 1.8Mb runtime.
Depends on the quality of the game, if its a big project its hardly noticable. But your right for a simple game it is some what large, but then flash, also requires an install. But once installed it will never have to be done again, well at least not till an update  Tongue


There are a few impressive games that run really well in Java and i havnt found any problems with performance.
But If the user has an old computer then Yes there will probably be performance issues, and thats why it is great that games warn of specs before distrubition.

My Projects
Games, Webcam chat, Video screencast, PDF tools.

Javagaming.org with chat room
Offline kaffiene
« Reply #2 - Posted 2008-11-12 07:56:06 »

[1] Que??  All games ultimately rely on the GFX card.  You can write to OpenGL or window's GDI using Java just as well as in any other language.

[2] That's a good reason to use Open GL.  Nothing's stopping you accessing whatever native apps use via JNI.

[3] HAH!  I write games in C++ for a living, and if you think Java is verbose try using the STL!  I'd love to be able to use APIs as well designed as Java's in my game coding.

[4] So, you've not used incremental GC?  

"For a large game, the garbage collector makes it nearly impossible to perform synchronised screen updates."  Really?  You must be doing it wrong.

Also, with multiple core machines, you can have a non-incremental GC running on another core.

[5] Huh Nothing is stopping you from writing different versions for different targets using Java if you want to.  What Java has over c++ is the possibilitiy of getting something that runs on many platforms with much greater ease than any other system around.  Shit, we have enough trouble with our C++ code over different *service packs* of windows let alone being able to run it on Mac or Linux.

[6] Callbacks can be done with interfaces, and are much cleaner and more self documenting if they are.  But again, this is NOT a reason why Java sucks for games - its a minor asthetic difference.  Closures?  Nice, but again - syntactic sugar.  Anonymous inner classes are again just a code flavour.  Saying ANY of these are important issues really makes me wonder how many games you've shipped.

[7] Applets are how 99% of the Java games in the world are NOT delivered.

[8] That's been fixed in the most recent Java releases, I believe.  

Sorry dude, but I think your list is a load of crap.  I write games in C++ and it pays the bills, but it's nowhere the land of milk and honey that you seem to think it is.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline bienator

Senior Devvie




OutOfCoffeeException


« Reply #3 - Posted 2008-11-12 08:21:21 »

[3] you know static imports?
also try:
netbeans sout + tab
eclipse type syso + strg + space

edit:
[4] you can't expect to put load on a GC and get hard realtime behavior in general.

edit2:
[5] who told you you could write programs without testing in production environments?

edit3:
[6] you can eather (1) think about a language and constantly try to prevent not tracable bugs and security exploits (see buffer overflow) or (2) concentrate on the problem you actually want to solve. The combination: References + GC + simple syntax + a very good compiler which tells you exactly whats wrong leads to 2.

Offline kevglass

« JGO Spiffy Duke »


Medals: 212
Projects: 24
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #4 - Posted 2008-11-12 08:34:58 »

1 - LWJGL doesn't rely on a decent card, even the crappiest of the crap intel card gives you some OpenGL. The new Java2D pipeline is also dependent on having a decent graphics card and it performas pretty well now.

2 - See above, the Java 2D pipe is good. The problem is consistency. The performance on different platforms and different VMs varies so much that you can't rely on it. Thats why alot of us go to natives.

3 - Matter of taste really, personally I prefer explicit declaration over shotcuts, especially with modern IDEs where I don't have to type any of that anyway. If you want to shorten it a bit I think you could probably do:

1  
import static java.lang.System.out;


4 - Agreed. We still have to do some work to tidy up how bad the garbage collection can get (even with incremental GC) - but then I'd rather do that work that do the work and take the risk of managing the memory myself. I've never experienced the extent of the problems you describe but there are definitely plenty of issues here.

5 - Agreed, there's no doubt at all here. The myth that it "just works" on different platforms is a real pita. I don't see much need to tune to different platform (since our JVM does that for us) but the lack of testing is a real cause for concern. I worked for a company that believed they didn't need to test on anything but the development platform simply because they were using Java.

6 - Again matter of taste. I prefer interfaces for these things, function pointers are too low granularity for me.

7 - Agreed, applets are painful. To be fair, it is being worked on, but can't see that having an impact for a few years.

8 - Like kaffiene said, the Java Kernel project in the latest release is designed to fix that issue. If you're shipping your own VM you should be able to use the latest (reported as a 3MB kernel?).

I think you've got some valid points.

Kev

Offline EgonOlsen
« Reply #5 - Posted 2008-11-12 09:23:27 »

Quote from: mgianota
[1] Native libs. Currently the only way to get decent graphics performance is to use native libraries. Native libraries such as LWJGL rely on the fact that the player has a decent video card, otherwise the library won't even open up a window. Most PCs have low-end video cards in them.
And your point is...? My latest game (http://jpct.de/robombs.game) has an optional phone home/call back-function that sends some configuration details and a screen shot. Judging from that, the "native libs (lwjgl in this case)" work fine on Intel crapsets (810, 845, 965,...), on S3 Delta- and Unichrome chips and even on Riva TNT and Geforce2MX. How much lower than this can you get nowadays?

Quote from: mgianota
[2] Java2D's performance is awful. Even when using the hardware accelerated graphics you still find that the game's main loop stutters and lags.
Personally, i wouldn't use Java2D for games myself. It wasn't designed for games in the first place. However, i've seen games that use it and run very well, so it obviously IS possible.

Quote from: mgianota
[3] Bloated API. Many method names and class names are stupidly, anally long. For example, how many times have you had to type System.out.println("some string");? This is a ridiculous amount of typing for such a simple task.
In Eclipse: Type "syso", press CTRL+SPACE. Too much work for you?

Quote from: mgianota
[4] The garbage collector makes games slow and unpredictable. Good time management is a crucial aspect of any game. When you think about it a large chunk of the playability tuning that goes on in game development comes down to adjusting the timed appearance of game objects such as aliens and other moving objects. For a large game, the garbage collector makes it nearly impossible to perform synchronised screen updates.
That's just wrong. Garbage collection usually isn't a problem even on low end machines. Of course you have to take care of some things. If you don't, then it's simply "shit in - shit out".

Quote from: mgianota
[5] Write once, run anywhere is a complete myth. It is write once, debug everywhere and if you are writing applets then that means testing it in IE, Mozilla & Opera running on a combination of Mac, Linux and Windows. Because of the run anywhere myth developers rarely take the time to produce different versions of their software tuned for different machines, something that happens in the C++ world all the time as a matter of routine.
I've written Robombs on Windows. Once done, i tested it on Mac (PPC and X86), Linux and even Solaris. It worked fine on all of them without changing anything. No need for different versions at all.

Quote from: mgianota
[6] The lack of function pointers is a major pain in the arse. Having no closures is also a major pain. True, Java has anonymous inner-classes but anonymous inner-classes are ugly as Hell; they hang off your code in the editor like a wart.
Just syntactical sugar that not even tastes sweet for everybody. You can always find a reason not to do something.

Quote from: mgianota
[7] The security restrictions on applets have rendered them almost useless; you can't even read and write a temporary cache which means that games can't save state for the player. Games that force a player to revisit completed levels are a bit lame.
Level codes would be a solution. However, i agree that applets suck.

Quote from: mgianota
[8] Size. At 14.5Mb the Java runtime is a huge lump of code for a casual game to be dependant upon. Flash games use only a small 1.8Mb runtime.
Size is an issue, but on the other hand, even the drivers(!) for my graphics cards are between 35 and 80mb and require the .NET runtime in addition.

Offline Mr_Light

Senior Devvie


Medals: 1


shiny.


« Reply #6 - Posted 2008-11-12 09:31:47 »

[3] Can you come up with a better example, System.out.println(..); is what you use for console interaction. I almost never use that method, except for the occasional example code. For debugging use a debugger, for logging use a logger....   Lips Sealed

[4] Never really been a problem for me, even so the effort you have to invest to fix it pales by the required effort you create by removing it.

[5] yes though I must note that your overly enthusiastic picture about 'the other side'  also write once run everywhere was abandoned anyway. Have fun recompiling for 64bit have fun recompiling to take advantage of other architectural improvements. your slowing down innovation. But then again who cares, any non casual game only have a lifespan of what 4 years max?

[6] 'Meh'

[7] cookies, chocolate cookies  Smiley

[8] I don't know as said there is kernel project but biggest problem is ease of install and distracting toolbar and openoffice stuff update all being too intrusive. They started flirting with microsoft perhaps they can fix something windows update I don't know where that is going.
@ EgonOlsen, try HP's 135 mb print driver, I shit you not.

It's harder to read code than to write it. - it's even harder to write readable code.

The gospel of brother Riven: "The guarantee that all bugs are in *your* code is worth gold." Amen brother a-m-e-n.
Offline gouessej
« Reply #7 - Posted 2008-11-12 09:33:03 »

After having read kev's post on reasons why Java is a good development choice for game programming I felt it necessary to balance things out with a list of reasons why Java is not a good choice.
Have you been payed by Microsoft or Adobe to be so defeatist?

[1] Native libs. Currently the only way to get decent graphics performance is to use native libraries. Native libraries such as LWJGL rely on the fact that the player has a decent video card, otherwise the library won't even open up a window. Most PCs have low-end video cards in them.
JOGL works fine even with low-end video cards, I succeeded in playing with my own game with old onboard graphics supporting only OpenGL 1.2. It is even possible to open a frame with a simple canvas even with a graphics card supporting only OpenGL 1.1.

[2] Java2D's performance is awful. Even when using the hardware accelerated graphics you still find that the game's main loop stutters and lags.
It depends on the way you use it too.

[3] Bloated API. Many method names and class names are stupidly, anally long. For example, how many times have you had to type System.out.println("some string");? This is a ridiculous amount of typing for such a simple task.
If you don't like Java, nobody forces you to use it. In C#, it is almost the same (Console.WriteLine("...")Wink.

[4] The garbage collector makes games slow and unpredictable. Good time management is a crucial aspect of any game. When you think about it a large chunk of the playability tuning that goes on in game development comes down to adjusting the timed appearance of game objects such as aliens and other moving objects. For a large game, the garbage collector makes it nearly impossible to perform synchronised screen updates.
It is wrong. In the worst case, you can choose the maximum length of the pause caused by the garbage collector. If you were right, it would be impossible to write 3D games in Java. Jake2 and Avengina prove that you're completely wrong. Even on low end machines, I rarely have some problems of lag even with complex 3D scenes with collisions.

[5] Write once, run anywhere is a complete myth. It is write once, debug everywhere and if you are writing applets then that means testing it in IE, Mozilla & Opera running on a combination of Mac, Linux and Windows. Because of the run anywhere myth developers rarely take the time to produce different versions of their software tuned for different machines, something that happens in the C++ world all the time as a matter of routine.
Applet support is not very good but you can write heavy applications using Java Webstart, it is less buggy. It is very rarely required to adapt the Java source code to each platform.

[6] The lack of function pointers is a major pain in the arse. Having no closures is also a major pain. True, Java has anonymous inner-classes but anonymous inner-classes are ugly as Hell; they hang off your code in the editor like a wart.
Lol is it a joke? Closures and functions pointers are not very useful, you can easily write a game without them.

[7] The security restrictions on applets have rendered them almost useless; you can't even read and write a temporary cache which means that games can't save state for the player. Games that force a player to revisit completed levels are a bit lame.
I don't give the advice to create "true" games in applets, it is enough for casual games that don't need to suggest to save a party. Otherwise, use at least a signed applet. Some players might be afraid of it but if they trust you, if they really want to play with your game, they will test it even with the annoying security popup.

[8] Size. At 14.5Mb the Java runtime is a huge lump of code for a casual game to be dependant upon. Flash games use only a small 1.8Mb runtime.
850 000 000 desktop computers are already Java-enabled, it is not a problem.

That's it for now. I'm sure if I thought about it I could come up with a much longer list, but for the moment I think the above pretty much covers it for me. What are my top hates for programming games in Java? Number one is the stutter and lag closely followed by the garbage collector which cannot be switched off.
Do you really know how a pauseless garbage collection would work? You can already monitor a bit the garbage collection and you should choose data types that don't require frequent garbage collections. It is mostly a list of prejudices against Java, it is not very constructive. I'm fed up with this defeatism.

As a conclusion, I tell you all that I love cross-platform game programming with Java  Grin Keep cool. Yes we can!

Offline Mr_Light

Senior Devvie


Medals: 1


shiny.


« Reply #8 - Posted 2008-11-12 10:11:22 »

Have you been payed by Microsoft or Adobe to be so defeatist?

....

 I'm fed up with this defeatism.

Discussion is always good, know thyself is not a bad credo either. Identifying problems is the first step to solving them. etc  Wink

I think we don't want to come across as too harsh, feedback any feedback is important enough to be considered. Even if it where totally off-base perception is important too. You actually need ppl to come into your shop before you can sell them anything ey?

It's harder to read code than to write it. - it's even harder to write readable code.

The gospel of brother Riven: "The guarantee that all bugs are in *your* code is worth gold." Amen brother a-m-e-n.
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #9 - Posted 2008-11-12 10:47:07 »

Don't muffins work with applets as well as webstart apps? That would solve number 7 quite nicely.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Mr_Light

Senior Devvie


Medals: 1


shiny.


« Reply #10 - Posted 2008-11-12 13:03:02 »

Don't muffins work with applets as well as webstart apps? That would solve number 7 quite nicely.
Ne, cookies you should have acces to Js after all from an applet.

hmm according to this it should also work in webstart, considering I haven't used it - but it was mentioned before and no one is mentioning it now, it might not work as expected. Perhaps I'll toy with it when I have time.

It's harder to read code than to write it. - it's even harder to write readable code.

The gospel of brother Riven: "The guarantee that all bugs are in *your* code is worth gold." Amen brother a-m-e-n.
Offline CaptainJester

JGO Knight


Medals: 12
Projects: 2
Exp: 14 years


Make it work; make it better.


« Reply #11 - Posted 2008-11-12 13:03:55 »

[3] Bloated API. Many method names and class names are stupidly, anally long. For example, how many times have you had to type System.out.println("some string");? This is a ridiculous amount of typing for such a simple task.
C library
strncmp()  let's see is that the binary safe compare or the case sensitive, no wait it is the case insensitive.
Java library
String.equals();
String.equalsIgnoreCase();
 - tough one
[4] The garbage collector makes games slow and unpredictable. Good time management is a crucial aspect of any game. When you think about it a large chunk of the playability tuning that goes on in game development comes down to adjusting the timed appearance of game objects such as aliens and other moving objects. For a large game, the garbage collector makes it nearly impossible to perform synchronised screen updates.
I dare you to find a game at http://www.puppygames.net/ and say that.
[5] Write once, run anywhere is a complete myth. It is write once, debug everywhere and if you are writing applets then that means testing it in IE, Mozilla & Opera running on a combination of Mac, Linux and Windows. Because of the run anywhere myth developers rarely take the time to produce different versions of their software tuned for different machines, something that happens in the C++ world all the time as a matter of routine.
Usually only a problem when you use non-standard libraries.  Ask CAS(http://www.puppygames.net/) how much problem he has once he has released a game.

Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #12 - Posted 2008-11-12 13:21:28 »

Ne, cookies you should have acces to Js after all from an applet.

hmm according to this it should also work in webstart, considering I haven't used it - but it was mentioned before and no one is mentioning it now, it might not work as expected. Perhaps I'll toy with it when I have time.
No no, I mean muffins, also known as <a href="http://java.sun.com/javase/technologies/desktop/javawebstart/docs/javadoc/index.html">PersistanceService</a>. Think "large cookies for webstart".

<a href="http://java.sun.com/developer/technicalArticles/javase/newapplets/">This</a> suggests that if you use the new applet plugin for 1.6 then you get access to webstart/jnlp features, so muffins should be usable.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline Mr_Light

Senior Devvie


Medals: 1


shiny.


« Reply #13 - Posted 2008-11-12 14:25:12 »

hmmm muffins.  Cheesy

Quote
[size=7pt]access to advanced JNLP extensions previously available only to Java Web Start software applications. A small set was previously available, with restrictions, and these restrictions have now been removed.[/size]

It's harder to read code than to write it. - it's even harder to write readable code.

The gospel of brother Riven: "The guarantee that all bugs are in *your* code is worth gold." Amen brother a-m-e-n.
Offline princec

« JGO Spiffy Duke »


Medals: 434
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #14 - Posted 2008-11-12 14:56:54 »

I can't say that I agree with most of the OP's original reasons, except for JRE size and code signing certs.

I would probably like to add some of my own though, which are:

1. The well-documented trouble with getting applets to work reliably.
2. The trouble with signed applets popping up a security dialog.
3. Failure of portability to consoles. The main reason Java has not taken off in this space in fact.
4. Mapped objects in buffers sure would make networking and graphics code a hell of a lot easier to write.

Cas Smiley

Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 841
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #15 - Posted 2008-11-12 18:34:36 »

Quote
After having read kev's post on reasons why Java is a good development choice for game programming I felt it necessary to balance things out with a list of reasons why Java is not a good choice.

Kev's post exists for the sole reason of balancing things out, because of the threads regarding major problems with applets.

So now you messed up the balance, and somebody must create a new 'hurray for java' thread all over again.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline kevglass

« JGO Spiffy Duke »


Medals: 212
Projects: 24
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #16 - Posted 2008-11-12 19:17:59 »

Why not just duplicate the old one and call it something else? I mean it worked for Microsoft and C# didn't it?  Grin

Kev

Offline mgianota

Senior Newbie





« Reply #17 - Posted 2008-11-12 19:41:58 »

Hmm... Perhaps I shouldn't have bothered with a list of points and simply published some test code instead to show you my number one reason for not using "pure" Java to write games. Below you'll see some test code that opens up a window on screen and attempts to move a filled rectangle left to right on screen at 60fps. The result stutters and lags. There's also some tearing in evidence which is not supposed to happen as BufferStrategy purportedly checks the vertical retrace before drawing. Also, despite the fact that the main loop codepath doesn't change you can clearly see the FPS indicator moving around between 59 and 40 frames per second.

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  
package gameloop;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.event.KeyListener;

/**
 *
 * @author Mario
 */

public class Main implements KeyListener {
    private static Color[] COLORS = new Color[] {
        Color.red, Color.blue, Color.green, Color.white, Color.black,
        Color.yellow, Color.gray, Color.cyan, Color.pink, Color.lightGray,
        Color.magenta, Color.orange, Color.darkGray };
    Frame mainFrame;
    long lastTime;
    int fps;
    int frameCounter;
    long elapsedTime;
    long delayTime = 0;
    Rectangle rect;
   
    public Main(GraphicsDevice device) {
        try {
            // Setup the frame
            GraphicsConfiguration gc = device.getDefaultConfiguration();
           
            mainFrame = new Frame(gc);
            mainFrame.setUndecorated(true);
            mainFrame.setIgnoreRepaint(true);
            mainFrame.setVisible(true);
            mainFrame.setSize(640, 480);
            mainFrame.setLocationRelativeTo(null);
            mainFrame.createBufferStrategy(3);
            mainFrame.addKeyListener(this);
           
            // Cache the buffer strategy and create a rectangle to move
            BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
            rect = new Rectangle(0, 100, 50, 50);
           
            // Main loop

            while(true) {
                long time = System.nanoTime();
                calculateFramesPerSecond();
               
                // Update rectangle co'ords
                rect.x+=4;
               
                if( rect.x > mainFrame.getWidth() )
                    rect.x = -rect.width;
               
                // Draw
                Graphics g = bufferStrategy.getDrawGraphics();
                drawScreen(g);
                g.dispose();
               
                // Flip the buffer
                if( ! bufferStrategy.contentsLost() )
                    bufferStrategy.show();

                // Delay for a period of time equal to 1/60th of a
                // second minus the elapsed time
                elapsedTime = System.nanoTime() - time;
                delayTime = 1000000000L/60 - elapsedTime;
                time = System.nanoTime();
                while( System.nanoTime() - time <= delayTime)
                    ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            device.setFullScreenWindow(null);
        }
       
    }
    private void drawScreen(Graphics g) {
        g.setColor(COLORS[0]);
        g.fillRect(0, 0, 640, 480);
        g.setColor(COLORS[3]);
        g.drawString("FPS: "+ fps, 0, 17);
        g.setColor(COLORS[1]);
        g.fillRect(rect.x, rect.y, rect.width, rect.height);
    }
    private void calculateFramesPerSecond() {
        long time = System.nanoTime();
        if( time - lastTime >= 1000000000L ) {
            fps = frameCounter;
            lastTime = time;
            frameCounter = 0;
        }
        frameCounter++;
    }
    public void keyPressed(KeyEvent e) {
        if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
            System.exit(0);
        }
    }
    public void keyReleased(KeyEvent e) {
       
    }
    public void keyTyped(KeyEvent e) {
       
    }
    public static void main(String[] args) {
        try {
            GraphicsEnvironment env = GraphicsEnvironment.
                getLocalGraphicsEnvironment();
            GraphicsDevice device = env.getDefaultScreenDevice();
            Main test = new Main(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


Whilst the collection of points against using Java for games writing is admittedly a little weak, I think that the code above that uses just Java's standard APIs clearly shows that it is not worthwhile attempting games in Java without recourse to a native library. Just my two cents worth: if you want to write games in Java then make sure you use a native library such as LWJGL, or JOGL to handle the painting and screen updates.

--Mario
Offline kevglass

« JGO Spiffy Duke »


Medals: 212
Projects: 24
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #18 - Posted 2008-11-12 19:46:18 »

Works flawlessly here, sure you're not just suffering from the wonderful nano timer bugs (dual core issues)?

Kev

Offline princec

« JGO Spiffy Duke »


Medals: 434
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #19 - Posted 2008-11-12 20:01:25 »

Rock solid here too...

Cas Smiley

Offline DragonsRage

Senior Newbie





« Reply #20 - Posted 2008-11-12 20:13:58 »

Smooth sailing for me, I have vista and a dual core but no problems with your sample code.

I have made several games in java and all of them have used Java2D and I haven't had any problems. One of them was even a full blown RPG with lots of drawing and calculations and I never saw a performance hit, always a steady 59-60 FPS so I think your issue with it lies somewhere else.

 I agree that many names are stupidly long, but it makes starting out easier as they are more explanatory.

And with the garbage collector, remember that java was not made exclusively for video games and the gc does an incredible job performance wise taking that in mind, I think everyone else's suggestions pretty much cover gc for video games.

Secrets and lies

     () ()
     (O.o)
     (>.<)
Offline CaptainJester

JGO Knight


Medals: 12
Projects: 2
Exp: 14 years


Make it work; make it better.


« Reply #21 - Posted 2008-11-12 20:17:16 »

Rock solid here too...

Cas Smiley
Ditto.

Offline mgianota

Senior Newbie





« Reply #22 - Posted 2008-11-12 20:29:21 »

So what do you think the issue might be? I'm running JRE6u10 under Windows Vista on a 2.2Ghz AMD Turion 64 with an ATI Radeon XPress 1100 graphics card. Should I be running the 64bit JRE? Undecided

--Mario
Offline princec

« JGO Spiffy Duke »


Medals: 434
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #23 - Posted 2008-11-12 21:08:38 »

I'm on u10 on a similarly specced machine and it's fine.

Cas Smiley

Offline mgianota

Senior Newbie





« Reply #24 - Posted 2008-11-12 21:30:31 »

Typically the problem resides with the hardware, not Java. I've discovered that the machine (a laptop) was throttling the CPU to conserve power!

If you're intrested, below you'll find some code that will bench the Thread.sleep() method on your machine and report failures if the method doesn't sleep for exactly the time requested.

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  
public class ThreadSleep {

    public static void main(String args[]) {
        try {
            boolean ok = true;
            for (int i = 0; i < 100; i++) {
                long start = System.nanoTime();
                Thread.sleep(10);
                long end = System.nanoTime();
                if ((end - start) < 10000000) {
                    System.out.print("failed, iteration ");
                    System.out.print(i);
                    System.out.print(", time ");
                    System.out.print(end - start);
                    System.out.println("ns");
                    ok = false;
                }
            }
            if (ok) {
                System.out.println("ok");
            }
        } catch (InterruptedException x) {
            System.out.println("error: Thread interrupted.");
        }
    }
}


Here's the output for my machine:
1  
2  
3  
4  
failed, iteration 1, time 9961881ns
failed, iteration 83, time 9998757ns
failed, iteration 94, time 9968865ns
failed, iteration 97, time 9989818ns


Unpredictable as Hell, what a headache! Does anyone get a run of the code above with zero failures?

--Mario
Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 841
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #25 - Posted 2008-11-12 21:37:14 »

If you want to get 100% innocent CPU usage, spawn (a few*) daemon threads looping on Thread.yield(). It might do the trick keeping your animation smooth (and draw your battery like there is no tomorrow).

*few -> as much as you have cores

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline mgianota

Senior Newbie





« Reply #26 - Posted 2008-11-12 21:46:54 »

Doesn't work.  Sad Task manager shows the java.exe consuming only 76% of the CPU.

--Mario
Offline komadori

Senior Newbie





« Reply #27 - Posted 2008-11-12 21:47:13 »

Unpredictable as Hell, what a headache! Does anyone get a run of the code above with zero failures?

Yes, but it sleeps close to 20ms (you only check the lower bound). In any case, without using a hard real-time scheduler the duration parameter is a request rather than a demand.

Offline DzzD
« Reply #28 - Posted 2008-11-12 21:48:40 »

Quote
1  
while( System.nanoTime() - time <= delayTime);
... at least add a thread.yield or you will produce a cpu lock (if your blitting has been delayed for example it will be locked..), (there are severals java source code available and able to produce a stable frame rate).
IMHO : even  from an algorithm point of view the method you have used is innacurate as the error are cumulative over time => with your method at 60fps after 100 s you can have produced a number of frame very different than 6000 (60*100)


Quote
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  
public class ThreadSleep {

    public static void main(String args[]) {
        try {
            boolean ok = true;
            for (int i = 0; i < 100; i++) {
                long start = System.nanoTime();
                Thread.sleep(10);
                long end = System.nanoTime();
                if ((end - start) < 10000000) {
                    System.out.print("failed, iteration ");
                    System.out.print(i);
                    System.out.print(", time ");
                    System.out.print(end - start);
                    System.out.println("ns");
                    ok = false;
                }
            }
            if (ok) {
                System.out.println("ok");
            }
        } catch (InterruptedException x) {
            System.out.println("error: Thread interrupted.");
        }
    }
}

Thread.sleep and System.nanoTime are two methods that have showed inaccuracy depending on OS and hardware

Offline ewjordan

Junior Devvie





« Reply #29 - Posted 2008-11-12 21:52:16 »

Oof, no love for the functor around these parts, is there? Smiley  Time for a rant, duck and cover!

A lot of people underestimate how useful closures are to have built in to a language, and how crippled a language actually is without them - yes, as in, there are abstractions that we cannot make in Java because we don't have this stuff, and it makes our code less reusable and modular.  You can work around some of the issues with an interface, and for those uses it's just syntax sugar (for sorting it's not too obnoxious to require a comparator, for instance).  But the same exact thing could be said about inheritance, which you can simulate to your heart's content in a language like Lisp (let's pretend for the moment that Common Lisp didn't already have CLOS built in, which for all intents and purposes is true since nobody uses it).  The difference between having that syntax sugar and not having it means that you approach problems in a completely different manner - in languages without closures, people pretend that everything is a noun, even when it's a verb (MyFunctionWrappingObject), and in languages without objects, people pretend everything is a verb (myObjectSimulatingFunction).  Yeah, you can get away with it, but IMO it's better to verbs and nouns as they are meant to be used, not try to shoehorn one into the other.

Added syntax sugar is only one tiny bit of the argument in favor of closures, though - Neal Gafter had the following to offer on the subject:
Quote
Most programming languages are turing-complete, so the power of closures do not arise from their ability to compute things that cannot otherwise be computed. Rather their expressive power arises from being able to abstract over things that you simply could not abstract over before. In the case of closures, it is the ability to define APIs that abstract over an arbitrary statement or expression. Writing such APIs simply isn't possible in Java today.

Since the ability to abstract common patterns is generally considered a good thing, I'm surprised that the addition of closures is so hotly contested, as it opens up a whole new class of abstractions - as a very simple example, functionality like foreach is dead simple to implement with closures, and pretty much impossible to do properly without them, at least without writing your own compiler or annotation processor (essentially what AOP weaving does).  Stuff like that needs to be hard coded directly into the language if we want to use it, which is a real shame, since it doesn't happen very often, and we end up duplicating mountains of code patterns as a result.

If you need more convincing that there's stuff that you really can't do in Java as-is, see Neal's talk about closures at http://www.parleys.com/display/PARLEYS/Home#talk=6533;slide=1;title=Closures%20for%20Java - there is actual power added to a language by closures, it's just that it's the type of power that most Java and C++ programmers don't even think to miss because the boilerplate code that it would replace (and the design patterns it would render irrelevant!) has become so ingrained at this point. [To be fair, C++ technically has the ability to do this stuff, it's just a lot messier than it should be - when people argue for closures, they're not merely suggesting C++ style function pointers, which tend to do more harm than good!!!]

From a less radical point of view, the unconvinced may be curious to hear James Gosling's take on closures (he's one of the people campaigning for them):
Quote
Closures were left out of Java initially more because of time pressures than anything else. In the early days of Java the lack of closures was pretty painful, and so inner classes were born: an uncomfortable compromise that attempted to avoid a number of hard issues. But as is normal in so many design issues, the simplifications didn't really solve any problems, they just moved them.

And btw, I'm no more sympathetic to the functional people's claims that their languages don't need objects or state - you may be able to get away with representing everything as a monad, and in situations where you absolutely need state-free computation that makes sense, but for the sanity of people that don't have that requirement, your language had better offer a choice, and build it in with some decent syntax.  Yeah, I'm looking at you, Haskell!!!

@mgianota: Yeah, works fine on my machine, too (constant 60 fps), though there is an unacceptable amount of tearing (tested both OS X Java 5 and 6).

Edit: it's worth noting that none of my closure rant has much to do with Java for games in particular, more just about the language as a whole.
Pages: [1] 2 3 ... 5
  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.

rwatson462 (35 views)
2014-12-15 09:26:44

Mr.CodeIt (26 views)
2014-12-14 19:50:38

BurntPizza (53 views)
2014-12-09 22:41:13

BurntPizza (86 views)
2014-12-08 04:46:31

JscottyBieshaar (48 views)
2014-12-05 12:39:02

SHC (63 views)
2014-12-03 16:27:13

CopyableCougar4 (65 views)
2014-11-29 21:32:03

toopeicgaming1999 (126 views)
2014-11-26 15:22:04

toopeicgaming1999 (117 views)
2014-11-26 15:20:36

toopeicgaming1999 (34 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
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!