Nick Ellas
Nick Ellas

Reputation: 97

LWJGL Matrix Stack Unexpected Behaviour

I wrote a simple class for matrix operations that was ported from C++ OpenGL to Java with LWJGL. However I have observed some odd behaviour that shouldn't occur at all. My pushMatrix() and popMatrix() seem to do nothing at all. When I run this code, the model I display will float off to the right of the screen. It should not move at all after translated because I pushed and popped the matrix stack. Here is my MatrixManager class:

private static Stack<Matrix4f> stack = new Stack<Matrix4f>();
public static void pushMatrix()
{
    stack.push(stack.peek());
}

public static void popMatrix()
{
    stack.pop();
}
public static Matrix4f getTop()
{
    return stack.peek();
}

public static void setTop(Matrix4f m)
{
    stack.set(stack.size()-1, m);
}

public static void multiplyTop(Matrix4f m)
{
    stack.set(stack.size()-1, Matrix4f.mul(stack.peek(), m,null));
}

public static void SendToGLSL()
{

    stack.peek().store(modelBuf);
    modelBuf.flip();
    //viewBuf.flip();
    //projectionBuf.flip();


    //GL20.glUniformMatrix4(matrixlocations[0], false, modelBuf);
    //GL20.glUniformMatrix4(matrixlocations[1], false, viewBuf);
    //GL20.glUniformMatrix4(matrixlocations[2], false, projectionBuf);
    GL20.glUniformMatrix4(matrixlocations[3], false, modelBuf);
}

And the code in question:

protected void renderTileEntityDirt(TileEntityDirt t)
{
    MatrixManager.pushMatrix();

    MatrixManager.multiplyTop(MatrixManager.getTop().translate(new Vector3f(t.posX,t.posY,t.posZ)));

    MatrixManager.SendToGLSL();
    Model.BindModelDataToRender(t.getClass());
    Main.renderEngine.bindTexture(TextureResource.getTexture("dirt"));
    Model.RenderModel(t.getClass());
    MatrixManager.popMatrix();
}

modelBuf is just a FloatBuffer. matrixLocations[0] is the the matrix I use in GLSL.

Upvotes: 1

Views: 230

Answers (1)

SDLeffler
SDLeffler

Reputation: 585

When you write:

stack.push(stack.peek());

you push the pointer for the matrix returned from stack.peek(); when you modify either of the two, it goes to the same slot in memory. e.g. When you modify the top of the stack, the second element is modified as well. Try:

stack.push(new Matrix4f(stack.peek()));

I had a similar problem working with JBox2D Vec2 at one point.

Upvotes: 2

Related Questions