A tutorial!? I'd have to go back to square one, fifteen years ago sitting in a comp sci. computer room drumming my fingers on the desk waiting for the download link for The Java Programming Language to appear.

Believe it or not, the smooth scroll code above is very nearly fifteen years old. Because of it's age it is extremely reliable. The most recent change was made when Javasofct released the system nanotimer. But since then the code has remained largely unchanged.

IMO the best tutorials are those that just show the code interspersed with a few comments. I never read most of the verbiage on the Java tutorial site, I normally go straiight for the section of code I am interested in and copy and paste the chunk into whatever piece of software I happen to be working on.

Oh, just one rather big thing to point out about the smooth scroll code: I've never written a full game in Java and released it so feel free to shoot me down in flames.

Hmm... I have enjoyed my time on this forum immensely, it is populated by very intelligent programmers. However, the real world beckons and I have a game to produce which I would have liked to have produced in Java but cannot because of the performance. I have seen the eminently capable LWJGL library though I am unwilling to opt for using OpenGL over DirectX. It is a shame that he used OpenGL 'cos I quite liked the screenshots for Puppygames and was disappointed that I couldn't play them. BTW IMO David Brackeen's Pulpcore is grr-eat. And JOGL is well... JOGL reminds me of that horse that is running around outside of a closed stable door.

I still have strong reservations about using Java exclusively for writing games and I simply don't believe it is up to the job. But I am not going to spend anymore time prodding at your hearts and minds by advocating C++ because it is obvious you have your souls set on Java. So I shall bid the forum a fond farewell and depart back to Microsoft land, where everything is bright and whizzy and explodes for no apparent reason. Sanity beckons. As a parting shot, I'll leave you with a reference to a picture of a truly great language designer: http://www.research.att.com/~bs/

This thread has taken a number of diversions away from its intended purpose but I can't say that I am unsurprised to see a discussion of JNI. My feeling on Java now after having spent a week or so with the language is that it is mean-spirited. Let me explain. I was initially bemused as to why Java does not include so much of the C/C++ syntax which gives that programming language so much of its power and flexibility, but understanding dawned when I read this article: http://www.eweek.com/c/a/IT-Management/Father-of-Java-Has-His-Eye-on-Jackpot/.

I wish you the best of luck with your Java creations but I cannot help but feel that you are being led up the garden path with a watered down version of C++ by a very clever man that has deliberately forbidden vital syntactical constructs and programming idioms because the inclusion of those constructs would fight his ability to create tools that produce "semantic models of the application", not because the use of those constructs and idioms are representative of bad programming practice. What he means by semantic models of course is a model of a program that is amenable to algebraic manipulation.

Finally, to sum up. I read comments from one young man who proclaimed that, "Java is a language that your grandfather uses.". I'm inclined to agree; it is safe and doesn't allow you to do anything "dangerous". For dangerous, read "truly useful".

That code is broken through too much hacking. Below is the code I'm currently using. It is based upon feedback from Mr_Light and it is better than my original version but it still stutters. BTW it is not true that Thread.sleep() is innacurate. The method has a resolution of 1 millisecond and it seems to sleep for exactly that length of time.

mainFrame = newFrame(gc);mainFrame.setUndecorated(true);mainFrame.setIgnoreRepaint(true);mainFrame.setVisible(true);mainFrame.setSize(640, 480);mainFrame.setLocationRelativeTo(null);mainFrame.createBufferStrategy(2);mainFrame.addKeyListener(this);// Uncomment this code if you want to see the game loop run full// screen. Running in full screen will enable the buffer strategy's// vertical retrace lock which should result in smoother animation.//device.setDisplayMode(new DisplayMode(640,480,8,DisplayMode.REFRESH_RATE_UNKNOWN));//device.setFullScreenWindow(mainFrame);

Hmm... You can't do a Thread.yield() in your delay section as it will peg the CPU. It is better just to put the thread to sleep for the length of the delay time. Additionally, the AWT thread is running at a higher priority than your game thread so you don't need code that gives it a chance to run. As far as I am aware, the only time you need to use yield is when you have a thread running at maximum priority and you need to give lower priority threads a chance to run.

I really want to get this stutter problem sorted out but I'm beginning to think that it is impossible.

I know how to write a game loop with a fixed time step, a variable time step and move objects in discrete increments and I know the benefits of these aproaches. I also know how to compensate for variable time step physics simulations by decoupling the physics update from the framerate and using an alpha blending approach to cope with any remainder problems. In short I know how the mathematics for game loops work. Your comments are simply unfair.

Anyway, it still stutters regardless of whether you use a fixed, or variable time step. The C code doesn't, which is strange because the JVM writers have access to the exact same C libraries that I do. If you write games in pure Java they stutter. I'm sorry but I think I'm correct, Java is not a good language for games development. Or more accurately, the JVM is not a good platform upon which to build a game.

