Re: Requesting tips, comm
To: comp.lang.java.gui
"Daniel Pitts" <googlegroupie@coloraura.com> wrote in message
news:1174530560.096511.297000@y66g2000hsf.googlegroups.com...
On Mar 21, 6:14 pm, Knute Johnson <nos...@rabbitbrush.frazmtn.com>
wrote:
Having played a lot with one form of animation, I would use a
completely
different tack. Use a Window or JWindow and do active rendering. This
avoids the EDT altogether for any drawing. You still may have to
synchronize some parts of your code but the more you can avoid that the
better. Synchronizing can have a rather significant performance hit.
I thought I *was* using active rendering. I thought active rendering
was simply having your own rendering loop instead of waiting for AWT to
sent paint events (which is how my code is structured). As a quick check,
I skimmed through
http://java.sun.com/docs/books/tutorial/extra/fullscreen/rendering.html
and now I'm a bit confused. The page mentions setIgnoreRepaint, which I've
forgotten to do. Okay, fine. But the page also implies (but does not
explicitly state) that active rendering is only possible in full screen
mode.
So:
(1) What's the difference between what I'm doing, and active rendering?
Are you thinking mainly of BufferStrategies? (I'll address that later on
in this post)
(2) I assume active rendering possible in windowed-mode. Is this
assumption correct?
(3) And finally, why do you recommend JWindow over JFrame (or do you)?
[...]
I suggest Java Concurrency in Practice <http://jcip.net/> for anyone
who wants to know the correct way to deal with multithreaded
applications. I already understood SOME of it, but that book
clarified a lot of concepts, and solidified my understanding of multi-
threaded programming.
Thanks, I'll take a look at that book.
On Mar 21, 9:41 am, "Oliver Wong" <o...@castortech.com> wrote:
<SSCCE>
[snip]
while (!timeToQuit) {
getPlayerInput();
processGameLogic();
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
synchronized (mainWindow) {
Graphics2D g = (Graphics2D) mainPanel.getGraphics();
g.setTransform(AffineTransform.getScaleInstance(
(double) mainPanel.getWidth()
/ (double) DEFAULT_RENDERING_WIDTH,
(double) mainPanel.getHeight()
/ (double) DEFAULT_RENDERING_HEIGHT));
updateScreen(g);
}
}
});
Thread.sleep(1);
}
}
[snip]
</SSCCE>
- Oliver
Oliver:
I personally think its a "Bad Thing" to have a busy wait -- a while
loop with a Thread.sleep(). Swing is design around an Event model,
you can probably refactor your code to avoid running on the main
thread, and use a javax.swing.Timer instead.
Perhaps for a "normal" application, but I'm pretty sure the common
wisdom for games is to have your own rendering loop. Sun themselves
recommends a rendering loop in their active rendering tutorial:
http://java.sun.com/docs/books/tutorial/extra/fullscreen/rendering.html
<quote>
public void myRenderingLoop() {
while (!done) {
Graphics myGraphics = getPaintGraphics();
// Draw as appropriate using myGraphics
myGraphics.dispose();
}
}
</quote>
"Knute Johnson" <nospam@rabbitbrush.frazmtn.com> wrote in message
news:RLkMh.96279$_w.85830@newsfe13.lga...
I'm not sure why you have the calls to set then main window visible and
dispose it synchronized. They are already being called on the EDT and
if you don't make any Swing method calls except on the EDT they will
already be synchronized by default.
[...]
"Daniel Pitts" <googlegroupie@coloraura.com> wrote in message
news:1174530560.096511.297000@y66g2000hsf.googlegroups.com...
BTW, you should avoid "synchronize" in the EDT all together. If you
have a thread that synchronizes on an object, and then calls
"invokeAndWait" with a runnable that syncs on the same object, you
have a deadlock. And this is only the first order example.
I was getting some NPEs from mainPanel.getGraphics() returning null,
and I had figured it was due to the window getting disposed while the
rendering loop was still occurring or something along those lines. But
after having read a bit more about the event model (e.g. that it is
implemented as a queue and is single-threaded) I see now that my
synchronizations didn't really make sense.
Anyway, here's my new code, taken into account your advices. The two
main changes are:
(1) Used BufferStrategy to do hardware accelerated page flipping/double
buffering. I normally do this in my games, but I thought it wasn't really
relevant to the threading questions, so I left it out for this example.
Now that I've put it in, I can't really use the JPanel (since you can't
get a strategy on the JPanel), so this also means there's a bit of extra
code to fiddle with insets on the Window.
(2) Replaced the synchronize() keywords with an if statement checking that
mainWindow is not null.
<SSCCE>
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferStrategy;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test {
private static final int DEFAULT_RENDERING_WIDTH = 640;
private static final int DEFAULT_RENDERING_HEIGHT = 480;
private static JFrame mainWindow;
/**
* Returns true if the game is in the process of shutting down and
quitting.
* If it's in the middle of a game-loop iteration, it'll finish that
* iteration (potentially drawing 1 more frame of animation, and then
quit.
*/
private static boolean timeToQuit = false;
/**
* True if the player pressed the "action" key since the last iteration
* through the game loop, false otherwise. In a real game, I'd probably
have
* many of these booleans (e.g. an "up" key, a "down" key, etc., and move
it
* into a seperate class for organization purposes.
*/
private static boolean pressedActionKey = false;
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
/*
* This first invokeAndWait initializes all the GUI components, and
* registers the appropriate listeners to hook into the main game
* engine.
*/
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
mainWindow = new JFrame("My game");
mainWindow.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
mainWindow.setIgnoreRepaint(true);
mainWindow.addWindowListener(new WindowListener() {
@Override
public void windowActivated(WindowEvent e) {
// Does nothing.
}
@Override
public void windowClosed(WindowEvent e) {
// Does nothing
}
@Override
public void windowClosing(WindowEvent e) {
timeToQuit = true;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mainWindow.dispose();
mainWindow = null;
}
});
}
@Override
public void windowDeactivated(WindowEvent e) {
// Does nothing.
}
@Override
public void windowDeiconified(WindowEvent e) {
// Does nothing.
}
@Override
public void windowIconified(WindowEvent e) {
// Does nothing.
}
@Override
public void windowOpened(WindowEvent e) {
// Does nothing.
}
});
mainWindow.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
pressedActionKey = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
// does nothing.
}
@Override
public void keyTyped(KeyEvent e) {
// does nothing.
}
});
mainWindow.setPreferredSize(new Dimension(
DEFAULT_RENDERING_WIDTH, DEFAULT_RENDERING_HEIGHT));
mainWindow.pack();
mainWindow.setVisible(true);
mainWindow.createBufferStrategy(2);
}
});
/*
* This while loop is the main game loop. It basically iterates through
* 3 stages forever: getting the player input, reacting to it, and
* drawing the results on screen.
*/
while (!timeToQuit) {
getPlayerInput();
processGameLogic();
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
if (mainWindow != null) {
BufferStrategy strategy = mainWindow
.getBufferStrategy();
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
Insets insets = mainWindow.getInsets();
g.translate(insets.left, insets.top);
g.setTransform(AffineTransform
.getScaleInstance(
(double) (mainWindow.getWidth() - insets.right)
/ (double) DEFAULT_RENDERING_WIDTH,
(double) (mainWindow
.getHeight() - insets.bottom)
/ (double) DEFAULT_RENDERING_HEIGHT));
updateScreen(g);
strategy.show();
}
}
});
Thread.sleep(1);
}
}
public static void processGameLogic() {
/*
* Check if pacman touched a ghost, stuff like that. Doesn't touch any
* Swing components.
*/
}
public static void getPlayerInput() {
/*
* Doesn't touch any Swing components.
*/
if (pressedActionKey) {
/* make mario jump */
System.out.println("Mario jumps.");
pressedActionKey = false;
}
}
public static void updateScreen(Graphics2D g) {
assert SwingUtilities.isEventDispatchThread() : "Don't call updateScreen
from outside the EDT.";
g.setColor(Color.BLACK);
g.fillRect(0, 0, 640, 480);
/*
* TODO: Draw all sorts of amazing eye-candy.
*/
}
}
</SSCCE>
- Oliver
---
* Synchronet * The Whitehouse BBS --- whitehouse.hulds.com --- check it out free usenet!
--- Synchronet 3.15a-Win32 NewsLink 1.92
Time Warp of the Future BBS - telnet://time.synchro.net:24