VBO with textures, without deprecated functions - java

I am trying to write a basic Quad-renderer, using VBO, VAO, IBO and shaders.
I am trying to use mainly only one VBO, VAO, IBO and rebuffer the data when an element is added/removed.
Mostly everything worked fine, until I decided to implement textures, instead of color gradings.
It just doesn't draw anyhting, no matter what I try, because I want to avoid using deprecated functions like ClientStates and maybe use the textures inside the shaders.
Next to the problem, that nothing is being drawn, I have the problem that the Textures are saved inside the BRectangle class, and now I don't know, how to access them while using DrawElements.
And can I reuse my IBO, so I don't have to add the additional indices?
My current approach:
The Renderer, you can add a Rectangle atm and it will buffer the needed data.
public class ShaderRenderer {
public static final int POSITION_INDEX = 0; // index of vertex attribute "in_Position"
public static final int TEXTURE_INDEX = 1; // index of vertex attribute "in_Texture"
public static final int FLOAT_NUM_BYTES; // sizeof(float) in bytes
public static final int INT_NUM_BYTES; // sizeof(int) in bytes
public static final int VEC4_BYTES; // sizeof(vec4) in bytes
static {
FLOAT_NUM_BYTES = Float.SIZE / Byte.SIZE;
INT_NUM_BYTES = Integer.SIZE / Byte.SIZE;
VEC4_BYTES = 4 * FLOAT_NUM_BYTES;
}
private VAO vao = new VAO();
private VBO vbo = new VBO();
private IBO ibo = new IBO();
private int elements = 0;
public ShaderRenderer() {
try {
ShaderUtilities.compileShader("shaders/screen.vert", "shaders/screen.frag", POSITION_INDEX, TEXTURE_INDEX);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void add( BRectangle rect ) {
// Bind the VAO
// This OpenGL-object groups the "in_Position" and "in_Color"
// vertex attributes.
vao.bind();
// Bind the VBO and add the FloatBuffer from the Rect
vbo.bind();
vbo.addBuffer(rect.vertexData);
ibo.bind();
ibo.addIndices(generateIndices());
ibo.buffer();
//==============================================================
// Now we tell OpenGL that we will use POSITION_INDEX and COLOR_INDEX
// to communicate respectively the vertex positions and vertex colors
// to our shaders.
{
// First we enable the indices. This will affect the vertex
// array object from above.
glEnableVertexAttribArray(POSITION_INDEX);
Util.checkGLError();
// Then we tell OpenGL how it should read the GL_ARRAY_BUFFER
// (to which we have bound our vertex data, see above).
// The position data starts at the beginning of the vertex data
glVertexAttribPointer(POSITION_INDEX, 4, GL_FLOAT, false,
2 * VEC4_BYTES, 0);
Util.checkGLError();
// The color data starts after the first 4 floats of position data
glVertexAttribPointer(TEXTURE_INDEX, 2, GL_FLOAT, false,
0, VEC4_BYTES);
Util.checkGLError();
}
vbo.bufferData();
// Just to be VERY clean, we will unbind the vertex attribute object
// and only bind it when we render. This way we cannot accidentally modify
// it anymore.
vao.unbind();
// Only after the vertex array is disabled, we unbind the buffers
// to the GL_ARRAY_BUFFER and GL_ELEMENT_ARRAY_BUFFER targets, because
// otherwise the vertex array object would become invalid again.
vbo.unbind();
ibo.unbind();
}
void DestroyVBO() {
glDisableVertexAttribArray(POSITION_INDEX);
Util.checkGLError();
glDisableVertexAttribArray(TEXTURE_INDEX);
Util.checkGLError();
glBindBuffer(GL_ARRAY_BUFFER, 0);
Util.checkGLError();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
Util.checkGLError();
glDeleteBuffers(ibo.id);
Util.checkGLError();
glDeleteBuffers(vbo.id);
Util.checkGLError();
glBindVertexArray(0);
Util.checkGLError();
glDeleteVertexArrays(vao.id);
Util.checkGLError();
}
private int[] generateIndices() {
int c = elements * 3;
int v[] = { c, c+1, c+2,
c, c+3, c+2};
elements++;
return v;
}
public void render () {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Util.checkGLError();
vao.bind();
glDrawElements(
GL_TRIANGLES,
ibo.size,
GL_UNSIGNED_INT,
0);
Util.checkGLError();
vao.unbind();
}
}
My basic Rectangle class
public class BRectangle {
final int amountOfVertices = 8;
final int vertexSize = 3;
final int textureSize = 2;
public FloatBuffer vertexData;
Texture texture;
public BRectangle(float x, float y ) {
float[] VerticesArray = new float[]{
-0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.1f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
-0.1f, 0.4f, 0.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.4f, 0.0f, 1.0f, 0.0f, 1.0f
};
vertexData = BufferUtils.createFloatBuffer(24);
vertexData.put(VerticesArray);
try {
texture = Textures.loadTexture("data/floor.jpg");
} catch (IOException e) {
e.printStackTrace();
}
glBindTexture(GL_TEXTURE_2D, texture.getTextureID());
}
}
The test with main[]
public class ShaderTest {
ShaderRenderer sr;
FpsCounter c;
public ShaderTest() {
}
public void create() throws LWJGLException, Exception {
new SimpleDisplay(800, 600, "test", false, false);
glOrtho(0, 800, 0, 600, 1, -1);
//Keyboard
Keyboard.create();
c = new FpsCounter();
Textures.setUpTextureLoader();
//Mouse
Mouse.setGrabbed(false);
Mouse.create();
sr = new ShaderRenderer();
//OpenGL
initGL();
}
public void destroy() {
Mouse.destroy();
Keyboard.destroy();
Display.destroy();
}
public void initGL() throws IOException {
ShaderUtilities.compileShader("shaders/screen.vert", "shaders/screen.frag", ShaderRenderer.POSITION_INDEX, ShaderRenderer.TEXTURE_INDEX);
sr.add(new BRectangle(0f, 0f));
}
public void processKeyboard() {
}
public void processMouse() {
}
public void render() throws LWJGLException {
sr.render();
}
public void run() throws LWJGLException {
while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
if (Display.isVisible()) {
processKeyboard();
processMouse();
update();
render();
} else {
if (Display.isDirty()) {
render();
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
}
Display.update();
//Display.sync(60);
}
}
public void update() {
c.updateFPS();
}
public static void main(String[] args) {
ShaderTest main = null;
try {
main = new ShaderTest();
main.create();
main.run();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (main != null) {
main.destroy();
}
}
}
}
and the openglinit
public static void initGLSlim() {
glClearColor(0, 0, 0, 0);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glEnable(GL11.GL_TEXTURE_2D);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 800, 600, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
vertex shader
#version 140
in vec4 in_Position;
in vec2 in_Texture;
out vec2 out_Texture;
void main(void)
{
gl_Position = vec4(in_Position.x *0.75 ,in_Position.y, in_Position.z, in_Position.w);
out_Texture = in_Texture;
}
fragment shader
#version 140
in vec2 out_Texture;
uniform sampler2D mytexture;
out vec4 fragColor;
void main(void)
{
fragColor = texture2D(mytexture, out_Texture);
}

Your stride parameters are not correct.
Here's what you have:
glVertexAttribPointer(POSITION_INDEX, 4, GL_FLOAT, false, 2 * VEC4_BYTES, 0);
glVertexAttribPointer(TEXTURE_INDEX, 2, GL_FLOAT, false, 0, VEC4_BYTES);
You're telling the position index that it has 8 float stride, which is not correct. As far as I can tell you're uploading 4 vertices, with 6 floats per vertex (4x position + 2x texture). That means your POSITION stride should be 6 * FLOAT_NUM_BYTES.
Your texture stride should be the same, as it's packed into the same array. Here you're telling it that the texcoords are tightly packed, but in reality theres only one pair of texcoords per 6 floats. So again you need 6 * FLOAT_NUM_BYTES here.
And can I reuse my IBO, so I don't have to add the additional indices?
Yes, you can use an IBO to draw as many objects as you want, provided that they all want the same indices.
Other less serious comments:
You don't need to clearColor to zero in initialization, it's zero by
default.
You don't need to disable depth_test/lighting in
initialization, they are off by default.
Don't call glEnable(GL_TEXTURE_2D) when you're using shaders. This
switch only enables texturing for the fixed pipeline, and it has no effect on shader programs. This will generate an error if you ever move to a core profile, so just get rid of it.

Related

GP/GPU : ping pong technique with JOGL

I've tried to implement an reaction-diffusion model on GPU with JOGL and GLSL.
I use a ping pong technique with 2 FramebufferObject ( I've tried too with one FBO and 2 Colors attachements without success).
Shader seems correct since I've tried it in unity (with some adaptations) and it works.
After one week of trying many things, i'm completely out of idea to make this code works. I'm really not specialist of JOGL, so maybe i miss something evident.
The result is an image which becomes white with time : no reaction-diffusion behaviors and I don't understand why !
Thanks in advance for helps. Here is my code :
package gpu2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.nio.IntBuffer;
import java.nio.FloatBuffer;
import java.io.File;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.util.FPSAnimator;
import com.jogamp.opengl.GLFBODrawable;
import com.jogamp.opengl.FBObject;
import com.jogamp.opengl.FBObject.Colorbuffer;
import com.jogamp.opengl.FBObject.ColorAttachment;
import com.jogamp.opengl.FBObject.TextureAttachment;
import com.jogamp.opengl.util.glsl.ShaderCode;
import com.jogamp.opengl.util.glsl.ShaderProgram;
import com.jogamp.opengl.util.glsl.ShaderUtil;
import com.jogamp.opengl.util.GLBuffers;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureIO;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLOffscreenAutoDrawable;
import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.util.awt.AWTGLReadBufferUtil;
import com.jogamp.opengl.GLDrawableFactory;
import static com.jogamp.opengl.GL.*; // GL constants
import static com.jogamp.opengl.GL2.*; // GL2 constants
import gpu2.ModelParam;
/**
* JOGL 2.0 Program Template (GLCanvas)
* This is a "Component" which can be added into a top-level "Container".
* It also handles the OpenGL events to render graphics.
*/
#SuppressWarnings("serial")
public class JOGL2Setup_GLCanvas extends GLCanvas implements GLEventListener {
// Define constants for the top-level container
private static String TITLE = "JOGL 2.0 Setup (GLCanvas)"; // window's title
private static final int CANVAS_WIDTH = 512; // width of the drawable
private static final int CANVAS_HEIGHT = 512; // height of the drawable
private static final int FPS = 30; // animator's target frames per second
private final float[] canvasVertices = {
-1f, -1f, 0.0f,
-1f, 1f, 0.0f,
1f, -1f, 0.0f,
1f, 1f, 0.0f,
};
private final float[] canvasTexCoords = {
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
};
/** The entry main() method to setup the top-level container and animator */
public static void main(String[] args) {
// Run the GUI codes in the event-dispatching thread for thread safety
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// Create the OpenGL rendering canvas
GLCanvas canvas = new JOGL2Setup_GLCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
// Create a animator that drives canvas' display() at the specified FPS.
final FPSAnimator animator = new FPSAnimator(canvas, FPS, true);
// Create the top-level container
final JFrame frame = new JFrame(); // Swing's JFrame or AWT's Frame
frame.getContentPane().add(canvas);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// Use a dedicate thread to run the stop() to ensure that the
// animator stops before program exits.
new Thread() {
#Override
public void run() {
if (animator.isStarted()) animator.stop();
System.exit(0);
}
}.start();
}
});
frame.setTitle(TITLE);
frame.pack();
frame.setVisible(true);
animator.start(); // start the animation loop
}
});
}
// Setup OpenGL Graphics Renderer
private GLU glu; // for the GL Utility
private GL2 gl;
//OpenGl data
private int vboVertices;
private int vboTextCoord;
private Texture textureFile;
private FBObject fbo[];
private ShaderProgram shaderCompute;
private ShaderProgram shaderVisu;
private ShaderProgram shaderComputeInit;
private int currentSourceBuffer = 0;
private int currentDestBuffer = 1;
private int currentFrame = 0;
private int maxFrameCount = 5000000;
private float clearUniform = 0;
ModelParam params = new ModelParam();
public JOGL2Setup_GLCanvas() {
this.addGLEventListener(this);
}
#Override
public void init(GLAutoDrawable drawable) {
gl = drawable.getGL().getGL2(); // get the OpenGL graphics context
glu = new GLU(); // get GL Utilities
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // set background (clear) color
gl.glEnable(GL_TEXTURE_2D);
gl.glEnable( GL_COLOR_MATERIAL );
gl.glEnable( GL_FRAMEBUFFER );
gl.glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NEAREST); // best perspective correction
viewOrtho(gl);
gl.glViewport(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
int[] buffers = new int[2];
gl.glGenBuffers(2, buffers, 0);
vboVertices = buffers[0];
vboTextCoord = buffers[1];
gl.glBindBuffer(GL_ARRAY_BUFFER, vboVertices);
gl.glBufferData(GL_ARRAY_BUFFER, canvasVertices.length*(Float.SIZE/Byte.SIZE)*3, FloatBuffer.wrap(canvasVertices), GL_STATIC_DRAW);
gl.glBindBuffer(GL_ARRAY_BUFFER, vboTextCoord);
gl.glBufferData(GL_ARRAY_BUFFER, canvasTexCoords.length*(Float.SIZE/Byte.SIZE)*2, FloatBuffer.wrap(canvasTexCoords), GL_STATIC_DRAW);
gl.glBindBuffer( GL_ARRAY_BUFFER, 0 );
// ------------ create Texture Source------------------------
textureFile = initializeTexture();
if (textureFile==null) {
System.out.println("cannot load texture from disk");
}
// ------------ load shaders ------------------------
shaderCompute = loadShader(gl, "compute.vsh", "compute.fsh");
shaderComputeInit = loadShader(gl, "compute.vsh", "computeInit.fsh");
shaderVisu = loadShader(gl, "visu.vsh", "visu.fsh");
// ------------ create FBO ------------------------
initFBO();
}
/**
* Called back by the animator to perform rendering.
*/
#Override
public void display(GLAutoDrawable drawable) {
if (currentFrame < maxFrameCount) {
prepareNextStep();
renderToFBO();
currentFrame++;
}
renderFBOToScreen();
}
private void prepareNextStep() {
currentSourceBuffer = 1 - currentSourceBuffer;
currentDestBuffer = 1 - currentDestBuffer;
}
private void renderToFBO()
{
fbo[currentDestBuffer].bind(gl);
//gl.glClear(GL_COLOR_BUFFER_BIT);
viewOrtho(gl);
shaderCompute.useProgram(gl, true);
setShaderUniformFloat(gl, shaderCompute.program(), "diffuseU", 0.211f);
setShaderUniformFloat(gl, shaderCompute.program(), "diffuseV", 0.088f);
setShaderUniformFloat(gl, shaderCompute.program(), "feed", 0.007f);
setShaderUniformFloat(gl, shaderCompute.program(), "kill", 0.08f);
setShaderUniformFloat(gl, shaderCompute.program(), "Tech", 1f);
setShaderUniformFloat(gl, shaderCompute.program(), "currentFrame", currentFrame);
setShaderUniformFloat2(gl, shaderCompute.program(), "resolution", CANVAS_WIDTH, CANVAS_HEIGHT);
drawDataBuffer(shaderCompute, true);
shaderCompute.useProgram(gl, false);
fbo[currentDestBuffer].unbind(gl);
}
void drawDataBuffer(ShaderProgram currentShader, boolean sencondImage) {
// --- draw vbo
gl.glEnableClientState(GL_VERTEX_ARRAY);
gl.glEnableClientState(GL_TEXTURE_COORD_ARRAY);
//textcoords
gl.glBindBuffer(GL_ARRAY_BUFFER,vboTextCoord);
gl.glTexCoordPointer(2, GL_FLOAT, 0, 0);
//vertices
gl.glBindBuffer( GL_ARRAY_BUFFER, vboVertices );
gl.glVertexPointer(3, GL_FLOAT, 0, 0);
//activate texture data from last fbo
final FBObject.Colorbuffer texSource = (FBObject.Colorbuffer) fbo[currentSourceBuffer].getColorbuffer(0);
gl.glActiveTexture(GL_TEXTURE0);
gl.glBindTexture(GL_TEXTURE_2D, texSource.getName());
setShaderUniform1i(gl, currentShader.program(), "textureData", 0);
if (sencondImage) {
//activate texture with image from file
gl.glActiveTexture(GL_TEXTURE1);
gl.glBindTexture(GL_TEXTURE_2D, textureFile.getTextureObject());
textureFile.bind(gl);
setShaderUniform1i(gl, currentShader.program(), "textureImage", 1);
}
//draw buffer on screens
gl.glDrawArrays(GL_TRIANGLE_STRIP, 0, canvasVertices.length / 3);
//disable texture image
if (sencondImage) {
gl.glActiveTexture(GL_TEXTURE1);
textureFile.disable(gl);
}
//disable texture data
gl.glActiveTexture(GL_TEXTURE0);
gl.glDisable(texSource.getName());
gl.glDisableClientState(GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL_VERTEX_ARRAY);
}
public void renderFBOToScreen()
{
gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear color and depth buffers
gl.glLoadIdentity(); // reset the model-view matrix
viewOrtho(gl);
gl.glEnable(GL_TEXTURE_2D);
final FBObject.Colorbuffer tex0 = (FBObject.Colorbuffer) fbo[currentDestBuffer].getColorbuffer(0);
gl.glActiveTexture(GL_TEXTURE0);
gl.glBindTexture(GL_TEXTURE_2D, tex0.getName());
//activate shader
shaderVisu.useProgram(gl, true);
// --- draw vbo
gl.glEnableClientState(GL_VERTEX_ARRAY);
gl.glEnableClientState(GL_TEXTURE_COORD_ARRAY);
//textcoords
gl.glBindBuffer(GL_ARRAY_BUFFER, vboTextCoord);
gl.glTexCoordPointer(2, GL_FLOAT, 0, 0);
//vertices
gl.glBindBuffer( GL_ARRAY_BUFFER, vboVertices );
gl.glVertexPointer(3, GL_FLOAT, 0, 0);
//draw buffer on screens
gl.glDrawArrays(GL_TRIANGLE_STRIP, 0, canvasVertices.length / 3);
gl.glDisableClientState(GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL_VERTEX_ARRAY);
gl.glBindBuffer( GL_ARRAY_BUFFER, 0 );
//desactivate shader
shaderVisu.useProgram(gl, false);
}
private void initFBO()
{
try {
gl.glEnable(GL_TEXTURE_2D);
fbo = new FBObject[2];
//first fbo
fbo[currentSourceBuffer] = new FBObject(); // Create FrameBuffer
fbo[currentSourceBuffer].init(gl, CANVAS_WIDTH, CANVAS_HEIGHT, 0);
fbo[currentSourceBuffer].reset(gl, CANVAS_WIDTH, CANVAS_HEIGHT, 0); // int width, height - size of FBO, can be resized with the same call
fbo[currentSourceBuffer].bind(gl);
int tex = genTexture(gl);
gl.glBindTexture(GL_TEXTURE_2D, tex);
gl.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, CANVAS_WIDTH, CANVAS_HEIGHT, 0, GL_RGBA, GL_FLOAT, null);
fbo[currentSourceBuffer].attachTexture2D(gl, 0, GL_RGBA32F, GL_RGBA, GL_FLOAT, GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
//gl.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
int DrawBuffers[] = {GL_COLOR_ATTACHMENT0};
gl.glDrawBuffers(1, DrawBuffers, 0); // "1" is the size of DrawBuffers
fbo[currentSourceBuffer].unbind(gl);
//second fbo
fbo[currentDestBuffer] = new FBObject(); // Create FrameBuffer
fbo[currentDestBuffer].init(gl, CANVAS_WIDTH, CANVAS_HEIGHT, 0);
fbo[currentDestBuffer].reset(gl, CANVAS_WIDTH, CANVAS_HEIGHT, 0); // int width, height - size of FBO, can be resized with the same call
fbo[currentDestBuffer].bind(gl);
tex = genTexture(gl);
gl.glBindTexture(GL_TEXTURE_2D, tex);
gl.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, CANVAS_WIDTH, CANVAS_HEIGHT, 0, GL_RGBA, GL_FLOAT, null);
fbo[currentDestBuffer].attachTexture2D(gl, 0, GL_RGBA32F, GL_RGBA, GL_FLOAT, GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
//ogl.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
gl.glDrawBuffers(1, DrawBuffers, 1); // "1" is the size of DrawBuffers
fbo[currentDestBuffer].unbind(gl);
} catch (Exception e) {
System.out.println("Problem with fbo init " + e);
e.printStackTrace();
}
}
private Texture initializeTexture() {
Texture t = null;
try {
t = TextureIO.newTexture(new File("e:/shaders/wiki.jpg"), false);
t.setTexParameteri(gl, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
t.setTexParameteri(gl, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
t.setTexParameteri(gl, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
t.setTexParameteri(gl, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
} catch (Exception e) {
System.out.println("Unable to read texture file: " + e);
e.printStackTrace();
}
return t;
}
private ShaderProgram loadShader(GL2 gl, String vertexShader, String fragmentShader)
{
ShaderCode vertShader = ShaderCode.create(gl, GL2.GL_VERTEX_SHADER, 1, getClass(), new String[]{"e:/shaders/"+vertexShader},false);
vertShader.compile(gl);
ShaderCode fragShader = ShaderCode.create(gl, GL2.GL_FRAGMENT_SHADER, 1, getClass(), new String[]{"e:/shaders/"+fragmentShader},false);
fragShader.compile(gl);
ShaderProgram newShader = new ShaderProgram();
newShader.init(gl);
newShader.add(vertShader);
newShader.add(fragShader);
newShader.link(gl, System.out);
vertShader.destroy(gl);
fragShader.destroy(gl);
return newShader;
}
public static void setShaderUniform1i(GL2 inGL,int inProgramID,String inName,int inValue) {
int tUniformLocation = inGL.glGetUniformLocation(inProgramID,inName);
if (tUniformLocation != -1) {
inGL.glUniform1i(tUniformLocation, inValue);
} else {
System.out.println("UNIFORM COULD NOT BE FOUND! NAME="+inName);
}
}
public static void setShaderUniformFloat(GL2 inGL,int inProgramID,String inName,float inValue) {
int tUniformLocation = inGL.glGetUniformLocation(inProgramID,inName);
if (tUniformLocation != -1) {
inGL.glUniform1f(tUniformLocation, inValue);
} else {
System.out.println("UNIFORM COULD NOT BE FOUND! NAME="+inName);
}
}
public static void setShaderUniformFloat2(GL2 inGL,int inProgramID,String inName,float inValue1 ,float inValue2) {
int tUniformLocation = inGL.glGetUniformLocation(inProgramID,inName);
if (tUniformLocation != -1) {
inGL.glUniform2f(tUniformLocation, inValue1, inValue2);
} else {
System.out.println("UNIFORM COULD NOT BE FOUND! NAME="+inName);
}
}
private void viewOrtho(GL2 gl) // Set Up An Ortho View
{
gl.glMatrixMode(GL_PROJECTION); // Select Projection
gl.glPushMatrix(); // Push The Matrix
gl.glLoadIdentity(); // Reset The Matrix
gl.glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
gl.glMatrixMode(GL_MODELVIEW); // Select Modelview Matrix
gl.glPushMatrix(); // Push The Matrix
gl.glLoadIdentity(); // Reset The Matrix
}
private int genTexture(GL2 gl) {
final int[] tmp = new int[1];
gl.glGenTextures(1, tmp, 0);
return tmp[0];
}
/**
* Called back before the OpenGL context is destroyed. Release resource such as buffers.
*/
#Override
public void dispose(GLAutoDrawable drawable) { }
}
And the corresponding GLSL Shader :
#version 120
uniform sampler2D textureData;
uniform sampler2D textureImage;
uniform vec2 resolution;
uniform float diffuseU;
uniform float diffuseV;
uniform float feed;
uniform float kill;
uniform float Tech = 1.0;
uniform float currentFrame = 0.0;
void main() {
//coords
vec2 position = ( gl_FragCoord.xy / resolution.xy );
vec2 pixel = 1./resolution;
//get data from texture
vec4 imgSource = texture2D(textureImage, gl_TexCoord[0].st);
vec2 oldUV = texture2D(textureData, gl_TexCoord[0].st).rg;
if(currentFrame<10){
if (distance(position,vec2(0.5,0.5 - currentFrame * 0.01f)) < 0.2f)
oldUV = vec2(0.0,0.2);
else if (distance(position,vec2(0.5,0.5 - currentFrame * 0.01f)) < 0.3f)
oldUV = vec2(0.5,0.1);
else
oldUV = vec2(0.1,0.0);
gl_FragColor = vec4(oldUV.rg, 0.0, 1.0);
return;
}
//get neightboors
vec2 dataUp = texture2D(textureData, position + pixel * vec2(0., 1.)).rg;
vec2 dataDown = texture2D(textureData, position + pixel * vec2(0., -1.)).rg;
vec2 dataLeft = texture2D(textureData, position + pixel * vec2(-1., 0.)).rg;
vec2 dataRight = texture2D(textureData, position + pixel * vec2(1., 0.)).rg;
//adapt parameters
vec2 imgParam = imgSource.rg;
float dU = diffuseU ;//+ 0.01 * (imgParam - 0.5);
float dV = diffuseV ;//+ 0.01 * (imgParam - 0.5);
float F = feed ;//+ 0.01 * (imgParam - 0.5);
float K = kill ;//+ 0.01 * (imgParam - 0.5);
//compute new values
vec2 laplace = (dataUp+dataDown+dataLeft+dataRight) - 4.0 * oldUV;
float uvv = oldUV.r * oldUV.g * oldUV.g;
// calculate delta quantities
float du = dU * laplace.r - uvv + F*(1.0 - oldUV.r);
float dv = dV * laplace.g + uvv - (F+K)*oldUV.g;
vec2 newUV = oldUV + vec2(du, dv)* Tech;
gl_FragColor = vec4(newUV.rg, 0.0, 1.0);
}
Few considerations:
avoid deprecated OpenGL (and GLU), use GL4 (or GL3)
unless you need awt/swt/swing, prefer newt, more here
prefer Animator instead of FPSAnimator, more here
prefer direct buffers instead of arrays, since otherwise jogl has to create them underneath and you can't keep trace (= deallocate when done) of those native allocations
GL4 will allow you also to avoid all those uniform overhead (and also potential bugs) you have to deal with (especially during runtime), thanks to explicit locations
prefer direct buffer management instead of FBObject for the moment unless you really know what FBObject is doing. Once you get it working, you can move on using that class. This may be (one of the) cause your code is not working, because something is not getting setup up as you need. Moreover, the lines of codes needed to replace FBObject are essentially the same
(if you can't use explicit location for any reason) prefer some literal way to define the texture uniform location, it is usually another tricky part causing bugs, something like this
prefer also a sampler for the textures, gives you more flexibility
don't wait one week next time, let us know earlier! :) Frustation can be a nasty thing that put you down easily. Together we can help you getting it working ;)

LWJGL 3, VAO and Shader not rendering

I am using LWJGL 3 and Shaders with VAO's. My current implementation does not draw the VAO when using the shaders. However the VAO will draw when not using shaders but the VAO will be white. My question is what am I missing in my shader setup that is preventing me from seeing the VAO when using shaders?
Main Class.
Shader and VAO setup is in the gameStart() method.
public class Test {
/** Window Properties **/
private int
HEIGHT = 800,
WIDTH = 1200,
RESIZABLE = GL11.GL_FALSE,
REFRESH_RATE = 60;
private String TITLE = "test";
// The window handler
private long window;
// callback reference instances
private GLFWErrorCallback errorCallback;
private GLFWKeyCallback keyCallback;
private void preWindowSetup() {
// Setup an error callback
GLFW.glfwSetErrorCallback(errorCallback = errorCallbackPrint(System.err));
// Initialize GLFW
if (GLFW.glfwInit() != GL11.GL_TRUE)
exit();
}
private void windowSetup() {
// Configure Window Properties
glfwDefaultWindowHints();
GLFW.glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // Keep the window hidden
glfwWindowHint(GLFW_RESIZABLE, RESIZABLE); // Do not allow resizing
glfwWindowHint(GLFW_REFRESH_RATE, REFRESH_RATE); // Refresh rate
// Create the window
window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, NULL, NULL);
if ( window == NULL )
exit();
// Get the resolution of the primary monitor
ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
// Center our window
glfwSetWindowPos(
window,
(GLFWvidmode.width(vidmode) - WIDTH) / 2,
(GLFWvidmode.height(vidmode) - HEIGHT) / 2
);
}
private void callbackSetup() {
// Setup a key callback. It will be called every time a key is pressed, repeated or released.
glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
#Override
public void invoke(long window, int key, int scancode, int action, int mods) {//TODO Dispatch key events
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
Tasker.executeASyncTask("GLFW_MAIN_THREAD");
}
});
}
public void initGL() {
preWindowSetup();
windowSetup();
callbackSetup();
glfwMakeContextCurrent(window); // Make the OpenGL context current
glfwShowWindow(window); // Make the window visible
GLContext.createFromCurrent(); // Bind lwjgl with GLFW
// Initialize openGl
GL11.glViewport(0, 0, WIDTH, HEIGHT);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, WIDTH, 0, HEIGHT, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
// Enable alpha transparency (for overlay image)
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthFunc(GL11.GL_LEQUAL);
GL11.glShadeModel(GL11.GL_SMOOTH);
}
public void gameStart() {
System.out.println("LWJGL Version: ["+Sys.getVersion()+"]");
System.out.println("OpenGL Version: ["+GL11.glGetString(GL11.GL_VERSION)+"]");
// ===============================================================================================
// =================== Shader Setup =====================
String vertPath = "src/test/java/org/ajgl/test/graphics/shaders/VertexShaderTest.glsl";
String fragPath = "src/test/java/org/ajgl/test/graphics/shaders/FragmentShaderTest.glsl";
int sahderVert = GL20.glCreateShader(GL20.GL_VERTEX_SHADER);
GL20.glShaderSource(sahderVert, Shader.loadShader(vertPath));
GL20.glCompileShader(sahderVert);
int sahderFrag = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER);
GL20.glShaderSource(sahderFrag, Shader.loadShader(fragPath));
GL20.glCompileShader(sahderFrag);
// =================== Shader Setup =====================
// =================== Shader Check =====================
int status = GL20.glGetShaderi(sahderVert, GL20.GL_COMPILE_STATUS);
if (status != GL11.GL_TRUE) {
throw new RuntimeException(GL20.glGetShaderInfoLog(sahderVert));
}
int statusN = GL20.glGetShaderi(sahderFrag, GL20.GL_COMPILE_STATUS);
if (statusN != GL11.GL_TRUE) {
throw new RuntimeException(GL20.glGetShaderInfoLog(sahderFrag));
}
// =================== Shader Check =====================
// =================== Shader Program ===================
int programID = GL20.glCreateProgram();
GL20.glAttachShader(programID, sahderVert);
GL20.glAttachShader(programID, sahderFrag);
GL20.glBindAttribLocation(programID, 0, "position");
GL20.glBindAttribLocation(programID, 1, "color");
GL20.glLinkProgram(programID);
// =================== Shader Program ===================
// =============== Shader Program Check =================
int statusP = GL20.glGetProgrami(programID, GL20.GL_LINK_STATUS);
if (statusP != GL11.GL_TRUE) {
throw new RuntimeException(GL20.glGetProgramInfoLog(programID));
}
// =============== Shader Program Check =================
// =================== VAO Setup ========================
FloatBuffer vertexBufferVAO = BufferUtils.createFloatBuffer(9);
vertexBufferVAO.put(new float[]{600,10,0, 550,50,0, 500,10,0});
vertexBufferVAO.flip();
FloatBuffer colorBufferVAO = BufferUtils.createFloatBuffer(9);
colorBufferVAO.put(new float[]{1,0,0, 0,1,0, 0,0,1});
colorBufferVAO.flip();
int vaoID = GL30.glGenVertexArrays();
GL30.glBindVertexArray(vaoID);
{
int vertHandle = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertHandle);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexBufferVAO, GL15.GL_STATIC_DRAW);
GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0);
int colorHandle = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, colorHandle);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, colorBufferVAO, GL15.GL_STATIC_DRAW);
GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, 0, 0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
GL30.glBindVertexArray(0);
// =================== VAO Setup ========================
// ===============================================================================================
while ( glfwWindowShouldClose(window) == GL_FALSE ) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Run Cycles
input();
GL20.glUseProgram(programID);
GL30.glBindVertexArray(vaoID);
{
GL20.glEnableVertexAttribArray(0);
GL20.glEnableVertexAttribArray(1);
GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
}
GL30.glBindVertexArray(0);
GL20.glUseProgram(0);
// Display Buffer swap
glfwSwapBuffers(window);
}
// Release window and window call backs
glfwDestroyWindow(window);
keyCallback.release();
exit();
}
private void input() {
glfwPollEvents();
Tasker.executeASyncTask("GLFW_MAIN_THREAD");
}
public void exit() {
// Terminate GLFW and release the GLFWerrorfun
glfwTerminate();
errorCallback.release();
System.exit(1);
}
public static void main(String[] args) {
Test test = new Test();
test.initGL();
test.gameStart();
}
}
Shader class.
public class Shader {
public static CharSequence loadShader(String path) {
StringBuilder shaderSource = new StringBuilder();
int shaderID = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
while ((line = reader.readLine()) != null) {
shaderSource.append(line).append("\n");
}
reader.close();
} catch (IOException e) {
System.err.println("Could not read file.");
e.printStackTrace();
System.exit(-1);
}
return shaderSource;
}
}
Vertex and fragment shaders.
// Vertex Shader
#version 400
in vec3 position;
in vec3 color;
out vec3 Color;
void main()
{
Color = color;
gl_Position = vec4(position, 1.0);
}
// Fragment shader
#version 400
in vec3 Color;
out vec4 fragColor;
void main()
{
fragColor = vec4(Color, 1.0);
}
I found the solution to the problem using this site here. The issue is that I was not using device coordinates as said in the link. Instead I was Using the cartesian coordinate system.
The fix.
FloatBuffer vertexBufferVAO = BufferUtils.createFloatBuffer(9);
**vertexBufferVAO.put(new float[]{{-0.95f,-0.95f,0, -0.5f,-0.95f,0, -0.95f,-0.5f,0});
vertexBufferVAO.flip();

Testing out some LWJGL OpenGL, won't make box. What should I do?

Had this working on OpenGL ES 1.0 & 2.0.
Goal: Make a box, then display it
Won't work with LWJGL on Win 7. Loads a green box (as it should), and then starts to display a bunch of really thick white lines that won't stay as a box. There is a lot of flickering. Here is a picture.
Here is the code for windows.
Main.java
package play.box;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
public class Main {
public static final boolean VSYNC = true;
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final boolean FULLSCREEN = false;
protected boolean running = false;
public static void main(String[] args) {
try {
start();
} catch (LWJGLException e) {
e.printStackTrace();
}
}
public static void start() throws LWJGLException {
Display.setTitle("Display example");
Display.setResizable(false);
Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
Display.setVSyncEnabled(VSYNC);
Display.setFullscreen(FULLSCREEN);
Display.create();
// Setup OpenGL
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(-3, 3, -2, 2, -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
new Renderer().run();
}
}
Renderer.java
package play.box;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
public class Renderer implements Runnable {
public Renderer() {
}
#Override
public void run() {
while(!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT);
GL11.glClearColor(0.0f, 0.5f, 0.0f, 1.0f);
// Rendering //
/*GL11.glBegin(GL11.GL_TRIANGLES);
GL11.glColor3f(1.0f, 0.0f, 0.0f);
GL11.glVertex2f(0.0f, 1.0f);
GL11.glColor3f(1.0f, 0.0f, 0.0f);
GL11.glVertex2f(1.0f, 1.0f);
GL11.glColor3f(1.0f, 0.0f, 0.0f);
GL11.glVertex2f(1.0f, -1.0f);
GL11.glEnd();*/
Box box = new Box();
box.draw();
// End of Rendering //
Display.update();
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Box.java
package play.box;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import org.lwjgl.opengl.GL11;
public class Box {
private float verticies[] = {
-1.0f, 1.0f, // Left Top (0)
-1.0f, -1.0f, // Left Bottom (1)
1.0f, -1.0f, // Right Bottom (2)
1.0f, 1.0f // Right Top (4)
};
private short indicies[] = {
0, 1, 2,
2, 3, 0
};
private FloatBuffer vertBuff;
private ShortBuffer indexBuff;
public Box() {
this.setupBuffers();
}
private void setupBuffers() {
ByteBuffer bBuff = ByteBuffer.allocateDirect(this.verticies.length * 4);
bBuff.order(ByteOrder.nativeOrder());
this.vertBuff = bBuff.asFloatBuffer();
this.vertBuff.put(this.verticies);
this.vertBuff.position(0);
ByteBuffer pbBuff = ByteBuffer.allocateDirect(this.indicies.length * 2);
pbBuff.order(ByteOrder.nativeOrder());
this.indexBuff = pbBuff.asShortBuffer();
this.indexBuff.put(this.indicies);
this.indexBuff.position(0);
}
public void draw() {
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GL11.glVertexPointer(2, GL11.GL_FLOAT, this.vertBuff);
GL11.glDrawElements(GL11.GL_TRIANGLES, this.indexBuff);
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
}
}
Updated Code:
package play.box;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
public class Box {
private float verticies[] = {
-1.0f, 1.0f, // Left Top (0)
-1.0f, -1.0f, // Left Bottom (1)
1.0f, -1.0f, // Right Bottom (2)
1.0f, 1.0f // Right Top (4)
};
private short indicies[] = {
0, 1, 2,
2, 3, 0
};
private FloatBuffer vertBuff;
private ShortBuffer indexBuff;
private int vbo_handle;
private int ibo_handle;
private int vao_handle;
private String vShaderStr =
"attribute vec4 vPosition; \n"
+ "void main() { \n"
+ " gl_Position = vPosition;\n"
+ "} \n";
private String fShaderStr =
"precision mediump float; \n"
+ "void main() { \n"
+ " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n"
+ "} \n";
private int vertexShader;
private int fragmentShader;
private int programObject;
public Box() {
}
public void create() {
ByteBuffer bBuff = ByteBuffer.allocateDirect(this.verticies.length * 4);
bBuff.order(ByteOrder.nativeOrder());
this.vertBuff = bBuff.asFloatBuffer();
this.vertBuff.put(this.verticies);
//this.vertBuff.flip();
this.vertBuff.position(0);
ByteBuffer pbBuff = ByteBuffer.allocateDirect(this.indicies.length * 2);
pbBuff.order(ByteOrder.nativeOrder());
this.indexBuff = pbBuff.asShortBuffer();
this.indexBuff.put(this.indicies);
//this.indexBuff.flip();
this.indexBuff.position(0);
// Create VBO
this.vbo_handle = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, this.vbo_handle);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, this.vertBuff, GL15.GL_DYNAMIC_DRAW);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
// Create IBO
this.ibo_handle = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, this.ibo_handle);
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, this.indexBuff, GL15.GL_DYNAMIC_DRAW);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
// Create VAO
this.vao_handle = GL30.glGenVertexArrays();
GL30.glBindVertexArray(vao_handle);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo_handle);
GL20.glEnableVertexAttribArray(0);
GL20.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, 0, 0);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, ibo_handle);
GL30.glBindVertexArray(0);
// Setup Shaders
this.vertexShader = this.loadShader(GL20.GL_VERTEX_SHADER, this.vShaderStr);
this.fragmentShader = this.loadShader(GL20.GL_FRAGMENT_SHADER, this.fShaderStr);
// Setup Program
int program = GL20.glCreateProgram();
if(program == 0) {
return;
}
GL20.glAttachShader(program, this.vertexShader);
GL20.glAttachShader(program, this.fragmentShader);
GL20.glBindAttribLocation(program, 0, "vPosition");
GL20.glLinkProgram(program);
if(GL20.glGetProgrami(program, GL20.GL_LINK_STATUS) == 0) {
System.out.println("Error Creating Program: " + GL20.glGetProgramInfoLog(program, Integer.MAX_VALUE));
GL20.glDeleteProgram(program);
return;
}
this.programObject = program;
}
public void draw() {
this.create();
GL20.glUseProgram(this.programObject);
GL30.glBindVertexArray(vao_handle);
GL11.glDrawElements(GL11.GL_TRIANGLES, 2, GL11.GL_FLOAT, 0);
GL30.glBindVertexArray(0);
this.dispose();
}
public void draw(boolean useVAO) {
if(useVAO) {
this.draw();
} else {
this.create();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, this.vbo_handle);
GL11.glVertexPointer(2, GL11.GL_FLOAT, 0, 0L);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, this.ibo_handle);
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GL11.glDrawElements(GL11.GL_TRIANGLES, this.indicies.length, GL11.GL_UNSIGNED_SHORT, 0L);
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
this.dispose();
}
}
public void dispose() {
GL30.glDeleteVertexArrays(vao_handle);
GL30.glDeleteVertexArrays(vbo_handle);
GL30.glDeleteVertexArrays(ibo_handle);
this.vao_handle = -1;
this.vbo_handle = -1;
this.ibo_handle = -1;
}
private int loadShader(int type, String shaderSrc) {
int shader;
shader = GL20.glCreateShader(type);
if(shader == 0) {
return 0;
}
GL20.glShaderSource(shader, shaderSrc);
GL20.glCompileShader(shader);
if(GL20.glGetShaderi(shader, GL20.GL_COMPILE_STATUS) == 0) {
System.out.println("Error Loading Shader: " + GL20.glGetShaderInfoLog(shader, Integer.MAX_VALUE));
GL20.glDeleteShader(shader);
return 0;
}
return shader;
}
}
Instead of just showing you what you asked for in the comments, I will demonstrate how you create, render and dispose a VAO using a VBO and IBO.
VAO <=> Vertex Array Object
VBO <=> Vertex Buffer Object
IBO <=> Index Buffer Object
Creating VAO, VBO & IBO
The vao_handle, vbo_handle and ibo_handle is 3 integers containing the id/handle, these 3 variables are used in the whole following code.
vbo_data <=> FloatBuffer containing the vertices
ibo_data <=> IntBuffer containing the indices
The two above variables are used in the following code.
// Creating the VBO
vbo_handle = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
glBufferData(GL_ARRAY_BUFFER, vbo_data, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Creating the IBO
ibo_handle = glGenBuffers();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_handle );
glBufferData(GL_ELEMENT_ARRAY_BUFFER, ibo_data, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// Creating the VAO
vao_handle = glGenVertexArrays();
glBindVertexArray(vao_handle);
glBindBuffer(GL_ARRAY_BUFFER, vbo_handle);
glEnableVertexAttribArray(INDEX); // Place your own INDEX value in the parenthesis
glVertexAttribPointer(INDEX, SIZE, TYPE, NORMALIZED, STRIDE, OFFSET); // Replace all the VARIABLES with the values which fit to your VAO, VBO and IBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_handle);
glBindVertexArray(0);
/*
* Remember that the INDEX given in the
* glEnableVertexAttribArray() and in
* glVertexAttribPointer() is the same
* INDEX used in Shaders (GLSL)
*
* If the INDEX is 0 then in GLSL it
* should look like this
* GLSL: layout(location = 0) in vec3 position;
*
* ^ we can ignore this if you aren't
* using Shaders, though keep it in mind
* since we might need it in the future
*/
Rendering VAO
glBindVertexArray(vao_handle);
glDrawElements(MODE, SIZE, TYPE, OFFSET); // Again replace the variables, so it fits to your VAO, VBO and IBO
glBindVertexArray(0);
Dispose VAO, VBO & IBO
This is how you delete the different buffers, which is a good thing to do, when you close the program or if at some point you don't need them anymore.
glDeleteVertexArrays(vao_handle); // Deletes the VAO
glDeleteBuffers(vbo_handle); // Deletes the VBO
glDeleteBuffers(ibo_handle); // Deletes the IBO
vao_handle = -1;
vbo_handle = -1;
ibo_handle = -1;

2D rendering with VBO in lwjgl won't draw

I'm working on a 2D game in LWJGL. I have successfully rendered QUADS with textures using glBegin but moving to VBOs turned out to be a big undertaking. At the moment I can switch between the vbo and non-vbo rendering with a boolean, both using the same vertex- and texture coordinates. The VBO-implementation won't draw anything onto the screen. Can anyone point me in the right direction?
This is my initialization:
public void init() {
VBOID = VBOHandler.createVBOID();
TBOID = VBOHandler.createVBOID();
float[] vdata = {0, 0,
width, 0,
width, height,
0, height};
float[] tdata = {sx, sy,
ex, sy,
ex, ey,
sx, ey};
//Texture coordinates: (0,0)(1,0)(1,1) and (0,1)
FloatBuffer fb = BufferUtils.createFloatBuffer(8);
fb.put(vdata);
VBOHandler.bufferData(VBOID, fb);
fb = BufferUtils.createFloatBuffer(8);
fb.put(tdata);
VBOHandler.bufferData(TBOID, fb);
}
And here is my rendering code:
private void render() {
texture.bind();
if(vbo) {
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
VBOHandler.bindBuffer(VBOID);
GL11.glVertexPointer(2, GL11.GL_FLOAT, 0, 0);
VBOHandler.bindBuffer(TBOID);
GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
VBOHandler.bindElementBuffer(VBOHandler.getDefaultIBOID());
// I figured why not use a standard IBO for all my sprite drawing
// The default IBO ID is initialized earlier in the program, not shown in this code
GL12.glDrawRangeElements(GL11.GL_TRIANGLE_FAN, 0, 3, 4, GL11.GL_UNSIGNED_SHORT, 0);
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
} else {
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
GL11.glTexCoord2f(sx, sy);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(ex, sy);
GL11.glVertex2f(width,0);
GL11.glTexCoord2f(ex, ey);
GL11.glVertex2f(width, height);
GL11.glTexCoord2f(sx, ey);
GL11.glVertex2f(0, height);
GL11.glEnd();
}
}
And the VBOHandler class, for those interested
public class VBOHandler {
private static int IBOID;
public static void initDefaultIBO() {
IBOID = createVBOID();
short[] indexdata = {0, 1, 2, 3};
ShortBuffer shortBuffer = BufferUtils.createShortBuffer(4);
shortBuffer.put(indexdata);
VBOHandler.bufferElementData(IBOID, shortBuffer);
}
public static int getDefaultIBOID() {
return IBOID;
}
public static int createVBOID() {
if(GLContext.getCapabilities().GL_ARB_vertex_buffer_object) {
return ARBVertexBufferObject.glGenBuffersARB();
}
return 0;
}
public static void bufferData(int id, FloatBuffer buffer) {
if (GLContext.getCapabilities().GL_ARB_vertex_buffer_object) {
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, id);
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, buffer, ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
public static void bufferElementData(int id, ShortBuffer buffer) {
if (GLContext.getCapabilities().GL_ARB_vertex_buffer_object) {
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ELEMENT_ARRAY_BUFFER_ARB, id);
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ELEMENT_ARRAY_BUFFER_ARB, buffer, ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
public static void bindBuffer(int id) {
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, id);
}
public static void bindElementBuffer(int id) {
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ELEMENT_ARRAY_BUFFER_ARB, id);
}
}
The above render-function lies within my Sprite class. It is called by my GameView every frame as so:
public void renderGame() {
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
sprite.render();
}
The GameView is initialized with the following code:
Display.setDisplayMode(new DisplayMode(1024, 768));
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glEnable(GL11.GL_BLEND); // enable alpha blending
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(x - width/2, x + width/2, y + height / 2, y - height / 2, -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
You did not call 'flip' on the FloatBuffers before passing them to OpenGL. You need to call 'flip()' on FloatBuffers before you pass them to OpenGL, or it will not be able to read them. It is worth noting that you cannot read the FloatBuffers after you call 'flip()' yourself.

Java OpenGL Vertex Buffer Objects not working

I tried to implement Open GLs Vertex Buffer Objects the first time, and all i get is a black screen.
I tried it with glOrtho instead of glPerspective, but it didnt work as well.
thanks for helping
Heres my code:
public class VBufferTest {
public static final int WIN_WIDTH = 640;
public static final int WIN_HEIGHT = 480;
public int vBufferId;
public static void main(String args[]){
VBufferTest foo = new VBufferTest();
foo.initLWJGLFrame();
foo.initBuffer();
while (!Display.isCloseRequested()){
foo.render();
}
}
public void initLWJGLFrame(){
try {
DisplayMode[] possible = Display.getAvailableDisplayModes();
DisplayMode chosen = null;
for (int i = 0; i < possible.length; i += 1){
if (possible[i].getWidth() == WIN_WIDTH && possible[i].getHeight() == WIN_HEIGHT){
chosen = possible[i];
break;
}
}
if (chosen != null){
Display.setDisplayMode(chosen);
Display.setTitle("TestFrame1");
Display.create();
}
else {
throw new LWJGLException("Couldn't find the appropriate display mode.");
}
}
catch (LWJGLException e){
}
}
public void initGL(){
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
GL11.glClearColor(104.f/255.0f, 136.0f/255.0f, 252.0f/255.0f, 1.0f);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GLU.gluPerspective(50.0f, Display.getDisplayMode().getWidth()/Display.getDisplayMode().getHeight(), 0.5f, 1000.0f);
GL11.glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
}
public void initBuffer(){
FloatBuffer vertices = BufferUtils.createFloatBuffer(4*3);
vBufferId = genNewId();
vertices.put(new float[]{-1.0f, -1.0f, 0.0f});
vertices.put(new float[]{1.0f, -1.0f, 0.0f});
vertices.put(new float[]{1.0f, 1.0f, 0.0f});
vertices.put(new float[]{-1.0f, 1.0f, 0.0f});
vertices.flip();
bufferData(vBufferId, vertices);
}
public void render(){
GL11.glColor3f(1.0f, 0.0f, 1.0f);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, this.vBufferId);
GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
GL11.glDrawArrays(GL11.GL_QUADS, 0, 4);
Display.update();
}
public static int genNewId(){
IntBuffer buffer = BufferUtils.createIntBuffer(1);
ARBVertexBufferObject.glGenBuffersARB(buffer);
return buffer.get(0);
}
public static void bufferData(int id, FloatBuffer buffer){
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, id);
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, buffer, ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
You have depth-testing enabled, but you don't clear the z-buffer once per frame using glClear (at the beginning of your render method). Same for clearing the color buffer.
EDIT: Also, initGl() seems to be never called?

Categories