If you use a native lib to do your graphics, input and sound then you might as well continue writing the game in C. At least in C you can synchronize the main loop properly. I think it is Java's shortcomings in the timing and synchronization arena that you are attempting to vainly support (it is obviously inadequate) and that you're just making excuses for Java's stuttery, laggy games performance by pointing the finger at my coding errors which were Java specific and based upon lack of experience in Java. It isn't fair to dismiss me as having made basic fundamental errors simply because I am new to Java. Let's face it, the code that I posted was pretty simple stuff and it was a fair translation of how you implement a simple game loop. Works in C, doesn't work in Java. Hmm... why not? That was the basis from which I approached the problem.

Why is it that Java games require a native library to handle the graphics & input in a satisfactory manner? Is it because pure Java simply sucks from a games development point of view? I think so. And it is obvious that others do too otherwise they wouldn't need the native libs.

@Mr_Light: It still stutters on my machine --I didn't run your code for long enough to see the stuttering effect the first time. It is as if something is throttling the execution thread, slowing it down and then speeding it up.

The *reason* you don't see stuttering as bad with your example is that you are not updating the game objects inline with elapsed time, you just tick them forward a fixed increment at a time. That's why your example looks smoother even though the game objects are actually moving at a variable rate. My game needs physics and that means integrating values over an elapsed time period.

I need to think about this issue some more. Something in the JVM or in the OS is throttling the execution thread.

LWJGL doesn't work on all systems. To run LWJGL code you must either have a graphics card plus drivers that support OpenGL, or a software OpenGL emulation layer. A lot of people out there simply will not be able to run your game.

As soon as you include native libs like LWJGL you effectively reduce the portability of your code to people who have compatible hardware. Cas has already said that he doesn't really use much OpenGL code, all he does is blit quads and draw lines. If that's all then you might as well use Windows GDI and DirectDraw and your game will work on every Windows machine.

I think now that if you're going to write games in Java, then for maximum portability you should stick to pure Java. But so far it looks as though pure Java isn't up to the job of managing a simple game loop.

Yup. The thread is about reasons why Java should not be used for games writing.

To bring the thread back on track I thought I'd post the updated test code I'm using. It is a physics based main loop and the physics update code is decoupled from the framerate with a fixed time step --quite groovy really. But it is still jerky, despite the addition of a call to synchronize with the display adapter. Recall from previous posts that the stuttering and lag is a major reason for saying no to using Java for writing games. It needs a bit of a clean-up because I've hacked about with it a bit but there is no reason I can think of why this code should produce a stuttering animation.

/** * * @author Mario */publicclassMainimplementsKeyListener {privatestaticColor[] COLORS = newColor[] {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 };FramemainFrame;/* * Saves the last time the frame counter looked at the clock */longlastTime;/* * Stores the calculated frames per second */intfps;/* * Stores a count of the number of frames that have been issued * within 1 second */intframeCounter;/* * Saves the elapsed time in nanoseconds */longelapsedTime;/* * Stores the calculated time to delay at the bottom of the main loop */doubledelayTime;/* * Total game time in nano seconds */floatgameTime;/* * Fixed time step in seconds */floatdt = 0.01f;/* * elapsed time accumulator in seconds */floataccumulator;/* * Desired frame rate */doubleframeRate = (double)1000000000L/(double)60;

I realize that many of you use LWJGL because of the performance hit, but I actually can't see the point of including native libraries with a Java program. When a Java program calls for native support I automatically reach for my C/C++ compiler. Once I'm in the C/C++ environment I'm reluctant to leave it to go back into Java as it just feels as though I'm creating a DLL for scripting purposes. I might as well stay in the C/C++ IDE and write the whole thing in C and then I don't have to concern myself with producing JNI interfaces. So-o, I want to write pure Java games without native support.

I have the ATI Radeon Xpress 1100 chipset with a DirectX 7 driver. Unfortunately, the card doesn't seem to support OpenGL: the driver software says that OpenGL is unavailable. It is the latest driver software package from AMD for my card too.

The machine is a laptop so I can't just go out and buy an NVidia card. I guess I'll have to buy a proper machine.

It's big right now - haven't optimised it for applets, should be able to cut out another 3mb or so - and it misbehaves a bit on shutdown and seems not to work properly in Chrome. But it's nearly there!

Cas

I can't play it. The screen shots for your games look really good too. That's why I want to write pure Java because the native libraries fail on some machines.

I wish someone would write a good shooter in pure Java so that I could see what can be done. Attack of the Meeplings wasn't bad, but it didn't really have much in the way of effects to make it more interesting.

The installer for the newest graphics drivers from AMD fails to execute properly on my machine. Windows Vista notifies me with a "this program has stopped working" dialog. I think the installer wasn't tested on Windows Vista. So, I can't update the drivers to run LWJGL code until AMD get around to fixing their installer to work with Vista.

Maybe I'm missing something, but I seriously don't know how you can call that 'Unpredictable as Hell' Given that Thread.sleep() has a precision of 1ms, 9998757ns IS exactly the amount of time you intended to sleep, so your example just demonstrates that Thread.sleep() works as advertised and your code to report a failure is wrong....

Since when was 9998757ns ever equal to 10ms? Okay, it is close to 10ms but it is not exact.

This thread is about why Java is not a good language for game development and the sample code which attempts to synchronize a main loop to 60fps clearly doesn't work properly on my machine (a reasonably well spec'd one) which is why I am investigating Java's timing abilities. A jerky screen update is a major reason for abandoning Java as a games development language.

