Main Menu

Ray Picking

Started by zFollette, January 25, 2014, 01:06:53

Previous topic - Next topic

zFollette

First off, sorry for posting many topics. Now, to the question: I am trying to implement Ray Picking into my 3D Project using the gluUnproject method, though I am getting some odd results so far.

Here is the code I am using.

private void pick() {
        float[] matModelView = new float[16], matProjView = new float[16];
        int[] view = new int[16];
        int mouseX = Mouse.getX();
        int mouseY = Mouse.getY();
        Vector3f start = new Vector3f();
        Vector3f end = new Vector3f();

        FloatBuffer modelBuffer = compileBuffer(matModelView);
        FloatBuffer projBuffer = compileBuffer(matProjView);
        FloatBuffer startBuffer = compileBuffer(new float[]{start.x, start.y, start.z, 1});
        FloatBuffer endBuffer = compileBuffer(new float[]{end.x, end.y, end.z, 1});
        IntBuffer viewBuffer = compileBuffer(view);

        glGetFloat(GL_MODELVIEW_MATRIX, modelBuffer);
        glGetFloat(GL_PROJECTION_MATRIX, projBuffer);
        glGetInteger(GL_VIEWPORT, viewBuffer);

        float winX = (float) mouseX;
        float winY = view[2] - (float) mouseY;

        gluUnProject(winX, winY, 0.0f, modelBuffer, projBuffer, viewBuffer, startBuffer);
        gluUnProject(winX, winY, 1.0f, modelBuffer, projBuffer, viewBuffer, endBuffer);

        start = new Vector3f(startBuffer.get(0), startBuffer.get(1), startBuffer.get(2));
        end = new Vector3f(endBuffer.get(0), endBuffer.get(1), endBuffer.get(2));

        picks.add(new Vector3f[]{start, end});

        System.out.println("Mouse Coords: " + mouseX + ", " + mouseY);
        System.out.println("Position: " + position.x + ", " + position.y + ", " + position.z);
        System.out.println("Rotation: " + rotation.x + ", " + rotation.y + ", " + rotation.z);
        System.out.println("Near Plane: " + start.x + ", " + start.y + ", " + start.z);
        System.out.println("Far Plane: " + end.x + ", " + end.y + ", " + end.z);
    }


Here is an example output:
Mouse Coords: 398, 344
Position: -0.5, -2.1, 0.5
Rotation: 0.0, 0.0, 0.0
Near Plane: 0.4998519, 2.0412652, -0.6
Far Plane: 0.35189778, -56.633606, -100.49771


And here is what that ray looks like:


I am puzzled because the code I am using matches the tutorials I have been following. If it helps, here are my compileBuffer functions.

private FloatBuffer compileBuffer(float[] floats) {
        FloatBuffer buffer = BufferUtils.createFloatBuffer(floats.length);
        buffer.put(floats);
        buffer.flip();
        return buffer;
    }

    private IntBuffer compileBuffer(int[] ints) {
        IntBuffer buffer = BufferUtils.createIntBuffer(ints.length);
        buffer.put(ints);
        buffer.flip();
        return buffer;
    }


Can someone can explain to me what I am doing wrong?