I have tried converting my LWJGL game to an applet but It can't load images, when I delete the code for the images it throws a null pointer exception, so Could SOmeone give me a walkthrough on how to Convert this code to an applet:
package com.kgt.platform.name;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import kuusisto.tinysound.Sound;
import kuusisto.tinysound.Music;
import kuusisto.tinysound.TinySound;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
import static org.lwjgl.opengl.GL11.*;
public class Game {
public static Player player;
public static Enemy enemy;
public static ExitButton exitbutton;
public static MenuButton menubutton;
public static ArrayList<Coin> coinlist;
public static ArrayList<Bullet> bulletlist;
public static ArrayList<Bullet2> bulletlist2;
public static ArrayList<Platform> platformlist;
public static ArrayList<OneWayPlatform> onewayplatformlist;
public static int score;
public static boolean p1on;
public static boolean p2on;
static State state = State.GAME;
public int curlvl = 1;
private static Texture logo;
private static Texture pause;
public enum State {
PAUSE, GAME, MAIN_MENU, INTRO;
}
public static void init() {
try {
// load texture from PNG file
logo = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/logo.png"));
System.out.println("Texture 'logo' Loaded. Format: PNG");
pause = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/paused.png"));
System.out.println("Texture 'pause' Loaded. Format: PNG");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void logo() {
Color.white.bind();
logo.bind(); // or GL11.glBind(texture.getTextureID());
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0,0);
GL11.glVertex2f(192,468);
GL11.glTexCoord2f(1,0);
GL11.glVertex2f(192+logo.getTextureWidth(),468);
GL11.glTexCoord2f(1,1);
GL11.glVertex2f(192+logo.getTextureWidth(),468- logo.getTextureHeight());
GL11.glTexCoord2f(0,1);
GL11.glVertex2f(192,468-logo.getTextureHeight());
GL11.glEnd();
}
public static void pause() {
Color.white.bind();
pause.bind(); // or GL11.glBind(texture.getTextureID());
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0,0);
GL11.glVertex2f(256,440);
GL11.glTexCoord2f(1,0);
GL11.glVertex2f(256+pause.getTextureWidth(),440);
GL11.glTexCoord2f(1,1);
GL11.glVertex2f(256+pause.getTextureWidth(),440- pause.getTextureHeight());
GL11.glTexCoord2f(0,1);
GL11.glVertex2f(256,440-pause.getTextureHeight());
GL11.glEnd();
}
public static void main(String[] args) throws Exception
{
System.setProperty("org.lwjgl.librarypath", new File("natives").getAbsolutePath());
System.out.println("Native Path: " + System.getProperty("org.lwjgl.librarypath"));
Display.setDisplayMode(new DisplayMode(640, 480));
Display.create();
init();
score = 0;
player = new Player();
exitbutton = new ExitButton(320, 61);
menubutton = new MenuButton(320, 95);
enemy = new Enemy();
coinlist = new ArrayList<Coin>(0);
bulletlist = new ArrayList<Bullet>(0);
bulletlist2 = new ArrayList<Bullet2>(0);
platformlist = new ArrayList<Platform>(0);
onewayplatformlist = new ArrayList<OneWayPlatform>(0);
Level1();
while(!Display.isCloseRequested())
{
setCamera();
drawBackground1();
for(Coin c: coinlist) c.draw();
for(Bullet b: bulletlist) b.draw();
for(Bullet2 b: bulletlist2) b.draw();
for(Platform b: platformlist) b.draw();
for(OneWayPlatform b: onewayplatformlist) b.draw();
enemy.draw();
player.draw();
states();
stateinput();
exitbutton.draw();
menubutton.draw();
Display.update();
Display.sync(60);
}
Display.destroy();
}
public static void stopsound(){
TinySound.shutdown();
}
public static void states(){
switch (state) {
case INTRO:
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
glColor3f(1.0f, 0.0f, 0.0f);
glRectf(0, 0, 640, 480);
break;
case GAME:
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
break;
case MAIN_MENU:
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
glColor3f(0.0f, 0.0f, 1.0f);
glRectf(0, 0, 640, 480);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, logo.getTextureID());
logo();
break;
case PAUSE:
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
glEnable(GL_COLOR_ARRAY);
glBegin(GL_QUADS);
glColor4d(0.5f, 0.5f, 0.5, 0.7);
glVertex2d(224, 40);
glVertex2d(416, 40);
glColor4d(0.7f, 0.7f, 0.7, 0.7);
glVertex2d(416, 440);
glVertex2d(224, 440);
glEnd();
glDisable(GL_COLOR_ARRAY);
glColor3f(0f, 0f, 0f);
glRectf(224, 40, 226, 440);
glRectf(416, 40, 414, 440);
glRectf(224, 40, 416, 42);
glRectf(224, 438, 416, 440);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, pause.getTextureID());
pause();
break;
}
}
public static void stateinput(){
while (Keyboard.next()) {
if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
if(state == State.GAME)
state = State.PAUSE;
else if(state == State.PAUSE)
state = State.GAME;
}
}
}
public static void jumpsound(){
TinySound.init();
Sound jump = TinySound.loadSound("/sound/Jump6.wav");
jump.play();
}
public static void shootsound(){
TinySound.init();
Sound shoot = TinySound.loadSound("/sound/Shoot1.wav");
shoot.play();
}
public static void selectsound(){
TinySound.init();
Sound select = TinySound.loadSound("/sound/select.wav");
select.play();
}
public static void hurtsound(){
TinySound.init();
Sound hurt = TinySound.loadSound("/sound/Hurt1.wav");
hurt.play();
}
public static void music(int track){
TinySound.init();
Music ocean = TinySound.loadMusic("/music/ocean.wav");
Music menu1 = TinySound.loadMusic("/music/menu1.wav");
if(track == 1){
ocean.play(true);
}
else if (track == 0){
menu1.play(true);
}
}
public static void setCamera(){
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL_COLOR_ARRAY);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable( GL11.GL_TEXTURE );
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glClearDepth(1);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glViewport(0,0,640,480);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, 640, 0, 480, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
}
public static void Level1(){
Game.platformlist.add(new Platform(16, 120));
Game.platformlist.add(new Platform(48, 120));
Game.platformlist.add(new Platform(624, 120));
Game.platformlist.add(new Platform(592, 120));
Game.onewayplatformlist.add(new OneWayPlatform(128, 200));
Game.onewayplatformlist.add(new OneWayPlatform(160, 200));
music(1);
}
public static void drawBackground1(){
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
glBegin(GL_QUADS);
glColor3d(0.4, 0.5, 0.7);
glVertex2d(640, 480);
glVertex2d(0, 480);
glColor3d(0.7, 0.8, 0.9);
glVertex2d(0, 0);
glVertex2d(640, 0);
glEnd();
glBegin(GL_QUADS);
glColor3d(0.3, 0.2, 0.1);
glVertex2d(0, 0);
glVertex2d(640, 0);
glColor3d(0.5, 0.2, 0.1);
glVertex2d(640, 32);
glVertex2d(0, 32);
glEnd();
glBegin(GL_QUADS);
glColor3d(0.5, 0.2, 0.1);
glVertex2d(0, 32);
glVertex2d(640, 32);
glColor3d(0.2, 0.5, 0.1);
glVertex2d(640, 47);
glVertex2d(0, 47);
glColor3d(1, 1, 1);
glEnd();
}
}
Related
i try to add to my LWJGL canvas some buttons and one image panel
but it wont work.
this is how it look like at the moment example image
i like to render in the grey square right next to the test image.
if i compile my code i get the following error:
Exception in thread "Thread-0" java.lang.RuntimeException: No OpenGL context found in the current thread.
at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124)
at org.lwjgl.opengl.GL20.glCreateProgram(GL20.java:253)
at util.ShaderProgram.createProgram(ShaderProgram.java:53)
at util.ShaderProgram.<init>(ShaderProgram.java:47)
at ExampleApplet$5.run(ExampleApplet.java:163)
what do i have do change?
thanks a lot.
adding swing to lwjgl is driving my crazy
here is my sourcecode:
import math.Mat4;
import math.Vec3;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import util.Mesh;
import util.OBJContainer;
import util.OBJGroup;
import util.ShaderProgram;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glViewport;
import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW;
public class ExampleApplet {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleApplet window = new ExampleApplet();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private ShaderProgram shaderProgram;
private ArrayList<Mesh> meshes;
private Mat4 modelMatrix;
private Mat4 viewMatrix;
private volatile float[] vertices;
private JFrame frame;
private Canvas canvas;
private JPanel controlPanel;
private JPanel canvasPanel;
private JPanel imagePanel;
private Thread gameThread;
private boolean running;
private int windowWidth;
private int windowHeight;
private volatile boolean needValidation;
private volatile boolean needUpdateViewport;
public ExampleApplet() {
frame = new JFrame();
frame.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
public void windowClosing(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
terminate();
}
public void windowActivated(WindowEvent arg0) {
}
});
frame.setTitle("Swing + LWJGL");
frame.setSize(1500, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
canvasPanel = new JPanel(new BorderLayout(0, 0));
imagePanel = new JPanel(new BorderLayout(0, 0));
canvas = new Canvas() {
private static final long serialVersionUID = -1069002023468669595L;
public void removeNotify() {
stopOpenGL();
}
};
canvas.addComponentListener(new ComponentListener() {
public void componentShown(ComponentEvent e) {
setNeedValidation();
}
public void componentResized(ComponentEvent e) {
setNeedValidation();
}
public void componentMoved(ComponentEvent e) {
setNeedValidation();
}
public void componentHidden(ComponentEvent e) {
setNeedValidation();
}
});
canvas.setIgnoreRepaint(true);
canvas.setSize(500,500);
canvasPanel.setSize(500,500);
//canvas.setPreferredSize(new Dimension(500, 500));
// canvas.setMinimumSize(new Dimension(320, 240));
canvas.setVisible(true);
canvasPanel.add(canvas, BorderLayout.CENTER);
try {
BufferedImage myImg = ImageIO.read((new File("/home/manu/workspaces/LWJGL_swing/resources/itworks-HDTV_720P.png")));
JLabel picLabel = new JLabel(new ImageIcon(resize(myImg, 1000, 500)));
imagePanel.add(picLabel);
} catch (Exception e) {
}
controlPanel = new JPanel(new BorderLayout(0, 0));
frame.add(canvasPanel, BorderLayout.LINE_END);
frame.add(imagePanel, BorderLayout.LINE_START);
frame.pack();
JPanel controls = new JPanel(new GridLayout(2,3));
controlPanel.add(controls,BorderLayout.EAST);
JButton openImage = new JButton("Bild öffnen");
JSlider brigthness = new JSlider(0,100,0);
controls.add(openImage);
controls.add(brigthness);
frame.add(controlPanel, BorderLayout.PAGE_END);
startOpenGL();
}
private void setNeedValidation() {
needValidation = true;
needUpdateViewport = true;
}
private void startOpenGL() {
System.out.println("StartOpenGL");
gameThread = new Thread() {
public void run() {
try {
shaderProgram = new ShaderProgram( "/home/manu/workspaces/LWJGL_swing/src/GUISample/Color_vs.glsl", "/home/manu/workspaces/LWJGL_swing/src/GUISample/Color_fs.glsl" );
modelMatrix = new Mat4();
viewMatrix = Mat4.translation( 0.0f, 0.0f, -3.0f );
meshes = new ArrayList<Mesh>();
windowWidth = 500;
windowHeight = 500;
loadObj("monkey.obj");
glEnable( GL_DEPTH_TEST );
Display.create();
Display.setParent(canvas);
running = true;
} catch (LWJGLException e) {
e.printStackTrace();
}
int i=0;
while (running) {
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
float fov = 60;
float near = 0.01f;
float far = 500.0f;
Mat4 projectionMatrix = Mat4.perspective( fov, windowWidth, windowHeight, near, far );
glViewport( 0, 0, windowWidth, windowHeight );
drawMeshes(viewMatrix, projectionMatrix);
GL11.glViewport(0, 0, 500,500);
if (i % 2 == 0) {
GL11.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
} else {
GL11.glClearColor(1.0f, 1.0f, 0.0f, 1.0f);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
}
Display.update();
try{
Thread.sleep(1000);
}catch (Exception e){
}
i++;
updateGL();
}
if (Display.isCreated()) {
Display.destroy();
}
}
};
gameThread.start();
}
public void drawMeshes( Mat4 viewMatrix, Mat4 projMatrix ) {
shaderProgram.useProgram();
shaderProgram.setUniform("uModel", modelMatrix);
shaderProgram.setUniform("uView", viewMatrix);
shaderProgram.setUniform("uProjection", projMatrix);
shaderProgram.setUniform("uColor",new Vec3(1.0f,0.0f,0.0f) );
shaderProgram.setUniform("uEnableShading", 0);
meshes.get(0).draw();
}
private void setupVertices() {
vertices = new float[4 * 2];
vertices[0] = 0.1f;
vertices[1] = 0.3f;
vertices[2] = 0.2f;
vertices[3] = 0.8f;
vertices[4] = 0.9f;
vertices[5] = 0.6f;
vertices[6] = 0.7f;
vertices[7] = 0.05f;
}
private void updateGL() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
render();
Display.update();
Display.sync(60);
if (needUpdateViewport) {
needUpdateViewport = false;
Rectangle rect = canvas.getBounds();
int w = (int) rect.getWidth();
int h = (int) rect.getHeight();
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, w, h, 0, -1, 1);
GL11.glViewport(0, 0, w, h);
}
int error = GL11.glGetError();
if (error != GL11.GL_NO_ERROR) {
String msg = "Unknown Error";
switch (error) {
case GL11.GL_INVALID_OPERATION:
msg = "Invalid Operation";
break;
case GL11.GL_INVALID_VALUE:
msg = "Invalid Value";
break;
case GL11.GL_INVALID_ENUM:
msg = "Invalid Enum";
break;
case GL11.GL_STACK_OVERFLOW:
msg = "Stack Overflow";
break;
case GL11.GL_STACK_UNDERFLOW:
msg = "Stack Underflow";
break;
case GL11.GL_OUT_OF_MEMORY:
msg = "Out of memory";
break;
}
throw new RuntimeException(msg);
}
}
private void render() {
float scale = 100;
GL11.glBegin(GL11.GL_QUADS);
GL11.glColor4f(1, 0, 0, 1);
GL11.glVertex3f(vertices[0] * scale, vertices[1] * scale, 0);
GL11.glColor4f(1, 0, 0, 1);
GL11.glVertex3f(vertices[2] * scale, vertices[3] * scale, 0);
GL11.glColor4f(1, 0, 0, 1);
GL11.glVertex3f(vertices[4] * scale, vertices[5] * scale, 0);
GL11.glColor4f(1, 0, 0, 1);
GL11.glVertex3f(vertices[6] * scale, vertices[7] * scale, 0);
GL11.glEnd();
}
private void stopOpenGL() {
System.out.println("StopOpenGL");
running = false;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void terminate() {
frame.dispose();
System.exit(0);
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
public void loadObj( String filename )
{
if( !filename.toLowerCase().endsWith(".obj") )
{
System.err.println( "Error in Sandbox.loadObj(): Invalid file extension, expected \".obj\":\n" + filename );
return;
}
OBJContainer objContainer = OBJContainer.loadFile( "monkey.obj" );
ArrayList<OBJGroup> objGroups = objContainer.getGroups();
for( OBJGroup group : objGroups )
{
float[] positions = group.getPositions();
float[] normals = group.getNormals();
int[] indices = group.getIndices();
Mesh mesh = new Mesh( GL_STATIC_DRAW );
mesh.setAttribute( 0, positions, 3 );
mesh.setAttribute( 1, normals, 3 );
mesh.setIndices( indices );
meshes.add( mesh );
}
}
}
You created the OpenGL context in a different thread. You have to use it in the same thread in which it's created.
Hi guys i am trying to draw a 100 by 100 image to my screen. However when i draw it, openGL draws it half the size of my square with a kind of border round the right and bottom edges.
This is my code:
package biz.boulter.lwjglgame;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import static org.lwjgl.opengl.GL11.*;
public class Game
{
public static final int WIDTH = 1000;
public static final int HEIGHT = WIDTH / 16 * 9;
private static Texture t;
private static void render()
{
glClear(GL_COLOR_BUFFER_BIT);
t.bind();
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2i(100, 100); // top-left
glTexCoord2f(1, 0);
glVertex2i(200, 100); // top-right
glTexCoord2f(1, 1);
glVertex2i(200, 200); // bottom-right
glTexCoord2f(0, 1);
glVertex2i(100, 200); // bottom-left
glEnd();
}
private static Texture loadTexture(String path) throws Exception{
return TextureLoader.getTexture("PNG", Game.class.getResourceAsStream(path));
}
public static void main(String[] args)
{
try
{
Display.setDisplayMode(new DisplayMode(1000, 1000 / 16*9));
Display.create();
t = loadTexture("/assets/guy.png");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1000, 1000/16*9, 0, 1, -1);
glEnable(GL_TEXTURE_2D);
glMatrixMode(GL_MODELVIEW);
while(!Display.isCloseRequested())
{
render();
Display.sync(60);
Display.update();
}
}catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
}
Why is it doing this. Also i am using slick-util.jar for the texture loading.
ScreenShot:
http://oi59.tinypic.com/13zyflk.jpg
I'm having an issue with lighting. I'm using GLSL to achieve this. All seems fine however I'm having an issue I believe its called "banding". Essentially it's giving a gradient like effect to my lights. Perhaps I'm doing something wrong, here is my code that I'm using a long with an image of the problem. I'm a beginner in GLSL and not sure if the code I have is the most efficient way.
Main Code
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.glUseProgram;
import java.util.ArrayList;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
public class Main {
public final int width = 1280;
public final int height = 720;
public ArrayList<Light> lights = new ArrayList<Light>();
private Shader shader;
private int bufferIndex;
private float[] vertices;
private Light lighter;
private Vector2f lightPos;
private boolean lockedIn = false;
private void render() {
glClear(GL_COLOR_BUFFER_BIT);
for (Light light : lights) {
shader.bind();
shader.setUniformf("lightLocation", light.getLocation().x,
light.getLocation().y);
shader.setUniform("lightColor", new Vector3f(light.getColors()));
shader.setUniform("ambientLight", new Vector3f(0.1f, 0.1f, 0.1f));
shader.setUniform("baseColor", new Vector3f(0.2f, 0.2f, 0.2f));
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
VertexBufferObject.GetInstance().render();
glDisable(GL_BLEND);
glUseProgram(0);
}
Display.update();
Display.sync(60);
}
private void input() {
if (Input.getMouse(0))
lockedIn = true;
else if (Input.getMouse(1))
lockedIn = false;
if (lockedIn) {
Mouse.setGrabbed(true);
lightPos.set(Input.getMousePosition().x, Input.getMousePosition().y);
if (Input.getKey(Input.KEY_UP)) {
lighter.setBlue((float) (lighter.getBlue() + 1));
lighter.setRed(lighter.getRed() + 1);
lighter.setGreen(lighter.getGreen() + 1);
}
if (Input.getKey(Input.KEY_DOWN)) {
lighter.setBlue((float) (lighter.getBlue() - 1));
lighter.setRed(lighter.getRed() - 1);
lighter.setGreen(lighter.getGreen() - 1);
}
if (Input.getKey(Input.KEY_L)) {
lights.add(new Light(new Vector2f(Input.getMousePosition().x,
Input.getMousePosition().y), lighter.getRed(), lighter
.getGreen(), lighter.getBlue()));
lighter.setBlue((float) Math.random() * 10);
lighter.setGreen((float) Math.random() * 10);
lighter.setRed((float) Math.random() * 10);
}
} else {
Mouse.setGrabbed(false);
}
}
private void setUpObjects() {
lightPos = new Vector2f(50, 50);
lighter = new Light(lightPos, 0, 5, 10);
lights.add(lighter);
lights.add(new Light(new Vector2f(60, 60), 120, 0, 120));
}
private void initialize() {
try {
Display.setDisplayMode(new DisplayMode(width, height));
Display.setTitle("2D Lighting");
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
vertices = new float[] { 0, 0, 0, width, 0, 0, 0, height, 0, width,
height, 0, 0, height, 0, width, 0, 0 };
bufferIndex = glGenBuffers();
int b2 = glGenBuffers();
VertexBufferObject.GetInstance().addObject(bufferIndex, vertices);
VertexBufferObject.GetInstance().addObject(
b2, new float[] { 100, 100, 0, 200, 100, 0, 100, 200, 0, 200, 200,
0, 100, 200, 0, 200, 100, 0 });
VertexBufferObject.GetInstance().initObjects();
shader = new Shader();
shader.addFragmentShader(Shader.loadShader("shader.frag"));
shader.addVertexShader(Shader.loadShader("shader.vertex"));
shader.compileShader();
shader.addUniform("ambientLight");
shader.addUniform("baseColor");
shader.addUniform("lightLocation");
shader.addUniform("lightColor");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
}
private void cleanup() {
shader.unbind();
Display.destroy();
}
public static void main(String[] args) {
Main main = new Main();
main.setUpObjects();
main.initialize();
while (!Display.isCloseRequested()) {
if (Input.getKey(Input.KEY_ESCAPE))
System.exit(1);
main.input();
main.render();
}
main.cleanup();
}
}
GLSL Code
#verson 120
uniform vec2 lightLocation;
uniform vec3 lightColor;
uniform vec3 ambientLight;
uniform vec3 baseColor;
void main() {
vec4 light = vec4(ambientLight, 1);
vec4 color = vec4(baseColor,1);
float distance = length(lightLocation - gl_FragCoord.xy);
float attenuation = 1 / distance;
vec4 lColor = vec4(attenuation, attenuation, attenuation, pow(attenuation, 3)) * vec4(lightColor, 1);
color += lColor;
gl_FragColor = color * light;
}
Vertex Shader
#version 120
void main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
A result from the code:
I'm currently experimenting with JOGL, and I ran into a problem which is really new to me. After starting the program, I see a blank window. After resize, I can normally see the content of it or if I do a minimise/restore. I suppose there is something with the events. The init() isn't called after the window created, but after the first trigger with resize or minimise.
Here is the code what I'm using for creating a window and setting up OpenGL:
package com.cogwheel.framework.graphics;
import java.awt.BorderLayout;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.*;
import javax.swing.JFrame;
import com.cogwheel.framework.init.CWGPreferences;
import com.cogwheel.framework.util.CWGDebug;
import com.jogamp.opengl.util.Animator;
public class CWGOpenGLScreen extends JFrame implements GLEventListener {
private static final String TAG = "CWGOpenGLScreen";
private GLCanvas mCanvas;
private long fpsLast = System.currentTimeMillis();
public CWGOpenGLScreen(){
this.setTitle(CWGPreferences.WINDOW_NAME);
this.setSize(CWGPreferences.WINDOW_SIZE);
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
///this.setResizable(false);
this.setVisible(true);
CWGDebug.info(TAG, "Window created!");
CWGSetupGL();
}
private void CWGSetupGL(){
GLCapabilities mCaps = new GLCapabilities(null);
mCaps.setHardwareAccelerated(true);
mCaps.setDoubleBuffered(true);
mCanvas = new GLCanvas(mCaps);
mCanvas.addGLEventListener(this);
this.add(mCanvas, BorderLayout.CENTER);
Animator animator = new Animator(mCanvas);
animator.start();
}
public void CWGDrawScene(GLAutoDrawable drawable)
{
CWGCalculateFPS();
GL2 gl = drawable.getGL().getGL2();
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glLoadIdentity();
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor3f(1.0f, 0.0f, 0.0f);
gl.glVertex3f(1.0f / 5 , 0.0f, 0.0f);
gl.glColor3f(0.0f, 1.0f, 0.0f);
gl.glVertex3f(1.0f / 5, 1.0f / 5, 0.0f);
gl.glColor3f(0.0f, 0.0f, 1.0f);
gl.glVertex3f(0.0f, 1.0f / 5, 1.0f / 5);
gl.glEnd();
gl.glFlush();
}
public void CWGCalculateFPS(){
this.setTitle(CWGPreferences.WINDOW_NAME + " [" + 1000 / (System.currentTimeMillis() - fpsLast) + "]");
fpsLast = System.currentTimeMillis();
}
public void init(GLAutoDrawable drawable){
/*GL2 gl = drawable.getGL().getGL2();
gl.glClearColor(0, 0, 0, 0);
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(0, 1, 0, 1, -1, 1);
*/
CWGDebug.info(TAG, "Init called!");
}
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height){}
public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged){}
public void display(GLAutoDrawable drawable){ CWGDrawScene(drawable); }
public void dispose(GLAutoDrawable drawable){}
}
Code quality is poor, I know, had no time to cleanup yet. Sorry for it.
Edit: got the problem, JFrame should not be shown until the GLEventListener is not initialised.
I've found your error (it has nothng to do with eclipse) : you should have set up the viewport (call to glViewport) whenever the canvas is resized => so you call glViewport(x,y, widht, height) in the reshape() method of the GLEventListener. So that OpenGL always knows where to draw scene, and not just when resizing frame.
Also, don't forget to setup screen (call to CWGSetupGL()) before showing it (otherwise you will still have the same problem, but only for a little time).
Here the modified code (I've removed calls to CWGDebug.info as you did not provide this class, but you can put them back) :
package com.cogwheel.framework.graphics;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import javax.swing.JFrame;
import com.jogamp.opengl.util.Animator;
public class CWGOpenGLScreen extends JFrame implements GLEventListener {
public static void main(String[] args) {
new CWGOpenGLScreen().setVisible(true);
}
private static final long serialVersionUID = 635066680731362587L;
private static final String TAG = "CWGOpenGLScreen";
private GLCanvas mCanvas;
private long fpsLast = System.currentTimeMillis();
public CWGOpenGLScreen(){
this.setTitle(TAG);
this.setSize(640,480);
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
///this.setResizable(false);
CWGSetupGL();
this.setVisible(true);
// CWGDebug.info(TAG, "Window created!");
}
private void CWGSetupGL(){
GLCapabilities mCaps = new GLCapabilities(null);
mCaps.setHardwareAccelerated(true);
mCaps.setDoubleBuffered(true);
mCanvas = new GLCanvas(mCaps);
mCanvas.addGLEventListener(this);
this.add(mCanvas, BorderLayout.CENTER);
final Animator animator = new Animator(mCanvas);
animator.start();
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
animator.stop();
System.exit(0);
}
});
}
public void CWGDrawScene(GLAutoDrawable drawable)
{
CWGCalculateFPS();
GL2 gl = drawable.getGL().getGL2();
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glLoadIdentity();
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor3f(1.0f, 0.0f, 0.0f);
gl.glVertex3f(1.0f / 5 , 0.0f, 0.0f);
gl.glColor3f(0.0f, 1.0f, 0.0f);
gl.glVertex3f(1.0f / 5, 1.0f / 5, 0.0f);
gl.glColor3f(0.0f, 0.0f, 1.0f);
gl.glVertex3f(0.0f, 1.0f / 5, 1.0f / 5);
gl.glEnd();
gl.glFlush();
}
public void CWGCalculateFPS(){
this.setTitle(TAG + " [" + 1000 / (System.currentTimeMillis() - fpsLast) + "]");
fpsLast = System.currentTimeMillis();
}
public void init(GLAutoDrawable drawable){
/*GL2 gl = drawable.getGL().getGL2();
gl.glClearColor(0, 0, 0, 0);
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(0, 1, 0, 1, -1, 1);
*/
// CWGDebug.info(TAG, "Init called!");
}
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height){
GL2 gl = drawable.getGL().getGL2();
gl.glViewport(x, y, width, height);
}
//public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged){}
public void display(GLAutoDrawable drawable){ CWGDrawScene(drawable); }
public void dispose(GLAutoDrawable drawable){}
}
Regards :)
Edit : apologizes, I haven't seen you replied yourself to your own question, by an edit.
Anyway, I still think you'd better call glViewport in reshape() method.
I have an application written in Java with JOGL that works fine on nvidia cards, but when I run it on an ati card, it works perfect until I add textures on 1 or more faces. Eventually, the java vm crashes hard, and it either says it is a crash in the ati driver thread or in the kernel system thread. I managed to recreate it in a simpler bit of code, but it takes a couple minutes to get the crash. up/ down rotates the image, return toggles the textures. keep doing that for a couple of minutes with an ati card and it will crash. I've tried it on about 10 or 15 machines.
package org.yourorghere;
import com.sun.opengl.util.Animator;
import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureIO;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.glu.GLU;
/**
* SimpleJOGL.java <BR>
* author: Brian Paul (converted to Java by Ron Cemer and Sven Goethel) <P>
*
* This version is equal to Brian Paul's version 1.2 1999/10/21
*/
public class SimpleJOGL implements GLEventListener, KeyListener {
GLCanvas canvas;
int lists;
float angle = 0.f;
boolean needsRotate = false;
boolean needsTexture = false;
Texture texture1;
Texture texture2;
Color c1 = Color.red;
Color c2 = Color.green;
public SimpleJOGL(GLCanvas canvas) {
this.canvas = canvas;
}
public static void main(String[] args) {
Frame frame = new Frame("Simple JOGL Application");
GLCanvas canvas = new GLCanvas();
SimpleJOGL sjogl = new SimpleJOGL(canvas);
canvas.addKeyListener(sjogl);
canvas.addGLEventListener(sjogl);
frame.add(canvas);
frame.setSize(640, 480);
final Animator animator = new Animator(canvas);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// Run this on another thread than the AWT event queue to
// make sure the call to Animator.stop() completes before
// exiting
new Thread(new Runnable() {
public void run() {
animator.stop();
System.exit(0);
}
}).start();
}
});
// Center frame
frame.setLocationRelativeTo(null);
frame.setVisible(true);
animator.start();
}
public void init(GLAutoDrawable drawable) {
// Use debug pipeline
// drawable.setGL(new DebugGL(drawable.getGL()));
GL gl = drawable.getGL();
System.err.println("INIT GL IS: " + gl.getClass().getName());
// Enable VSync
gl.setSwapInterval(1);
// double buffer
gl.glEnable(GL.GL_DOUBLEBUFFER);
drawable.setAutoSwapBufferMode(false);
// Enable VSync
gl.setSwapInterval(1);
// Setup the drawing area and shading mode
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl.glShadeModel(GL.GL_SMOOTH); // try setting this to GL_FLAT and see what happens.
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_REPLACE);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glDisable(GL.GL_BLEND);
// -- lighting --
gl.glEnable(GL.GL_COLOR_MATERIAL);
gl.glLightModelf(GL.GL_LIGHT_MODEL_TWO_SIDE, 1.0f);
gl.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE);
gl.glEnable(GL.GL_MAP1_VERTEX_3);
gl.glHint(GL.GL_POLYGON_SMOOTH_HINT, GL.GL_NICEST);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, new float[]{.3f,.3f,.3f,1.f},0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, new float[]{.55f,.55f,.55f,1.f},0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, new float[]{.05f,.05f,.05f,1.f}, 0);
gl.glFrontFace(GL.GL_CCW);
gl.glEnable(GL.GL_LIGHT0);
gl.glEnable(GL.GL_LIGHTING);
gl.glEnable(GL.GL_DEPTH_TEST);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, new float[]{.5f,.5f,.5f,1.0f}, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, new float[]{.05f, .05f, .05f, 1.0f}, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_EMISSION, new float[]{0.01f, 0.01f, 0.01f, 1.f}, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, new float[]{30}, 0);
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_COLOR_INDEXES, new float[]{1.0f, 0.0f, 0.0f, 1.0f}, 0);
gl.glCullFace(GL.GL_BACK);
gl.glDisable(GL.GL_BLEND);
gl.glEnable(GL.GL_RESCALE_NORMAL);
lists = gl.glGenLists(3);
this.needsRotate = true;
this.needsTexture = true;
}
private void reTexture(GL gl) {
BufferedImage image1 = makeImage(c1);
BufferedImage image2 = makeImage(c2);
makeShape(gl, image1, image2);
}
private BufferedImage makeImage(Color c) {
int y = 1200;
int x = 1024;
BufferedImage image = new BufferedImage(y, y, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setBackground(Color.white);
g.clearRect(0, 0, y,y);
Rectangle2D r = new Rectangle2D.Float(128,128,x-256,x-256);
g.setColor(c);
g.fill(r);
g.dispose();
return image;
}
private void makeShape(GL gl, BufferedImage image1, BufferedImage image2) {
float x = 1024.f/1200.f;
texture1 = TextureIO.newTexture(image1, false) ;
texture2 = TextureIO.newTexture(image2, false) ;
gl.glNewList(lists+1, GL.GL_COMPILE);
gl.glColor3f(0f, .8f, .4f);
// Drawing Using Triangles
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(0, 0);
gl.glVertex3f(0.0f, 0.0f, 0.0f); // Top
gl.glNormal3f(0, 0, 1);
gl.glTexCoord2f(x, 0);
gl.glVertex3f(1.0f, 0.0f, 0.0f); // Bottom Left
gl.glNormal3f(0, 0, 1);
gl.glTexCoord2f(x, x);
gl.glVertex3f(1.0f, 1.0f, 0.0f); // Bottom Right
gl.glNormal3f(0, 0, 1);
gl.glTexCoord2f(0, x);
gl.glVertex3f(0f, 1.0f, 0.0f); // Bottom Right
gl.glNormal3f(0, 0, 1);
gl.glEnd();
texture1.disable();
gl.glEndList();
gl.glNewList(lists+2, GL.GL_COMPILE);
texture2.enable();
texture2.bind();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(0, 0);
gl.glVertex3f(0.0f, 0.0f, 0.0f); // Top
gl.glNormal3f(0, 0, 1);
gl.glTexCoord2f(x, 0);
gl.glVertex3f(1.0f, 0.0f, 0.0f); // Bottom Left
gl.glNormal3f(0, 0, 1);
gl.glTexCoord2f(x, x);
gl.glVertex3f(1.0f, -1.0f, 0.0f); // Bottom Right
gl.glNormal3f(0, 0, 1);
gl.glTexCoord2f(0, x);
gl.glVertex3f(0f, -1.0f, 0.0f); // Bottom Right
gl.glNormal3f(0, 0, 1);
gl.glEnd();
texture2.disable();
gl.glEndList();
}
public void rotate(GL gl) {
gl.glNewList(lists, GL.GL_COMPILE);
gl.glLoadIdentity();
gl.glTranslatef(-2.f, 0.f, -6.f);
gl.glRotatef(angle, 1.0f, 0.f, 0.f);
gl.glCallList(lists+1);
gl.glRotatef(-45, 1.f, 0.f, 0.f);
gl.glCallList(lists+2);
gl.glEndList();
}
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
GL gl = drawable.getGL();
GLU glu = new GLU();
if (height <= 0) { // avoid a divide by zero error!
height = 1;
}
final float h = (float) width / (float) height;
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(45.0f, h, 1.0, 20.0);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();
}
public void display(GLAutoDrawable drawable) {
GL gl = drawable.getGL();
if (needsTexture) {
reTexture(gl);
needsTexture = false;
}
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, new float[]{1.f, 1.f, 1.f, 0.f}, 0);
gl.glLoadIdentity();
gl.glTranslatef(-2.f, 0.f, -6.f);
gl.glRotatef(angle, 1.0f, 0.f, 0.f);
texture1.enable();
texture1.bind();
gl.glCallList(lists+1);
texture1.disable();
gl.glRotatef(-45, 1.f, 0.f, 0.f);
gl.glCallList(lists+2);
// Flush all drawing operations to the graphics card
drawable.swapBuffers();
}
public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
angle -= 5;
needsRotate = true;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
angle += 5;
needsRotate = true;
}
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
Color c = c1;
c1 = c2;
c2 = c;
needsTexture = true;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
canvas.repaint();
}
}
thank you!
You need to dispose of the textures when you have finished with them, e.g.
private void makeShape(GL gl, BufferedImage image1, BufferedImage image2) {
if (texture1 != null) {
texture1.dispose();
}
texture1 = TextureIO.newTexture(image1, false) ;
if (texture2 != null) {
texture2.dispose();
}
texture2 = TextureIO.newTexture(image2, false) ;
// ...
}
otherwise you will eventually run out of texture names.
Note: Texture does not have a finalizer.