Here's some timer test code written by David Brackeen that shows the problem. He's already stated in a PM to me that he believes it to be a thread scheduling problem. When you execute it you should get no jumps forward.

Try using Toolkit.getDefaultToolkit().sync(); just after you call show() of BufferStrategy.

That dramatically improves things. Interestingly, it causes Windows Vista to revert to what it calls a basic colour scheme: "The following program has performed an action that requires Windows to temporarily change the colour scheme to Windows Basic." The popup help hints at the fact that there is either: (i) insufficient memory to continue displaying Windows Aero (the default scheme on Windows Vista) translucent Windows. Which is unlikely, or (ii) the computer's hardware configuration or screen resolution was changed.

Looks like a call to sync() triggers this behaviour on Windows Vista. Bu-ut, the frame rate is now more or less steady at 58-60 FPS. Thanks jezek2.

You're not gonna believe what just happened. I was reloading the Applet over and over again. On about the twentieth reload the applet left the window and reappeared in the top left hand corner of the screen! BTW I saw no memory issues in task manager.

@Dzzd: Okay, there's a strong possibility that I have hardware that Java just doesn't like very much. But, the problem is that I can write a rock-solid game using C & SDL and the timing will be 100% accurate. This code works just great on my machine so I don't think my hardware can be all that bad, I'm more inclined to think that the problem lies with Java not me. True, I should not have locked up the CPU in the while loop but I fixed that and it made no difference.

I'm just totally bemused by the way the Java code behaves, it seems to have a mind of its own and that makes me feel nervous and unsafe when I'm writing code on top of code that makes things move around unpredictably over time. All I can think about is that if the Java code is doing this to me then chances are it is going to do the same to a lot of other people too. What it boils down to is that if I use C I get no timing problems, but if I use Java I get timing problems.

@Kev: I'm not a Java hater. It is impossible to hate a language which is obviously so beautifully engineered. At heart I'm a C programmer and I use Java because I think it has a great class library, blindingly good tools and a knockout windowing kit all built-in to one package. Also, server-side Java goes like sh*t off a shovel. The speed of Java isn't an issue for me, it is the reliability of the programming APIs. I don't know about you, but for me timing bugs are a source of major headaches and Java's timing (I'm basing this upon what David Brackeen and Dzzd has said) isn't up to the job for games writing.

I would like to be able to write games in Java because it gives me one-click deployment off a web page but I'm forced back into C simply because Java has got the fundamentals wrong. In gaming, timing is everything.

@Riven: Yeah, you've hit the nail on the head. My only raison d'etre for using Java is the gorgeous IDEs and other build tools (like Ant) that are available. Plus the Javadoc popup thing in the editor makes coding to libraries a breeze. But, if I can't get a stable frame rate because the platform timer sucks then no way am I going to use Java.

BTW Pulpcore is excellent David, but the applets are jerky. It is such a shame 'cos Pulpcore has got a beautiful timing and animation framework. I wrote a quick 2D shooter using Pulpcore and it was just dead easy to do, but I stopped writing when I noticed the jerky screen updates becase I thought that nobody will play a game for more than ten seconds if it is lagging and jerking around on screen. In fact, I think players will actually start to *hate* you for publishing a jerky game. Jerky games are my number one biggest turn off.

I have no idea whether the problem is due to the Java system's timer, or the graphics libraries. I just know that I can't use it to write games 'cos the stutter & lag offends my sensibilities as a programmer first and as an avid games player second.

So in summary, is it fair to say that Java is bad choice for game development if you do not include native libs?

I think the answer to the question is fairly obvious really. I don't mind using native libraries from within Java, but using them increases the likelihod that my game will fail to start up on another machine. For example, neither LWJGL nor JOGL will work on this Windows Vista laptop that I'm using despite the fact that it is a reasonably well specc'd machine. LWJGL complains about an unsupported pixel format (video card trouble) and JOGL regularly crashes the JRE, though software emulation works just fine but is far too slow for games work. I can't play Puppy Games' games because they won't start up on my machine. The failure to start problem is just *eating* away at your profits Cas. A DirectX version in C++ would have run just fine. A shame really 'cos I really like playing shoot-em up games --they help me to concentrate.

