I'm trying to get a simple triangle drawn in Java using LWJGL.
I'm trying to get a simple triangle up, each with a corner of one specific color. Right now it is just giving me a blank screen.
Here is my code:
package com.ex;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.input.Keyboard;
public class ColoredTriangle {
public void start() {
try {
Display.setDisplayMode(new DisplayMode(640, 480));
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
// Init OpenGL
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, 640, 480, 0, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
boolean quit = false;
while (!quit) {
// Clear the screen.
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
// Begin drawing
GL11.glBegin(GL11.GL_TRIANGLES);
// Top & Red
GL11.glColor3f(1.0f, 0.0f, 0.0f);
GL11.glVertex2f(0.0f, 1.0f);
// Right & Green
GL11.glColor3f(0.0f, 1.0f, 0.0f);
GL11.glVertex2f(1.0f, 1.0f);
// Left & Blue
GL11.glColor3f(0.0f, 0.0f, 1.0f);
GL11.glVertex2f(1.0f, -1.0f);
GL11.glEnd();
Display.update();
if (Display.isCloseRequested() || Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
quit = true;
}
Display.destroy();
}
public static void main(String args[]) {
ColoredTriangle ct = new ColoredTriangle();
ct.start();
}
}
OpenGL 3 makes it easy to write complicated stuff, but at the expense that drawing a simple triangle is actually quite difficult. Don’t forget to cut’n paste the code on a regular basis.
So if we gave (1,1), the triangle would have one of its vertices at the top right corner of the screen. We’ll see in the next tutorial how to do some more interesting computations on the input position.
Shaders are programmed in a language called GLSL : GL Shader Language, which is part of OpenGL. Unlike C or Java, GLSL has to be compiled at run time, which means that each and every time you launch your application, all your shaders are recompiled. The two shaders are usually in separate files.
It is working perfectly fine, it's just that your triangle is 1 unit high and your window is 480 units high, so it only shows up as one pixel in the corner.
If you replace GL11.glOrtho(0, 640, 480, 0, 1, -1);
with GL11.glOrtho(-3.2, 3.2, -2.4, 2.4, -1, 1);
then you'll see everything just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With