I have been thinking about porting my game, http://freerails.sourceforge.net/, to OpenGL directly rather than use Swing, since people keep saying its too slow:( However, this seems like a lot of work and there are lots of things that Swing makes easy that would take a long time to get right if I were doing it myself. So I have been looking at ways to mix Swing and OpenGL.
So far I have had a quick look at JOGL, but the most promising approach would seem to be using agile2D.
What I have done so far is as follows:
I have added a method:
GLFunc getGL(){
to the class
agile2d.opengl
This lets me mix java2D and direct use of OpenGL in JComponents. For example
import gl4java.GLEnum;
import gl4java.GLFunc;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import agile2d.opengl.AGLGraphics2D;
public class TestJPanel extends JPanel implements GLEnum {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawString("This text was drawn by calling g.drawString(.) before the GL triangle.", 20, 20);
GLFunc gl = ((AGLGraphics2D) g).getGL();
gl.glBegin(GL_TRIANGLES);
gl.glColor3f(0.0f, 0.0f, 1.0f); //blue
gl.glVertex3i(20, 0, 0);
gl.glVertex3i(0, 100, 0);
gl.glVertex3i(100, 100, 0);
gl.glEnd();
g.setColor(Color.WHITE);
g.drawString("This text was drawn by calling g.drawString(.) after the GL triangle.", 20, 60);
}
}
and
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
import agile2d.AgileJFrame;
public class TestFrame {
public static void main(String[] args) {
JFrame frame = new AgileJFrame();
frame.setSize(400, 400);
frame.getContentPane().add(new TestJPanel());
//Add an JInternalFrame - shows light weight components can be drawn on top
//components rendered using direct OpenGL.
JInternalFrame jInternalFrame = new JInternalFrame("JInternalFrame");
jInternalFrame.setSize(200, 200);
frame.getLayeredPane().add(jInternalFrame,
JLayeredPane.MODAL_LAYER);
jInternalFrame.setVisible(true);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
System.exit(0);
}
});
frame.show();
}
}
Which produces the following…
http://freerails.sourceforge.net/screenshots/opengltest.PNG
The advantages of this approach seem to be:
(1) Java2d calls and direct openGL calls can be freely mixed.
(2) I don’t need to worry about light and heavyweight components.
(3) rendering of the swing components is h/w accelerated.
My questions
(1) Does this sound sensible? Has anyone else tried it?
(2) How does the performance of agile2D compare with the current performance of standard java2D?
(3) Is the any benefit in trying to port AGLGraphics2D and other relevant classes to use JOGL instead of gl4java?
Luke