G
G
Grigory Dikiy2016-11-17 16:11:45
C++ / C#
Grigory Dikiy, 2016-11-17 16:11:45

Determining mouse coordinate in OpenGL world area?

Good afternoon! I'm trying to get the coordinates of a point in the scene. For this I use this tutorial . For this, the MousePicker class was developed:

#include "../../headers/renderEngine/MousePicker.h"
#include "../../headers/toolbox/Math.h"

MousePicker::MousePicker(Camera *camera, glm::mat4 projectionMatrix)
{
    this->camera = camera;
    this->projectionMatrix = projectionMatrix;
    this->viewMatrix = Math::CreateViewMatrix(camera->getCameraPos(), camera->getCameraFront(), camera->getCameraUp());
}

void MousePicker::Update(Camera * camera)
{
    this->camera = camera;
    this->viewMatrix = Math::CreateViewMatrix(camera->getCameraPos(), camera->getCameraFront(), camera->getCameraUp());
    currentRay = CalculateMouseRay();
}

glm::vec3 MousePicker::GetCurrentRay()
{
    return currentRay;
}

glm::vec3 MousePicker::CalculateMouseRay()
{
    glm::vec3 result;
    int mouseX, mouseY;

    SDL_GetMouseState(&mouseX, &mouseY);

    glm::vec2 normalizedCoords = GetNormalizedDeviceCoords(mouseX, mouseY);
    glm::vec4 clipCoords = glm::vec4(normalizedCoords.x, normalizedCoords.y, -1.0f, 1.0f);
    glm::vec4 eyeCoords = ToEyeCoords(clipCoords);

    result = ToWorldCoords(eyeCoords);

    return result;
}

glm::vec2 MousePicker::GetNormalizedDeviceCoords(int mouseX, int mouseY)
{
    float x = (2.0f * mouseX) / 800.0f - 1;
    float y = 1.0f - (2.0f * mouseY) / 600.0f;

    return glm::vec2(x, y);
}

glm::vec4 MousePicker::ToEyeCoords(glm::vec4 clipCoords)
{
    glm::vec4 eyeCoords = glm::inverse(projectionMatrix) * clipCoords;
    eyeCoords = glm::vec4(eyeCoords.x, eyeCoords.y, -1.0f, 0.0f);

    return eyeCoords;
}

glm::vec3 MousePicker::ToWorldCoords(glm::vec4 eyeCoords)
{
    glm::vec4 worldCoords = glm::inverse(viewMatrix) * eyeCoords;
    glm::vec3 world = glm::vec3(worldCoords.x, worldCoords.y, worldCoords.z);

    return glm::normalize(world);
}

As a result, I got that on the x-axis and everything works well, but on the z-axis, minimal deviations are obtained, although in theory they should be large since the foreground is set as 0.1f and the back is 100f , and the deviations fluctuate around -1. What could be wrong? (I would appreciate your help)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question