Search code examples
java3d2dlwjgl

Java LWJGL OpenGL 3 convert 3d point to 2d point


I'm trying to convert a 3d vector to a 2d vector in LWJGL 3. The goal is to render a nametag on the 2d screen while moving in a 3d world.

this is what I've used on LWJGL 2:

public static Vector2d to2D(double x, double y, double z) {
    FloatBuffer screenCoords = BufferUtils.createFloatBuffer(3);
    IntBuffer viewport = BufferUtils.createIntBuffer(16);
    FloatBuffer modelView = BufferUtils.createFloatBuffer(16);
    FloatBuffer projection = BufferUtils.createFloatBuffer(16);

    GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, modelView);
    GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projection);
    GL11.glGetInteger(GL11.GL_VIEWPORT, viewport);

    boolean result = GLU.gluProject((float) x, (float) y, (float) z, modelView, projection, viewport, screenCoords);
    if (result) {
        return new Vector2d(screenCoords.get(0), Display.getHeight() - screenCoords.get(1));
    }
    return null;
}

In LWJGL 2 it was doable using GLU.gluProject() which is now removed, is there any alternative in the new LWJGL version?


Solution

  • You can use JOML (which is also downloadable as an LWJGL 3 Addon) and its Matrix4f.project() method for this. The following is a functioning port of your shown code snippet for LWJGL3 + JOML:

    import java.nio.*;
    import org.joml.*;
    import org.lwjgl.opengl.GL11;
    import org.lwjgl.system.MemoryStack;
    public class Snippet {
        public static Vector2d to2D(double x, double y, double z, int displayHeight) {
            Vector3f screenCoords = new Vector3f();
            int[] viewport = new int[4];
            try (MemoryStack stack = MemoryStack.stackPush()) {
                FloatBuffer modelView = stack.mallocFloat(16);
                FloatBuffer projection = stack.mallocFloat(16);
                GL11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelView);
                GL11.glGetFloatv(GL11.GL_PROJECTION_MATRIX, projection);
                GL11.glGetIntegerv(GL11.GL_VIEWPORT, viewport);
                new Matrix4f(projection)
                    .mul(new Matrix4f(modelView))
                    .project((float) x, (float) y, (float) z, viewport, screenCoords);
            }
            return new Vector2d(screenCoords.x, displayHeight - screenCoords.y);
        }
    }
    

    On top of the port, I've also followed best practices regarding native memory management in LWJGL 3: https://blog.lwjgl.org/memory-management-in-lwjgl-3/#strategy5