As for writing games in pure Java, I've given up! There are timing problems and screen update problems that I just don't get if I use C and a really simple hardware layer interface library like SDL. Additionally, there is something deeply suspicious about the inner-workings of System.nanotime() and the lag and stutter in the main game loop is causing me so many headaches. Again, as Kev suggested, it is probably a hardware problem but I no longer care about Java's hardware interface problems. My lack of care in this respect is prompted in part by the suspiciously low coupling of Java to hardware.

Anyway, back to the point. If I can't do something really, really basic like time the appearance of game objects and move them *smoothly* around on screen (even at low frame rates on really bad hardware) then I don't really want to know what else Java can do. Hell, even Blitz Basic and Dark Basic will give me a smooth, consistent main loop on a crappy 500Mhz Pentium, why won't Java? Christ, even Flash will give me a steady frame rate and Flash is the suckiest of the suckiest arse-over-tit, extra-ecma-anal game programming environments. On this machine, I only get a stable frame rate for my test code in Java if I drop the frame rate to ten frames per seconds, which is unusable except for the simplest of puzzle games.

It is not enough to say, well there's something wrong with the way you're doing your screen updates in the test code (as Dzzd said) and you need code to stabalize the frame rate. That's just a load of bollocks Dzzd. There's nothing wrong with the code: time the game objects update & drawing operations and then sleep for a period of time to sync the loop at sixty frames per second, or whatever frame rate you can get away with. It doesn't get much simpler than that. Coding a game loop is trivial, yet Java just doesn't seem to be able to handle the timing and synchronisation requirements and produces inexplicable stutters and lags in the main loop. Let's face it, stutter and lag are just anathema to a games writer. Its the kind of thing that furrows your brow when you're falling off to sleep and it is annoying because the problem subtracts thinking time from designing and implementing the game play and game mechanic. Incidentally, when I ported the test code across to C and SDL, I got a rock steady frame rate. As expected, with none of the stupid bollocky timing artifacts that Java seems to throw in to the mix.

The other thing that is bothering me, which cas has touched upon, is that there is no console support in Java. If I write a game for the PC and it does reasonably well then the obvious thing to do would be to use the profits generated from the PC version to purchase a console development kit and port the game across. If I've already written the game in C then porting becomes trivial, if it is written in Java with native lib dependencies then porting is not so easy and straight-forward. In fact, it is probably near enough a complete rewrite.

IMO Java fails as a choice for game writing at the most basic level: the game's update/render loop. This is unpardonable for a runtime that wants to make it in the game writing arena. If the timing in your game is off then the players will notice and stop playing the game and they certainly won't buy a game that stutters and lags. I'm a little annoyed not to mention peeved at the amount of time (wasted in my opinion) I have spent writing and debugging code on a platform that just doesn't perform well enough and no amount of tinkering will coax the JRE, or the graphics libraries or the timer or whatever the Hell the problem is with Java's jerky screen updates into giving me a stable main loop on top of which I can build a playable game.

I'll continue to hang around the forum to see if things improve, but TBH I think that Java's games writing problems are fundamental and located within the JRE and the native interface code. Aargh, all those bloody layers just to get at the hardware! I'm sorry, but I think you are completely wrong to spend your time writing games in Java. C/C++ is a much better choice. Using Java for games writing just brings to mind a modern curse: may your games stutter and lag for all eternity.

I'll stick around the forum to view the games showcase releases (I do like seeing those) and just generally monitor the Java performance related posts but as for using Java to write a commercial game, I think I'd rather eat a pooh sandwhich and wash it down with an extra large cup of vommit. Heh, not that I'm in the habit of consuming such eye wateringly disgusting repasts. My experiences with Java game programming have given me a bloody twitch. Right, where the Hell's my C compiler? Sanity extends an elegant, manicured finger and beckons with a sultry call "this way young Jedi, this way...".

Jesus, you know what? I'm actually beginning to believe that I'll need a theraputic course in advanced cognitive neronal repair after my experiences with that JRE and class library. I feel that my experience of writing games in Java has just caused the window of opportunity to slam down on my fingernails, throwing me breathless to the floor. And there I lied, helpless, as I watched the Sun Necrosystems vultures descend from the sky to pick at my loathsome bones...

... 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).

Yes, you're right. I added the Thread.yield() call into the main loop.

Quote

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)

The method I'm using is the only one I know for producing a reasonably acceptable frame rate. Do you have any code to share that can increase the accuracy? For example, do I need code that will measure the frame rate while the game is running and increase the frame rate to compensate for cumulative errors over time?

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